Skip to content

Conversation

@satococoa
Copy link
Owner

@satococoa satococoa commented Oct 29, 2025

Summary

Fixes #29 - Improves readability of wtp list output on very wide terminals by adding width control options.

Changes

  • Added --compact flag (-c) to minimize column widths for narrow or redirected output
  • Added --max-path-width flag to cap PATH column width (default: 56 characters)
  • Added WTP_LIST_MAX_PATH environment variable for customizing the default cap
  • Auto-enable compact mode when output is redirected (non-TTY)
  • Auto-enable compact mode on super-wide terminals (≥160 columns)
  • Prevents excessive padding in PATH column while maintaining alignment

Testing

  • All existing tests pass
  • Added 5 new test cases:
    • TestListCommand_PathColumnCappedOnWideTerminals
    • TestListCommand_AutoCompactForSuperWideTerminals
    • TestListCommand_AutoCompactForNonTTY
    • TestListCommand_CompactFlag
    • TestListCommand_CustomMaxPathWidth

Examples

Before (very wide terminal)

PATH                                                                              BRANCH         STATUS     HEAD
----                                                                              ------         ------     ----
@                                                                                 main           managed    abc12345
feature/test                                                                      feature/test   managed    def67890

After (same wide terminal, automatic compact)

PATH          BRANCH         STATUS     HEAD
----          ------         ------     ----
@             main           managed    abc12345
feature/test  feature/test   managed    def67890

With custom width cap

wtp list --max-path-width 30
# or
export WTP_LIST_MAX_PATH=30
wtp list

Backward Compatibility

  • Default behavior unchanged for normal terminal widths (<160 columns)
  • All existing flags and output formats remain compatible
  • Compact mode is opt-in via flag or automatically applied when beneficial

Summary by CodeRabbit

  • New Features

    • Added --compact (-c) and --max-path-width flags and WTP_LIST_MAX_PATH env var to control list display
  • Improvements

    • Automatic terminal-width detection with dynamic column sizing, path truncation, and auto-compact behavior for very wide or non‑TTY outputs
    • Column width clamping to ensure readable PATH/BRANCH/STATUS presentation while preserving quiet-mode behavior
  • Tests

    • Added display-focused tests for column sizing, compact mode, non‑TTY behavior, and custom max-path overrides

- Add --compact flag to minimize column widths
- Add --max-path-width flag to cap PATH column width (default: 56)
- Support WTP_LIST_MAX_PATH environment variable
- Auto-enable compact mode on non-TTY output (pipes, redirects)
- Auto-enable compact mode on super-wide terminals (≥160 columns)
- Improve readability on very wide terminals by preventing excessive padding

Closes #29
Copilot AI review requested due to automatic review settings October 29, 2025 15:59
@coderabbitai
Copy link

coderabbitai bot commented Oct 29, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds width-aware rendering to wtp list: new flags --compact/-c and --max-path-width, environment override WTP_LIST_MAX_PATH, terminal/TTY detection, column-width calculation and clamping, truncation logic, and propagation of display options into list rendering and tests.

Changes

Cohort / File(s) Summary
List command display customization
cmd/wtp/list.go
Adds listDisplayOptions and resolveListDisplayOptions; new flags --compact/-c, --max-path-width; constants (defaultMaxPathWidth, superWideThreshold, pathPadding, minPathWidth, columnSpacing); threads opts through listCommandWithCommandExecutor; implements width-aware rendering (listDisplayData, listColumnMetrics, collectListDisplayData, computeListColumnWidths, derivePathWidth, clamping helpers, truncation/formatting helpers); updates displayWorktreesRelative to accept termWidth and opts.
List command tests and helpers
cmd/wtp/list_test.go
Adds defaultListDisplayOptionsForTests() and extractPathColumnWidth() helpers; updates tests to pass display options into listCommandWithCommandExecutor; adds tests for path column capping, auto-compact on super-wide terminals and non-TTY, --compact interaction, and custom --max-path-width; imports fmt.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant CLI
    participant Cmd as listCommandWithCommandExecutor
    participant Resolver as resolveListDisplayOptions
    participant Renderer as displayWorktreesRelative

    CLI->>Cmd: run `wtp list` (flags/env)
    Cmd->>Resolver: derive options (flags, WTP_LIST_MAX_PATH, detect TTY & term width)
    Resolver->>Resolver: parse values, detect terminal width
    Resolver-->>Cmd: return listDisplayOptions + termWidth
    Cmd->>Renderer: render worktrees with termWidth + opts
    Renderer->>Renderer: collectListDisplayData()
    Renderer->>Renderer: computeListColumnWidths() and clamp widths
    Renderer->>Renderer: format rows (truncate PATH/BRANCH/STATUS)
    Renderer-->>Cmd: formatted output
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Areas needing extra attention:
    • Terminal width detection and TTY detection / fallback behavior in resolveListDisplayOptions.
    • Precedence between environment WTP_LIST_MAX_PATH and --max-path-width.
    • Auto-compact trigger (superWideThreshold) vs explicit --compact handling.
    • Column width computation, clamping logic, and truncation correctness across edge cases.
    • Tests updated to pass display options — ensure test harness matches runtime behavior.

Possibly related PRs

Suggested reviewers

  • ox

Poem

🐰
I hopped the terminal, measured fur and seam,
I trimmed long paths so rows stay neat and lean.
Flags and env clues tell this rabbit how to fold,
I compact, clamp, and print each tale untold.
A tiny hop to make list output clean 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 17.65% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "feat: add width controls for list command output" directly reflects the primary changes in the changeset. The implementation introduces width control mechanisms for the list command including the --compact and --max-path-width flags, environment variable configuration, and width-aware rendering logic. The title is concise, clear, and specific enough that a teammate reviewing the history would immediately understand the purpose of the changes.
Linked Issues Check ✅ Passed The changeset addresses all coding requirements from the linked issue #29. The implementation provides user-configurable width limits through the --compact flag and --max-path-width flag [#29], supports the WTP_LIST_MAX_PATH environment variable for customization [#29], implements width-aware rendering with truncation to reduce excessive spacing [#29], and introduces adaptive behavior that auto-enables compact mode for non-TTY output and super-wide terminals (≥160 columns) [#29]. The changes include appropriate test coverage with five new tests validating the display behavior across different scenarios.
Out of Scope Changes Check ✅ Passed All changes in the pull request are directly scoped to the objectives of issue #29. The modifications to cmd/wtp/list.go implement the width control features, display options resolution, and width-aware rendering for the list command. The modifications to cmd/wtp/list_test.go add necessary test helpers and validation tests for the new display functionality. No unrelated changes or refactoring outside the scope of improving list command output readability on wide terminals are present in this changeset.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/list-width-control

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@satococoa satococoa self-assigned this Oct 29, 2025
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR adds display customization options to the list command, allowing users to control the width of the PATH column and enable compact mode for better readability on various terminal sizes.

  • Introduces --compact and --max-path-width flags for the list command
  • Implements automatic compact mode for non-TTY output and super-wide terminals (>= 160 columns)
  • Adds support for WTP_LIST_MAX_PATH environment variable to set default max path width

Reviewed Changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
cmd/wtp/list.go Adds display options handling, path width calculation logic, and new command flags for compact mode and max path width
cmd/wtp/list_test.go Updates all test calls to include display options and adds comprehensive tests for new display behaviors

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

cmd/wtp/list.go Outdated
Comment on lines 385 to 387
if pathWidth < minCompactWidth {
pathWidth = minCompactWidth
}
Copy link

Copilot AI Oct 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 382-387 are redundant. After line 383 sets pathWidth = minCompactWidth, line 385 checks if pathWidth < minCompactWidth, which can never be true. Lines 385-387 should be removed.

Suggested change
if pathWidth < minCompactWidth {
pathWidth = minCompactWidth
}

Copilot uses AI. Check for mistakes.
cmd/wtp/list.go Outdated
termWidth = 80
}
// If branch column is too wide, limit it as well
maxAvailableForBranch := termWidth - minPathWidth - spacing - maxStatusLen - spacing - spacing - headWidth
Copy link

Copilot AI Oct 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The spacing constant is subtracted three times but written as spacing - spacing - spacing. This should be simplified to (spacing * 3) or (3 * spacing) for clarity and to avoid confusion.

Suggested change
maxAvailableForBranch := termWidth - minPathWidth - spacing - maxStatusLen - spacing - spacing - headWidth
maxAvailableForBranch := termWidth - minPathWidth - (3 * spacing) - maxStatusLen - headWidth

Copilot uses AI. Check for mistakes.
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
cmd/wtp/list.go (1)

345-412: Consider simplifying the width calculation logic.

The path width calculation has multiple conditional branches with overlapping bounds checks that make the logic difficult to follow. For example:

  • Lines 382-387: Sets pathWidth to minCompactWidth, then immediately checks if it's less than minCompactWidth (redundant)
  • Lines 404-412: Performs additional bounds checking that overlaps with earlier constraints
  • Overall flow: calculate → cap → apply mode logic → re-cap → final bounds

While functionally correct, consolidating the bounds checking and reducing branching would improve maintainability. Consider calculating the constraints (min, max, desired) first, then applying them in a single pass.

Example refactoring approach:

// Calculate constraints
minWidth := max(pathHeaderWidth, 1)
maxWidth := min(availableForPath, opts.MaxPathWidth)

// Calculate desired width based on mode
var desiredWidth int
if opts.Compact {
    desiredWidth = max(minWidth, maxPathLen)
} else {
    desiredWidth = max(minPathWidth, maxPathLen+2)
}

// Apply constraints
pathWidth := clamp(desiredWidth, minWidth, maxWidth)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6a8895d and f6c51a0.

📒 Files selected for processing (2)
  • cmd/wtp/list.go (8 hunks)
  • cmd/wtp/list_test.go (18 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
cmd/wtp/list_test.go (2)
internal/command/types.go (2)
  • Result (11-15)
  • Command (4-8)
internal/config/config.go (2)
  • Config (12-16)
  • Defaults (19-21)
🪛 GitHub Check: Lint
cmd/wtp/list_test.go

[failure] 141-141:
The line is 124 characters long, which exceeds the maximum of 120 characters. (lll)


[failure] 210-210:
The line is 124 characters long, which exceeds the maximum of 120 characters. (lll)


[failure] 255-255:
The line is 122 characters long, which exceeds the maximum of 120 characters. (lll)


[failure] 277-277:
The line is 122 characters long, which exceeds the maximum of 120 characters. (lll)


[failure] 338-338:
The line is 124 characters long, which exceeds the maximum of 120 characters. (lll)


[failure] 406-406:
The line is 124 characters long, which exceeds the maximum of 120 characters. (lll)


[failure] 456-456:
The line is 122 characters long, which exceeds the maximum of 120 characters. (lll)


[failure] 487-487:
The line is 122 characters long, which exceeds the maximum of 120 characters. (lll)


[failure] 732-732:
The line is 124 characters long, which exceeds the maximum of 120 characters. (lll)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: CodeQL analysis (go)
🔇 Additional comments (5)
cmd/wtp/list_test.go (2)

18-40: LGTM! Well-designed test helpers.

The defaultListDisplayOptionsForTests() and extractPathColumnWidth() helpers provide consistent test setup and enable verification of the new width control behavior. The approach of extracting the path column width from formatted output is appropriate for validating display formatting.


841-1000: LGTM! Comprehensive test coverage for new display features.

The five new tests thoroughly validate the width control functionality:

  • Path column capping at the default width
  • Auto-compact activation for super-wide terminals (≥160 columns)
  • Auto-compact activation for non-TTY output
  • Explicit --compact flag behavior
  • Custom --max-path-width configuration

The tests appropriately mock terminal width and verify the resulting column widths.

cmd/wtp/list.go (3)

29-32: LGTM! Clean API design for width controls.

The new constants, CLI flags, and listDisplayOptions struct provide a clear and well-documented interface for controlling list output formatting. The default values (max path width of 56, super-wide threshold of 160) are reasonable for typical terminal usage.

Also applies to: 64-73, 441-445


447-472: LGTM! Robust option resolution with proper precedence.

The resolveListDisplayOptions function correctly:

  • Prioritizes CLI flags over environment variables (WTP_LIST_MAX_PATH)
  • Validates that MaxPathWidth is positive
  • Detects TTY status for auto-compact behavior
  • Handles edge cases like invalid environment variable values

The precedence order (CLI flag → env var → default) follows standard CLI conventions.


154-165: LGTM! Appropriate auto-compact behavior.

The auto-compact logic correctly:

  • Enables compact mode automatically for non-TTY output (redirected/piped)
  • Enables compact mode for super-wide terminals (≥160 columns)
  • Respects explicit user choice (only auto-enables when --compact flag wasn't set)

Minor note: Lines 155-157 perform redundant validation already done in resolveListDisplayOptions (lines 456-458), but this defensive check is harmless.

- Extract helper functions to satisfy gocyclo lint rules
- Split displayWorktreesRelative into smaller focused functions
- Add named return values for clarity
- Format long lines to meet lll (120 char) requirement
- Fix clampCompactPathWidth to respect currentWidth properly
- Replace manual if comparisons with built-in min/max functions
- Simplify clampCompactPathWidth and clampExpandedPathWidth
- More readable and idiomatic Go 1.21+ code
@satococoa
Copy link
Owner Author

@codex review

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
cmd/wtp/list.go (1)

402-402: Simplify spacing arithmetic for clarity.

The spacing constant is subtracted three times in a non-contiguous pattern. Grouping the spacing terms makes the intent clearer.

Apply this diff:

-	maxAvailableForBranch := termWidth - minPathWidth - spacing - statusWidth - spacing - spacing - headWidth
+	maxAvailableForBranch := termWidth - minPathWidth - (3 * spacing) - statusWidth - headWidth
🧹 Nitpick comments (1)
cmd/wtp/list.go (1)

421-421: Simplify spacing arithmetic for clarity.

Similar to line 402, the spacing is subtracted three times non-contiguously. Grouping improves readability.

Apply this diff:

-	availableForPath := max(termWidth-spacing-branchWidth-spacing-statusWidth-spacing-headWidth, pathHeaderWidth)
+	availableForPath := max(termWidth-(3*spacing)-branchWidth-statusWidth-headWidth, pathHeaderWidth)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 19ca14d and c5d9d08.

📒 Files selected for processing (1)
  • cmd/wtp/list.go (6 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
cmd/wtp/list.go (1)
cmd/wtp/list_test.go (3)
  • TestListCommand_RelativePathDisplay (582-718)
  • TestListCommand_LongPaths (325-389)
  • TestListCommand_TerminalWidthTruncation (720-814)
🔇 Additional comments (6)
cmd/wtp/list.go (6)

9-9: LGTM! Constants and import are appropriate.

The strconv import and display constants are well-chosen for the width control feature.

Also applies to: 29-33


65-74: LGTM! CLI flags are well-defined.

The new flags provide clear control over display formatting with appropriate defaults and help text.


113-114: LGTM! Display options integration is correct.

The option resolution and auto-compact logic work as intended, providing adaptive behavior for different terminal widths and output types.

Also applies to: 121-121, 126-126, 155-166


276-310: LGTM! Display refactor is well-structured.

The function cleanly separates data collection, width computation, and rendering with appropriate width enforcement via truncation.


312-368: LGTM! Data collection is clean and efficient.

The data structures and collection logic properly track display content and metrics needed for width computation.


454-485: LGTM! Options resolution is robust and well-designed.

The function properly prioritizes CLI flags over environment variables, validates inputs, and safely detects TTY status.

- Move minPathWidth, columnSpacing to package constants
- Remove duplicate const blocks in helper functions
- Single source of truth for layout dimensions
@chatgpt-codex-connector
Copy link

Codex Review: Didn't find any major issues. Can't wait for the next one!

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

- Move MaxPathWidth application after mode-specific width adjustment
- Ensures user-specified width limit is respected
- Fixes --max-path-width flag not taking effect
@satococoa satococoa merged commit 9fcab14 into main Oct 30, 2025
6 of 7 checks passed
@satococoa satococoa deleted the feature/list-width-control branch October 30, 2025 16:44
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
cmd/wtp/list.go (1)

385-389: Duplicate constants still present.

Despite being marked as addressed in a previous review, these local constants duplicate file-level definitions and create inconsistent naming:

  • minPathWidth (line 386) duplicates line 33
  • spacing (line 388) duplicates columnSpacing (line 34) with different naming
  • headWidth (line 387) is redundant with headDisplayLength (line 25)

The function derivePathWidth already uses the file-level constants correctly (lines 417-418). This function should do the same.

Apply this diff to remove the local const block and use file-level constants:

 func clampBranchAndStatusWidths(
 	maxBranchLen, maxStatusLen, termWidth int,
 ) (branchWidth, statusWidth int) {
-	const (
-		minPathWidth = 20
-		headWidth    = headDisplayLength
-		spacing      = 3
-	)
-
 	branchWidth = maxBranchLen
 	statusWidth = maxStatusLen
 
 	branchHeaderWidth := len("BRANCH")
 	statusHeaderWidth := len("STATUS")
 
 	if branchWidth < branchHeaderWidth {
 		branchWidth = branchHeaderWidth
 	}
 	if statusWidth < statusHeaderWidth {
 		statusWidth = statusHeaderWidth
 	}
 
-	maxAvailableForBranch := termWidth - minPathWidth - spacing - statusWidth - spacing - spacing - headWidth
+	maxAvailableForBranch := termWidth - minPathWidth - columnSpacing - statusWidth - columnSpacing - columnSpacing - headDisplayLength
 	if branchWidth > maxAvailableForBranch {
 		branchWidth = maxAvailableForBranch
 		if branchWidth < branchHeaderWidth {
 			branchWidth = branchHeaderWidth
 		}
 	}
 
 	return branchWidth, statusWidth
 }
🧹 Nitpick comments (2)
cmd/wtp/list.go (2)

158-160: Consider removing redundant check.

The resolveListDisplayOptions function (lines 467-469) already ensures opts.MaxPathWidth is never <= 0, so this check is redundant.

Apply this diff to remove the redundant check:

-	if opts.MaxPathWidth <= 0 {
-		opts.MaxPathWidth = defaultMaxPathWidth
-	}

433-434: Consider removing redundant boundary check.

Line 433 already ensures pathWidth >= pathHeaderWidth (which is 4), so the subsequent max(pathWidth, 1) on line 434 is redundant.

Apply this diff to simplify:

 	pathWidth = max(min(pathWidth, availableForPath), pathHeaderWidth)
-	pathWidth = max(pathWidth, 1)
 
 	return pathWidth
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between af27249 and b8bb125.

📒 Files selected for processing (1)
  • cmd/wtp/list.go (6 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
cmd/wtp/list.go (2)
internal/config/config.go (1)
  • Config (12-16)
internal/git/worktree.go (1)
  • Worktree (14-19)
🔇 Additional comments (7)
cmd/wtp/list.go (7)

67-76: LGTM! Well-structured flag definitions.

The new flags are clearly defined with appropriate defaults, aliases, and usage descriptions. The integration with the existing flag structure is clean.


115-123: Clean integration of display options.

The display options are resolved early and propagated cleanly through the command execution flow.


161-167: Auto-enable compact mode logic is correct.

The logic correctly auto-enables compact mode for non-TTY output and super-wide terminals (≥160 columns) as specified in the PR objectives.


280-312: Width-aware rendering is well-implemented.

The rendering logic correctly:

  • Collects display data and metrics
  • Computes appropriate column widths based on terminal size and options
  • Applies truncation to fit content within computed widths
  • Maintains alignment across all rows

314-370: Data collection logic is sound.

The new data structures and collection function provide a clean separation between data gathering and rendering. The metrics tracking correctly captures maximum column widths needed for proper formatting.


415-437: Width derivation logic is well-structured.

The function correctly:

  • Calculates available space
  • Applies appropriate clamping based on compact vs expanded mode
  • Enforces the MaxPathWidth cap
  • Ensures bounds are respected

The separation between compact and expanded clamping logic provides clear, maintainable behavior.


458-483: Display options resolution is robust.

The function correctly:

  • Prioritizes explicit CLI flags over environment variables
  • Safely parses environment variable with error handling
  • Ensures MaxPathWidth is always positive
  • Properly detects TTY status for adaptive behavior

The logic handles all edge cases appropriately.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

wpt list output is inconvenient in wide terminal window

2 participants