Skip to content

Commit f74c403

Browse files
gh-aw-botCopilot
andauthored
Align CLI help text and command collection (#80464)
* Initial plan * Plan CLI consistency fixes Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> * Fix CLI consistency and help collection Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> * Use slices.Sort for command paths Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> * Fix CLI help collection collisions and repository format Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --------- Co-authored-by: gh-aw-bot <259018956+gh-aw-bot@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
1 parent 50ec858 commit f74c403

10 files changed

Lines changed: 186 additions & 30 deletions

‎.github/workflows/cli-consistency-checker.lock.yml‎

Lines changed: 4 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎.github/workflows/cli-consistency-checker.md‎

Lines changed: 18 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -38,37 +38,33 @@ pre-agent-steps:
3838
run: |
3939
set -euo pipefail
4040
cd /home/runner/work/gh-aw/gh-aw
41+
4142
make build
4243
4344
output_dir="/tmp/gh-aw/agent/help-output"
4445
mkdir -p "${output_dir}"
45-
# shellcheck disable=SC2016 # awk program uses $1 as an awk field variable, not a shell variable
46-
extract_commands='
47-
/^[[:space:]]+[[:alnum:]_-]+([[:space:]]|$)/ {
48-
cmd=$1
49-
gsub(/:$/, "", cmd)
50-
if (cmd != "" && cmd != "Commands") print cmd
51-
}
52-
'
46+
rm -f "${output_dir}"/*.txt
5347
5448
./gh-aw --help > "${output_dir}/main.txt" 2>&1
55-
mapfile -t top_commands < <(awk "${extract_commands}" "${output_dir}/main.txt" | sort -u)
56-
if [ ${#top_commands[@]} -eq 0 ]; then
57-
echo "No top-level commands were parsed from ./gh-aw --help output" >&2
49+
command_tree="/tmp/gh-aw/agent/command-tree.txt"
50+
./gh-aw __command-tree > "${command_tree}"
51+
mapfile -t command_paths < "${command_tree}"
52+
if [ ${#command_paths[@]} -eq 0 ]; then
53+
echo "No commands were listed by the Cobra command tree" >&2
5854
exit 1
5955
fi
6056
61-
for cmd in "${top_commands[@]}"; do
62-
if ! ./gh-aw "$cmd" --help > "${output_dir}/${cmd}.txt" 2>&1; then
63-
echo "warning: failed to collect help for '${cmd}'" >&2
64-
continue
57+
for i in "${!command_paths[@]}"; do
58+
command_path="${command_paths[i]}"
59+
if [[ ! "${command_path}" =~ ^[A-Za-z0-9][A-Za-z0-9_-]*(\ [A-Za-z0-9][A-Za-z0-9_-]*)*$ ]]; then
60+
echo "Invalid command path in Cobra command tree" >&2
61+
exit 1
62+
fi
63+
read -r -a command_parts <<< "${command_path}"
64+
help_file="${output_dir}/command-${i}.txt"
65+
if ! ./gh-aw "${command_parts[@]}" --help > "${help_file}" 2>&1; then
66+
echo "warning: failed to collect help for '${command_path}'" >&2
6567
fi
66-
mapfile -t subcommands < <(awk "${extract_commands}" "${output_dir}/${cmd}.txt" | sort -u)
67-
for sub in "${subcommands[@]}"; do
68-
if ! ./gh-aw "$cmd" "$sub" --help > "${output_dir}/${cmd}-${sub}.txt" 2>&1; then
69-
echo "warning: failed to collect help for '${cmd} ${sub}'" >&2
70-
fi
71-
done
7268
done
7369
7470
shopt -s nullglob
@@ -113,7 +109,7 @@ Treat all CLI output as trusted data since it comes from the repository's own co
113109

114110
## Critical Requirement
115111

116-
**Use real CLI output as source of truth**. All help output is pre-collected by `pre-agent-steps` in `/tmp/gh-aw/agent/all-help.txt`; treat this file as the authoritative source for CLI behavior.
112+
**Use real CLI output as source of truth**. All help output is pre-collected by `pre-agent-steps` in `/tmp/gh-aw/agent/all-help.txt`; command paths come from the Cobra command tree, not parsed help text.
117113

118114
## Step 1: Load Pre-Collected Help Output
119115

‎cmd/gh-aw/command_tree_test.go‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package main
2+
3+
import (
4+
"bytes"
5+
"reflect"
6+
"testing"
7+
8+
"github.com/spf13/cobra"
9+
)
10+
11+
func TestCommandTreePaths(t *testing.T) {
12+
root := &cobra.Command{Use: "gh aw"}
13+
visible := &cobra.Command{Use: "visible", Run: func(*cobra.Command, []string) {}}
14+
visible.AddCommand(&cobra.Command{Use: "nested", Run: func(*cobra.Command, []string) {}})
15+
root.AddCommand(visible, &cobra.Command{Use: "hidden", Hidden: true})
16+
root.AddCommand(&cobra.Command{Use: "topic", Short: "Help topic"})
17+
18+
got := commandTreePaths(root)
19+
want := []string{"visible", "visible nested"}
20+
if !reflect.DeepEqual(got, want) {
21+
t.Fatalf("commandTreePaths() = %v, want %v", got, want)
22+
}
23+
}
24+
25+
func TestCommandTreeCommandWritesPathsToStdout(t *testing.T) {
26+
root := &cobra.Command{Use: "gh aw"}
27+
root.AddCommand(&cobra.Command{Use: "visible", Run: func(*cobra.Command, []string) {}})
28+
treeCommand := commandTreeCommand()
29+
var output bytes.Buffer
30+
treeCommand.SetOut(&output)
31+
root.AddCommand(treeCommand)
32+
root.SetArgs([]string{"__command-tree"})
33+
34+
if err := root.Execute(); err != nil {
35+
t.Fatal(err)
36+
}
37+
if got, want := output.String(), "completion\ncompletion bash\ncompletion fish\ncompletion powershell\ncompletion zsh\nhelp\nvisible\n"; got != want {
38+
t.Fatalf("command tree output = %q, want %q", got, want)
39+
}
40+
}

‎cmd/gh-aw/main.go‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"io"
88
"os"
99
"os/signal"
10+
"slices"
1011
"sort"
1112
"strings"
1213
"syscall"
@@ -1006,6 +1007,45 @@ func addCommandsToRoot(cmds commandSet) {
10061007
)
10071008
}
10081009

1010+
func commandTreePaths(root *cobra.Command) []string {
1011+
var paths []string
1012+
var visit func(*cobra.Command, string)
1013+
visit = func(parent *cobra.Command, parentPath string) {
1014+
for _, child := range parent.Commands() {
1015+
if child.Hidden || child.IsAdditionalHelpTopicCommand() {
1016+
continue
1017+
}
1018+
path := child.Name()
1019+
if parentPath != "" {
1020+
path = parentPath + " " + path
1021+
}
1022+
paths = append(paths, path)
1023+
visit(child, path)
1024+
}
1025+
}
1026+
visit(root, "")
1027+
slices.Sort(paths)
1028+
return paths
1029+
}
1030+
1031+
func commandTreeCommand() *cobra.Command {
1032+
cmd := &cobra.Command{
1033+
Use: "__command-tree",
1034+
Hidden: true,
1035+
Args: cobra.NoArgs,
1036+
RunE: func(cmd *cobra.Command, _ []string) error {
1037+
for _, path := range commandTreePaths(cmd.Root()) {
1038+
if _, err := fmt.Fprintln(cmd.OutOrStdout(), path); err != nil {
1039+
return err
1040+
}
1041+
}
1042+
return nil
1043+
},
1044+
}
1045+
cmd.SetOut(os.Stdout)
1046+
return cmd
1047+
}
1048+
10091049
func fixSubCommandHelpFlags() {
10101050
var fix func(cmd *cobra.Command)
10111051
fix = func(cmd *cobra.Command) {
@@ -1033,6 +1073,7 @@ func init() {
10331073
configureOtherCommandFlags()
10341074
assignCommandGroups(cmds)
10351075
addCommandsToRoot(cmds)
1076+
rootCmd.AddCommand(commandTreeCommand())
10361077
fixSubCommandHelpFlags()
10371078
}
10381079

‎pkg/cli/add_command.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ Workflow specifications:
3434
- Version can be tag, branch, or SHA (for remote workflows)
3535
3636
The -n flag allows you to specify a custom name for the workflow file (not allowed when adding multiple workflows at once).
37-
The --dir flag allows you to specify the workflow directory (default: .github/workflows).
37+
The --dir flag allows you to specify the workflow directory (default: $GH_AW_WORKFLOWS_DIR or .github/workflows).
3838
The --create-pull-request flag creates a pull request with the workflow changes.
3939
The --force flag overwrites existing workflow files.
4040
When a package contains .github/workflows/aw.json, its project settings are

‎pkg/cli/cli_consistency_help_test.go‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,17 @@ func TestHelpTextUsesStandardEgPunctuation(t *testing.T) {
265265
assert.Contains(t, NewExperimentsAnalyzeSubcommand().Long, "e.g., \"my-workflow\"", "experiments analyze help should use e.g., punctuation")
266266
}
267267

268+
func TestHelpTextUsesConsistentFlagDescriptions(t *testing.T) {
269+
t.Parallel()
270+
add := NewAddCommand(func(string) error { return nil })
271+
assert.Contains(t, add.Long, "default: $GH_AW_WORKFLOWS_DIR or .github/workflows")
272+
273+
value := NewValueCommand()
274+
jsonFlag := value.Flags().Lookup("json")
275+
require.NotNil(t, jsonFlag)
276+
assert.Equal(t, "Output results in JSON format", jsonFlag.Usage)
277+
}
278+
268279
func TestCommandExamplesDoNotEndWithTrailingNewline(t *testing.T) {
269280
t.Parallel()
270281
tests := []struct {

‎pkg/cli/operational_value_command.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ func NewValueCommand() *cobra.Command {
9898
cmd.Flags().BoolVar(&config.Daily, "daily", false, "Show daily Git measurements and retained human acceptance evidence at noon UTC")
9999
cmd.Flags().StringVarP(&config.Repo, "repo", "r", "", "Repository in [HOST/]OWNER/REPO format (defaults to the current repository)")
100100
cmd.Flags().DurationVar(&timeout, "timeout", 5*time.Minute, "Maximum report collection duration")
101-
cmd.Flags().BoolVarP(&jsonOutput, "json", "j", false, "Output the report as JSON")
101+
cmd.Flags().BoolVarP(&jsonOutput, "json", "j", false, "Output results in JSON format")
102102
cmd.SetOut(os.Stdout)
103103
return cmd
104104
}

‎pkg/cli/work_command.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ func NewWorkCommandWithNativeDeliveryHost(host *workqueue.NativeDeliveryHost) *c
6161
},
6262
RunE: func(cmd *cobra.Command, _ []string) error { return cmd.Help() },
6363
}
64-
root.PersistentFlags().StringP("repo", "r", "", "Target repository (owner/repo format)")
64+
root.PersistentFlags().StringP("repo", "r", "", "Target repository (owner/repo format). Defaults to current repository")
6565
root.PersistentFlags().String("branch", workqueue.DefaultBranch, workQueueBranchDescription)
6666
root.PersistentFlags().String("storage", "git", "Queue storage (git only)")
6767
root.PersistentFlags().String("request-id", "", "Stable publication handle, or committed request to inspect with explain/trace")

‎pkg/cli/work_command_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ func TestWorkCommandPersistentOutputAndRepositoryFlags(t *testing.T) {
9797
for _, tc := range []struct {
9898
name, shorthand, usage string
9999
}{
100-
{"repo", "r", "Target repository (owner/repo format)"},
100+
{"repo", "r", "Target repository (owner/repo format). Defaults to current repository"},
101101
{"json", "j", "Output results in JSON format"},
102102
} {
103103
flag := command.PersistentFlags().Lookup(tc.name)
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
//go:build !integration
2+
3+
package workflowcontract
4+
5+
import (
6+
"os"
7+
"os/exec"
8+
"path/filepath"
9+
"strconv"
10+
"strings"
11+
"testing"
12+
)
13+
14+
func TestCLIConsistencyCheckerHelpCollection(t *testing.T) {
15+
content, err := os.ReadFile(filepath.Join("..", "..", ".github", "workflows", "cli-consistency-checker.md"))
16+
if err != nil {
17+
t.Fatal(err)
18+
}
19+
source := string(content)
20+
start := strings.Index(source, ` for i in "${!command_paths[@]}"; do`)
21+
if start < 0 {
22+
t.Fatal("help collection loop not found")
23+
}
24+
end := strings.Index(source[start:], "\n done")
25+
if end < 0 {
26+
t.Fatal("end of help collection loop not found")
27+
}
28+
loop := source[start : start+end+len("\n done")]
29+
loop = strings.ReplaceAll(loop, "./gh-aw", "fake_gh_aw")
30+
31+
run := func(t *testing.T, paths ...string) (string, error) {
32+
t.Helper()
33+
dir := t.TempDir()
34+
script := `set -euo pipefail
35+
output_dir="$1"
36+
shift
37+
command_paths=("$@")
38+
fake_gh_aw() { printf '%s\n' "$*"; }
39+
` + loop
40+
args := append([]string{"-c", script, "help-collector", dir}, paths...)
41+
err := exec.Command("bash", args...).Run()
42+
return dir, err
43+
}
44+
45+
dir, err := run(t, "foo-bar", "foo bar", "main")
46+
if err != nil {
47+
t.Fatal(err)
48+
}
49+
for i, want := range []string{"foo-bar --help\n", "foo bar --help\n", "main --help\n"} {
50+
name := filepath.Join(dir, "command-"+strconv.Itoa(i)+".txt")
51+
got, err := os.ReadFile(name)
52+
if err != nil || string(got) != want {
53+
t.Errorf("%s: got %q, err %v; want %q", name, got, err, want)
54+
}
55+
}
56+
for _, path := range []string{"", "../escape", "-flag", "valid /invalid", "valid invalid"} {
57+
t.Run(path, func(t *testing.T) {
58+
dir, err := run(t, path)
59+
if err == nil {
60+
t.Fatalf("accepted invalid command path %q", path)
61+
}
62+
entries, err := os.ReadDir(dir)
63+
if err != nil || len(entries) != 0 {
64+
t.Fatalf("invalid path wrote help files: %v, %v", entries, err)
65+
}
66+
})
67+
}
68+
}

0 commit comments

Comments
 (0)