From cff8435402d3b37dac6ceb09c5102ce403567bbd Mon Sep 17 00:00:00 2001 From: James Maes Date: Thu, 4 Jun 2026 16:27:18 -0500 Subject: [PATCH 01/14] docs: plan init tui wizard --- docs/PLAN-GH-29-init-tui-wizard.md | 45 ++++++++++++++++++ docs/SESSION-STATE.md | 25 +++------- docs/TODO.md | 74 ++++++++---------------------- 3 files changed, 70 insertions(+), 74 deletions(-) create mode 100644 docs/PLAN-GH-29-init-tui-wizard.md diff --git a/docs/PLAN-GH-29-init-tui-wizard.md b/docs/PLAN-GH-29-init-tui-wizard.md new file mode 100644 index 0000000..8ab5efb --- /dev/null +++ b/docs/PLAN-GH-29-init-tui-wizard.md @@ -0,0 +1,45 @@ +# PLAN: GH-29 Init TUI Wizard + +## Goal +Redesign `license-tool init` into a full-screen configuration wizard that explains each choice through a live example source-file preview before writing `.license-tool.yaml`. + +## Approach +Keep non-TTY `init` scriptable, but replace the interactive `huh` form with a Bubble Tea TUI. The wizard remains a configuration tool, not legal advice: it presents licensing models, common SPDX choices, private/internal paths, holder/year/style controls, include/exclude coverage, and a final review screen. The preview defaults to an example source file rendered with the current answers; detected repo language chooses the example, and C is the fallback. + +## Files Affected +- `cmd/license-tool/wizard.go` - replace linear form shell with TUI entrypoint. +- `cmd/license-tool/commands.go` - wire persisted include settings and init-specific flags. +- `cmd/license-tool/commands_test.go` - CLI/init behavior tests. +- `internal/config/config.go` - add persisted `include` schema and merge/render support. +- `internal/config/config_test.go` - config schema and layering tests. +- `internal/initwizard/` - new wizard state, sample selection, preview rendering, and TUI model. +- `internal/render/` - reuse existing header rendering for previews; no direct changes expected. +- `README.md`, `DEVELOPERS.md` - document the interactive wizard and include/exclude config. + +## User Flow +1. Choose project model: open source, private/internal, existing project detection, or advanced/manual. +2. Choose target license path: common SPDX, full searchable SPDX renderable list, or private/internal. +3. Enter copyright holder. +4. Choose year policy. +5. Choose header style with plain-language descriptions. +6. Choose whether to manage `LICENSE` and `LICENSES/.txt`. +7. Configure file coverage: detected defaults, selected extensions, or advanced glob lists. +8. Review generated config, preview header on an example file, and confirm write. + +## Preview Requirements +- Default panel is an example source file with the generated header applied. +- Secondary panels show `.license-tool.yaml`, license-file behavior, and a policy/coverage summary. +- Include examples for JavaScript/TypeScript, Python, Java, Go, C, C++, C#, PHP, Ruby, Swift, Kotlin, Rust, Shell, PowerShell, and R. +- If none of those languages are detected, default to C. + +## Steps +1. [ ] Add persisted config `include` support with TDD. +2. [ ] Add init answers and preview model capable of rendering config and sample headers. +3. [ ] Add language sample catalog and deterministic detection/fallback. +4. [ ] Implement Bubble Tea wizard model with review flow. +5. [ ] Wire interactive `init` to the new TUI while preserving non-TTY behavior. +6. [ ] Update docs and issue status. +7. [ ] Run full local quality and 100% coverage gates. + +## Open Questions +- How complete should the private/internal license path be in this first slice if no proprietary license renderer exists yet? diff --git a/docs/SESSION-STATE.md b/docs/SESSION-STATE.md index 7d3fbce..6389fe0 100644 --- a/docs/SESSION-STATE.md +++ b/docs/SESSION-STATE.md @@ -1,27 +1,16 @@ # Session State ## Current Branch -`feature/GH-12-27-audit-fixes` +`feature/GH-29-init-tui-wizard` ## Current Objective -Resolve GitHub issues #6 through #27 using TDD, keep the 100% coverage gate passing, and merge the passing local feature branch back to local `develop`. +Implement GitHub issue #29: redesign `license-tool init` as a full-screen configuration TUI with live example source preview, persisted include/exclude defaults, and 100% test coverage. ## Status -- Branch created from `develop`. -- Audit issues filed and de-duplicated against existing open issues #6 through #11. -- Plan and TODO created. -- Worktrees created under `/private/tmp/license-tool-worktrees/` for write safety, CLI reporting, SPDX/policy, dependency/release/docs, and header placement slices. -- Worker agents assigned: - - Write safety: #12, #13, #14, #15 on `feature/GH-12-27-write-safety`. - - CLI/reporting: #16, #17, #18, #25 on `feature/GH-12-27-cli-reporting`. - - SPDX/policy: #19, #20 on `feature/GH-12-27-spdx-policy`. - - Dependency/release/docs: #11, #21, #22, #23, #26 on `feature/GH-12-27-deps-release-docs`. - - Header placement: #6, #7, #8, #24, #27 on `feature/GH-12-27-header-placement`. - - File-type coverage: #9 and #10 on `feature/GH-9-10-filetype-coverage`. -- GitHub issue comments reviewed for #6 through #27 and closed tracker #3. -- Worker branches integrated into `feature/GH-12-27-audit-fixes`. -- Local gates passed: `gofmt -l .`, `go vet ./...`, `golangci-lint run`, `go test ./... -race -cover`, 100% configured coverage gate, `go build ./...`, `goreleaser check`, and `gitleaks detect`. -- `feature/GH-12-27-audit-fixes` fast-forward merged into local `develop`. +- `v0.3.0` is released. +- Feature branch created from `main` at `7e177a9`. +- Plan created in `docs/PLAN-GH-29-init-tui-wizard.md`. +- Feature-definition agent Huygens is running. ## Next Step -Manual review and testing before any push to GitHub, promotion to `main`, tag, or release. +Split implementation into worker-owned slices and integrate each behind tests. diff --git a/docs/TODO.md b/docs/TODO.md index 851f5c3..e3ff639 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -1,59 +1,21 @@ -# TODO: Audit Fixes +# TODO: GH-29 Init TUI Wizard -## Tracking -- [x] Worker agents assigned for all implementation slices. -- [x] GitHub issue comments reviewed for #6 through #27. -- [x] Keep `docs/SESSION-STATE.md` current after each integrated slice. -- [x] Keep coverage at the repository gate: total coverage 100% for the gated set. +## Definition +- [ ] Define full feature specification and MVP boundaries. +- [ ] Update issue #29 with implementation plan once finalized. -## Header Boundary Preservation -- [x] #6: Preserve Go `//go:build` and `// +build` constraints before inserted headers. -- [x] #7: Preserve CSS `@charset` before inserted headers. -- [x] #8: Preserve HTML/XML `` before inserted headers. +## Implementation +- [ ] Persist `include` patterns in `.license-tool.yaml`. +- [ ] Add init wizard sample-language catalog and C fallback. +- [ ] Add live preview rendering for example source files. +- [ ] Replace interactive `init` form with full-screen TUI. +- [ ] Preserve deterministic non-TTY `init` behavior. +- [ ] Update README/DEVELOPERS documentation. -## File-Type Coverage -- [x] #9: Add Perl, PowerShell, R, Makefile, TOML, and Batch file-type support. -- [x] #10: Detect extensionless script type from shebang content. - -## README Docs -- [x] #11: Document the init wizard and audit findings summary accurately. - -## Write Safety -- [x] #12: Make `license` honor write gates and either implement or reject commit options. -- [x] #13: Prevent dirty-tree apply commits from staging unrelated work. -- [x] #14: Make apply honor include and gitignore scope controls. -- [x] #15: Emit unified diffs during dry-run apply and license runs. - -## Header Placement -- [x] #24: Preserve Python `coding=` pragmas before inserted headers. -- [x] #27: Deduplicate shared sentinel and header placement behavior. - -## CLI And Reports -- [x] #16: Print errors and map documented exit codes. -- [x] #17: Make check fail-condition CLI overrides affect behavior. -- [x] #18: Honor audit/check output controls and documented dependency skip behavior. -- [x] #25: Reject invalid dependency resolver tier values. - -## Policy And SPDX -- [x] #19: Align accepted SPDX IDs with renderable license support. -- [x] #20: Validate policy required, allow, and deny IDs or expressions. - -## Dependencies And Release -- [x] #21: Pin release workflow actions and release tooling. -- [x] #22: Make Gradle tool-tier behavior explicit or implemented. -- [x] #23: Discover nested dependency manifests. - -## Public Docs -- [x] #26: Refresh public support, security-policy, and scaffolding docs. - -## Final Gates -- [x] `gofmt -l .` -- [x] `go vet ./...` -- [x] `golangci-lint run` -- [x] `go test ./... -race -cover` -- [x] `go test ./... -race -coverpkg=./internal/...,./cmd/... -covermode=atomic -coverprofile=cover.out` -- [x] `go run github.com/vladopajic/go-test-coverage/v2@v2.18.8 --config=.testcoverage.yml` -- [x] `go build ./...` -- [x] `goreleaser check` -- [x] `gitleaks detect --source . --no-banner --redact --exit-code 1` -- [x] Merge passing feature branch to local `develop`. +## Verification +- [ ] `gofmt -l .` +- [ ] `go vet ./...` +- [ ] `golangci-lint run` +- [ ] `go test ./... -race -coverpkg=./internal/...,./cmd/... -covermode=atomic -coverprofile=cover.out` +- [ ] `go run github.com/vladopajic/go-test-coverage/v2@v2.18.8 --config=.testcoverage.yml` +- [ ] `go build ./...` -- 2.54.0 From 5a66996d735f7f46a8d15695b255c2228e548a77 Mon Sep 17 00:00:00 2001 From: James Maes Date: Thu, 4 Jun 2026 16:31:31 -0500 Subject: [PATCH 02/14] docs: refine init tui plan --- docs/PLAN-GH-29-init-tui-wizard.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/docs/PLAN-GH-29-init-tui-wizard.md b/docs/PLAN-GH-29-init-tui-wizard.md index 8ab5efb..0b56958 100644 --- a/docs/PLAN-GH-29-init-tui-wizard.md +++ b/docs/PLAN-GH-29-init-tui-wizard.md @@ -26,12 +26,39 @@ Keep non-TTY `init` scriptable, but replace the interactive `huh` form with a Bu 7. Configure file coverage: detected defaults, selected extensions, or advanced glob lists. 8. Review generated config, preview header on an example file, and confirm write. +## TUI Shape +- Left progress rail: Project, License, Identity, Header, Files, Coverage, Review. +- Center panel: the active controls and short implications for the current step. +- Right preview panel: source preview by default, with tabs for source, YAML, license files, and coverage summary. +- Footer: key hints, validation errors, and target path. + +The terminal event loop should stay thin. Business logic belongs under `internal/initwizard` so the 100% coverage gate can test state transitions, sample selection, preview rendering, and validation without driving a real PTY. + ## Preview Requirements - Default panel is an example source file with the generated header applied. - Secondary panels show `.license-tool.yaml`, license-file behavior, and a policy/coverage summary. - Include examples for JavaScript/TypeScript, Python, Java, Go, C, C++, C#, PHP, Ruby, Swift, Kotlin, Rust, Shell, PowerShell, and R. - If none of those languages are detected, default to C. +Samples should exercise preserve-first behavior when relevant: Go build tags, Python/Ruby coding pragmas, PHP open tags, shebang-bearing shell-like files, and Java/Kotlin package declarations. + +## Config Semantics +- Add persisted `include` support to `.license-tool.yaml`. +- Empty include means all eligible files. +- Highest non-empty include layer wins: flags > repo config > user config > defaults. +- `exclude` keeps the existing accumulating behavior. +- Command paths should use resolved config includes; CLI `--include` remains highest precedence because it flows through config resolution. + +```yaml +include: + - "src/**" +exclude: + - "**/generated/**" +``` + +## Private/Internal MVP +Private/internal is supported as a guided path, but the tool must not invent proprietary license terms. The MVP can allow a private/internal project to choose metadata-only behavior or a renderable SPDX license used internally. Deeper `LicenseRef-*` support requires explicit user-provided license text and can be deferred if it would spread across render, policy, and license-file management. + ## Steps 1. [ ] Add persisted config `include` support with TDD. 2. [ ] Add init answers and preview model capable of rendering config and sample headers. -- 2.54.0 From fa1b86da03c26742a1466f62194904757e6eec48 Mon Sep 17 00:00:00 2001 From: James Maes Date: Thu, 4 Jun 2026 16:35:20 -0500 Subject: [PATCH 03/14] feat(init): persist include patterns Refs #29 --- README.md | 4 ++- cmd/license-tool/commands.go | 7 +++-- cmd/license-tool/commands_test.go | 49 +++++++++++++++++++++++++++++-- internal/config/config.go | 9 ++++++ internal/config/config_test.go | 41 ++++++++++++++++++++++++++ internal/model/model.go | 2 ++ 6 files changed, 106 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index c02d534..f31a1c3 100644 --- a/README.md +++ b/README.md @@ -153,7 +153,7 @@ overwrite it unless `--force` is passed. ## Configuration -Configuration is layered. Precedence, high to low: flags, the per-repo `.license-tool.yaml`, the user/global config (`$XDG_CONFIG_HOME/license-tool/config.yaml`), then built-in defaults. The committed `.license-tool.yaml` declares the repo's license identity and doubles as the `check` expectation. For `init`, missing required fields prompt through the wizard on a TTY; non-TTY runs skip the wizard, use flags only, and report missing or invalid values as usage errors. +Configuration is layered. Precedence, high to low: flags, the per-repo `.license-tool.yaml`, the user/global config (`$XDG_CONFIG_HOME/license-tool/config.yaml`), then built-in defaults. The committed `.license-tool.yaml` declares the repo's license identity and doubles as the `check` expectation. `include` uses the highest non-empty layer, while `exclude` accumulates across layers. For `init`, missing required fields prompt through the wizard on a TTY; non-TTY runs skip the wizard, use flags only, and report missing or invalid values as usage errors. ```yaml # .license-tool.yaml (committed per repo; doubles as the check expectation) @@ -162,6 +162,8 @@ holder: "Kingsrook, LLC" # copyright holder year: git # current | YYYY | YYYY-YYYY | git style: reuse+notice # reuse | notice | reuse+notice manage_license_file: true # write top-level LICENSE + LICENSES/.txt +include: # optional globs limiting files considered + - "src/**" exclude: # gitignore-style, in addition to .gitignore - "**/generated/**" - "**/*.pb.go" diff --git a/cmd/license-tool/commands.go b/cmd/license-tool/commands.go index fab3ad0..df9e8fd 100644 --- a/cmd/license-tool/commands.go +++ b/cmd/license-tool/commands.go @@ -223,7 +223,7 @@ func newApplyCmd(shared *sharedFlags) *cobra.Command { // for write operations, so no second check is needed here. r, err := applier.Apply(path, cfg, applier.Options{ Write: f.write, - Includes: shared.include, + Includes: cfg.Includes, AllowDirty: f.allowDirty, Force: f.force, NoGitignore: shared.noGitignore, @@ -261,7 +261,7 @@ func newLicenseCmd(shared *sharedFlags) *cobra.Command { // for write operations, so no second check is needed here. results, err := applier.License(path, cfg, applier.Options{ Write: f.write, - Includes: shared.include, + Includes: cfg.Includes, AllowDirty: f.allowDirty, Force: f.force, NoGitignore: shared.noGitignore, @@ -456,6 +456,7 @@ func newInitCmd(shared *sharedFlags) *cobra.Command { if err != nil { return usageError(err) } + cfg.Includes = shared.include target, err := config.WriteFile(path, cfg, f.force) if err != nil { return writeOrInternalError(err) @@ -495,7 +496,7 @@ func buildAuditPipeline(cfg model.Config, shared *sharedFlags) report.Pipeline { return report.Pipeline{ Enumerate: func(root string, excludes []string) ([]report.SourceFile, error) { entries, err := enumerate.WithContent(root, enumerate.Options{ - Includes: shared.include, + Includes: cfg.Includes, Excludes: excludes, NoGitignore: shared.noGitignore, }, classify) diff --git a/cmd/license-tool/commands_test.go b/cmd/license-tool/commands_test.go index 5b602c2..b469ca9 100644 --- a/cmd/license-tool/commands_test.go +++ b/cmd/license-tool/commands_test.go @@ -295,6 +295,30 @@ func TestAuditCommand(t *testing.T) { assert.Contains(t, out, "# license-tool audit report") }) + t.Run("config include scopes source enumeration", func(t *testing.T) { + dir := t.TempDir() + writeFile(t, dir, ".license-tool.yaml", configYAML+"include: [\"included.go\"]\n") + writeFile(t, dir, "included.go", "package included\n") + writeFile(t, dir, "excluded.go", "package excluded\n") + + out, err := runRoot(t, "audit", dir, "--deps=false") + require.NoError(t, err) + assert.Contains(t, out, "included.go") + assert.NotContains(t, out, "excluded.go") + }) + + t.Run("flag include overrides config include", func(t *testing.T) { + dir := t.TempDir() + writeFile(t, dir, ".license-tool.yaml", configYAML+"include: [\"repo.go\"]\n") + writeFile(t, dir, "repo.go", "package repo\n") + writeFile(t, dir, "flag.go", "package flag\n") + + out, err := runRoot(t, "audit", dir, "--include", "flag.go", "--deps=false") + require.NoError(t, err) + assert.Contains(t, out, "flag.go") + assert.NotContains(t, out, "repo.go") + }) + t.Run("default path resolves to dot", func(t *testing.T) { // No path arg: argPath returns ".". Run from an isolated empty dir so the // audit sees only its own (absent) config and produces a clean report. @@ -734,6 +758,25 @@ func TestApplyCommand(t *testing.T) { assert.NotContains(t, string(ignored), "SPDX-License-Identifier") }) + t.Run("write honors config include scope", func(t *testing.T) { + dir := t.TempDir() + writeFile(t, dir, ".license-tool.yaml", configNoManagedYAML+"include: [\"included.go\"]\n") + writeFile(t, dir, "included.go", "package included\n") + writeFile(t, dir, "ignored.go", "package ignored\n") + initGitRepo(t, dir) + + _, err := runRoot(t, "apply", dir, "--write") + require.NoError(t, err) + + included, rerr := os.ReadFile(filepath.Join(dir, "included.go")) + require.NoError(t, rerr) + assert.Contains(t, string(included), "SPDX-License-Identifier: AGPL-3.0-or-later") + + ignored, rerr := os.ReadFile(filepath.Join(dir, "ignored.go")) + require.NoError(t, rerr) + assert.NotContains(t, string(ignored), "SPDX-License-Identifier") + }) + t.Run("allow-dirty commit leaves unrelated changes uncommitted", func(t *testing.T) { dir := t.TempDir() writeFile(t, dir, ".license-tool.yaml", configNoManagedYAML) @@ -876,9 +919,9 @@ func TestInitCommand(t *testing.T) { t.Run("flags scaffold config file", func(t *testing.T) { // Non-TTY stdin (forced by isolateEnv) skips the wizard, so init scaffolds a - // .license-tool.yaml purely from the --license/--holder flags. + // .license-tool.yaml purely from flags. dir := t.TempDir() - out, err := runRoot(t, "init", dir, "--license", "MIT", "--holder", "Acme") + out, err := runRoot(t, "init", dir, "--license", "MIT", "--holder", "Acme", "--include", "src/**", "--exclude", "vendor/**") require.NoError(t, err) target := filepath.Join(dir, ".license-tool.yaml") assert.Contains(t, out, "wrote "+target) @@ -887,6 +930,8 @@ func TestInitCommand(t *testing.T) { require.NoError(t, lerr) assert.Equal(t, "MIT", cfg.License) assert.Equal(t, "Acme", cfg.Holder) + assert.Equal(t, []string{"src/**"}, cfg.Includes) + assert.Equal(t, []string{"vendor/**"}, cfg.Excludes) }) t.Run("missing license errors", func(t *testing.T) { diff --git a/internal/config/config.go b/internal/config/config.go index 8694ed1..49dcdd3 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -93,6 +93,7 @@ func Defaults() model.Config { Year: model.YearSpec{Kind: model.YearGit}, Style: model.StyleReusePlusNotice, ManageLicenseFile: true, + Includes: nil, Excludes: nil, Policy: model.Policy{ FailOn: []model.FailCondition{ @@ -211,6 +212,7 @@ func RenderFile(cfg model.Config) ([]byte, error) { Year: yearSpecRaw(cfg.Year), Style: cfg.Style.String(), ManageLicenseFile: &cfg.ManageLicenseFile, + Include: cfg.Includes, Exclude: cfg.Excludes, } // Only emit a policy block when the config actually carries policy intent, so a @@ -301,6 +303,7 @@ type fileSchema struct { Year string `yaml:"year"` Style string `yaml:"style"` ManageLicenseFile *bool `yaml:"manage_license_file"` + Include []string `yaml:"include"` Exclude []string `yaml:"exclude"` Policy policySchema `yaml:"policy"` FileTypes map[string]fileTypeOverrideYAML `yaml:"file_types"` @@ -367,6 +370,9 @@ func mergeSchema(cfg *model.Config, fs fileSchema) error { if fs.ManageLicenseFile != nil { cfg.ManageLicenseFile = *fs.ManageLicenseFile } + if len(fs.Include) > 0 { + cfg.Includes = append([]string(nil), fs.Include...) + } if len(fs.Exclude) > 0 { // Excludes accumulate: a layer's excludes add to, rather than replace, the // lower layers' so a repo cannot accidentally lose user/global exclusions. @@ -450,6 +456,9 @@ func mergeFlags(cfg *model.Config, flags Flags) error { if len(flags.Exclude) > 0 { cfg.Excludes = append(cfg.Excludes, flags.Exclude...) } + if len(flags.Include) > 0 { + cfg.Includes = append([]string(nil), flags.Include...) + } return nil } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 2cf4752..06bae68 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -169,6 +169,8 @@ holder: "Kingsrook, LLC" year: git style: reuse+notice manage_license_file: true +include: + - "src/**" exclude: - "**/generated/**" policy: @@ -189,6 +191,9 @@ file_types: if fs.ManageLicenseFile == nil || !*fs.ManageLicenseFile { t.Errorf("manage_license_file not decoded as true: %+v", fs.ManageLicenseFile) } + if len(fs.Include) != 1 || fs.Include[0] != "src/**" { + t.Errorf("include not decoded: %+v", fs.Include) + } if len(fs.Policy.Allow) != 2 || len(fs.FileTypes) != 1 { t.Errorf("nested keys not decoded: %+v", fs) } @@ -524,6 +529,38 @@ style: notice } } }) + + t.Run("highest non-empty include layer wins", func(t *testing.T) { + xdg := isolateXDG(t) + writeFile(t, filepath.Join(xdg, "license-tool", "config.yaml"), "license: MIT\nholder: A\ninclude: [\"global/**\"]\n") + repo := t.TempDir() + writeFile(t, filepath.Join(repo, repoConfigName), "include: [\"repo/**\"]\n") + + cfg, err := Resolve(repo, Flags{}, Options{Interactive: false}) + if err != nil { + t.Fatalf("Resolve error: %v", err) + } + if len(cfg.Includes) != 1 || cfg.Includes[0] != "repo/**" { + t.Fatalf("includes = %v, want repo layer only", cfg.Includes) + } + + cfg, err = Resolve(repo, Flags{Include: []string{"flags/**"}}, Options{Interactive: false}) + if err != nil { + t.Fatalf("Resolve error: %v", err) + } + if len(cfg.Includes) != 1 || cfg.Includes[0] != "flags/**" { + t.Fatalf("includes = %v, want flags layer only", cfg.Includes) + } + + repoWithoutInclude := t.TempDir() + cfg, err = Resolve(repoWithoutInclude, Flags{}, Options{Interactive: false}) + if err != nil { + t.Fatalf("Resolve error: %v", err) + } + if len(cfg.Includes) != 1 || cfg.Includes[0] != "global/**" { + t.Fatalf("includes = %v, want user layer only", cfg.Includes) + } + }) } func TestResolveRequiredFields(t *testing.T) { @@ -1100,6 +1137,7 @@ func TestRenderFile(t *testing.T) { cfg.Year = model.YearSpec{Kind: model.YearRange, Start: 2021, End: 2026} cfg.Style = model.StyleNotice cfg.ManageLicenseFile = false + cfg.Includes = []string{"src/**"} cfg.Excludes = []string{"**/generated/**"} cfg.Policy = model.Policy{ Required: "AGPL-3.0-or-later", @@ -1133,6 +1171,9 @@ func TestRenderFile(t *testing.T) { if got.ManageLicenseFile { t.Errorf("manage_license_file should round-trip as false") } + if len(got.Includes) != 1 || got.Includes[0] != "src/**" { + t.Errorf("includes = %v, want [src/**]", got.Includes) + } if len(got.Excludes) != 1 || got.Excludes[0] != "**/generated/**" { t.Errorf("excludes = %v, want [**/generated/**]", got.Excludes) } diff --git a/internal/model/model.go b/internal/model/model.go index d69efc4..d8afdc4 100644 --- a/internal/model/model.go +++ b/internal/model/model.go @@ -232,6 +232,8 @@ type Config struct { Style HeaderStyle // ManageLicenseFile enables writing top-level LICENSE + LICENSES/.txt. ManageLicenseFile bool + // Includes are glob patterns that restrict source-file processing when non-empty. + Includes []string // Excludes are gitignore-style patterns added on top of .gitignore. Excludes []string // Policy drives audit classification and check exit codes. -- 2.54.0 From 4773596e5d017de1070a237702ae1ba022a1bc8d Mon Sep 17 00:00:00 2001 From: James Maes Date: Thu, 4 Jun 2026 16:36:03 -0500 Subject: [PATCH 04/14] feat(init): wire tui collector Refs #29. --- cmd/license-tool/commands.go | 58 ++-- cmd/license-tool/commands_test.go | 118 ++++++-- cmd/license-tool/wizard.go | 428 ++++++++++++++++++++++++------ internal/initwizard/model.go | 127 +++++++++ 4 files changed, 599 insertions(+), 132 deletions(-) create mode 100644 internal/initwizard/model.go diff --git a/cmd/license-tool/commands.go b/cmd/license-tool/commands.go index fab3ad0..78b5e39 100644 --- a/cmd/license-tool/commands.go +++ b/cmd/license-tool/commands.go @@ -16,6 +16,7 @@ import ( "github.com/KofTwentyTwo/license-tool/internal/config" "github.com/KofTwentyTwo/license-tool/internal/detect" "github.com/KofTwentyTwo/license-tool/internal/enumerate" + "github.com/KofTwentyTwo/license-tool/internal/initwizard" "github.com/KofTwentyTwo/license-tool/internal/model" "github.com/KofTwentyTwo/license-tool/internal/report" "github.com/KofTwentyTwo/license-tool/internal/resolve" @@ -389,8 +390,8 @@ func bindApplyFlags(cmd *cobra.Command, f *applyFlags) { } // interactiveCollect is a package-level seam over collectInteractive so tests can -// drive the init command's non-interactive flow (and inject answers) without a real -// terminal. Production always points at the huh-backed collectInteractive. +// inject richer wizard answers without a real terminal. Production points at the +// Bubble Tea collector, which no-ops when interactive is false. var interactiveCollect = collectInteractive // answersToConfig validates and converts collected init answers into a model.Config, @@ -400,35 +401,40 @@ var interactiveCollect = collectInteractive // gate that both the TTY and flag-only paths funnel through, so an invalid or // unrenderable license and an empty holder are rejected identically regardless of // how the answers arrived. -func answersToConfig(a initAnswers) (model.Config, error) { - if !spdx.Validate(a.License) { - return model.Config{}, fmt.Errorf("init: %q is not a recognized SPDX license identifier", a.License) +func answersToConfig(a initwizard.Answers) (model.Config, error) { + licenseID := strings.TrimSpace(a.License.SPDXID) + holder := strings.TrimSpace(a.Identity.Holder) + year := strings.TrimSpace(a.Identity.Year) + style := strings.TrimSpace(a.HeaderStyle.Style) + + if !spdx.Validate(licenseID) { + return model.Config{}, fmt.Errorf("init: %q is not a recognized SPDX license identifier", licenseID) } - if _, ok := spdx.Lookup(a.License); !ok { - return model.Config{}, fmt.Errorf("init: %q is a recognized SPDX license identifier, but license-tool cannot render it", a.License) + if _, ok := spdx.Lookup(licenseID); !ok { + return model.Config{}, fmt.Errorf("init: %q is a recognized SPDX license identifier, but license-tool cannot render it", licenseID) } - if a.Holder == "" { + if holder == "" { return model.Config{}, fmt.Errorf("init: copyright holder is required") } cfg := config.Defaults() - cfg.License = a.License - cfg.Holder = a.Holder - if a.Year != "" { - ys, err := config.ParseYearSpec(a.Year) + cfg.License = licenseID + cfg.Holder = holder + if year != "" { + ys, err := config.ParseYearSpec(year) if err != nil { return model.Config{}, err } cfg.Year = ys } - if a.Style != "" { - st, err := config.ParseStyle(a.Style) + if style != "" { + st, err := config.ParseStyle(style) if err != nil { return model.Config{}, err } cfg.Style = st } - cfg.ManageLicenseFile = a.ManageLicenseFile - cfg.Excludes = a.Excludes + cfg.ManageLicenseFile = a.LicenseFiles.Manage + cfg.Excludes = append([]string(nil), a.Coverage.Exclude...) return cfg, nil } @@ -441,15 +447,19 @@ func newInitCmd(shared *sharedFlags) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { path := argPath(args) out := cmd.OutOrStdout() - a := initAnswers{ - License: f.license, - Holder: f.holder, - Year: f.year, - Style: f.style, - ManageLicenseFile: true, - Excludes: shared.exclude, + a := initwizard.Answers{ + Project: initwizard.ProjectAnswer{Model: initwizard.ProjectModelAdvancedManual}, + License: initwizard.LicenseAnswer{SPDXID: f.license}, + Identity: initwizard.IdentityAnswer{Holder: f.holder, Year: f.year}, + HeaderStyle: initwizard.HeaderStyleAnswer{Style: f.style}, + LicenseFiles: initwizard.LicenseFilesAnswer{Manage: true}, + Coverage: initwizard.CoverageAnswer{ + Include: shared.include, + Exclude: shared.exclude, + }, } - if err := interactiveCollect(&a, isTTY()); err != nil { + a, err := interactiveCollect(path, a, isTTY()) + if err != nil { return usageError(err) } cfg, err := answersToConfig(a) diff --git a/cmd/license-tool/commands_test.go b/cmd/license-tool/commands_test.go index 5b602c2..bfddc94 100644 --- a/cmd/license-tool/commands_test.go +++ b/cmd/license-tool/commands_test.go @@ -16,6 +16,7 @@ import ( "github.com/KofTwentyTwo/license-tool/internal/config" "github.com/KofTwentyTwo/license-tool/internal/enumerate" + "github.com/KofTwentyTwo/license-tool/internal/initwizard" "github.com/KofTwentyTwo/license-tool/internal/model" "github.com/KofTwentyTwo/license-tool/internal/report" "github.com/KofTwentyTwo/license-tool/internal/spdx" @@ -932,13 +933,19 @@ func TestInitCommand(t *testing.T) { // exercised, and they must reject identically regardless of how answers arrived. func TestAnswersToConfig(t *testing.T) { t.Run("valid answers build a config from defaults", func(t *testing.T) { - cfg, err := answersToConfig(initAnswers{ - License: "MIT", - Holder: "Acme, LLC", - Year: "2021-2026", - Style: "reuse", - ManageLicenseFile: false, - Excludes: []string{"**/vendor/**"}, + cfg, err := answersToConfig(initwizard.Answers{ + License: initwizard.LicenseAnswer{SPDXID: "MIT"}, + Identity: initwizard.IdentityAnswer{ + Holder: "Acme, LLC", + Year: "2021-2026", + }, + HeaderStyle: initwizard.HeaderStyleAnswer{Style: "reuse"}, + LicenseFiles: initwizard.LicenseFilesAnswer{ + Manage: false, + }, + Coverage: initwizard.CoverageAnswer{ + Exclude: []string{"**/vendor/**"}, + }, }) require.NoError(t, err) assert.Equal(t, "MIT", cfg.License) @@ -954,32 +961,46 @@ func TestAnswersToConfig(t *testing.T) { t.Run("empty year and style keep the built-in defaults", func(t *testing.T) { // Unset year/style answers must leave the Defaults() values untouched, so the // year/style parse branches are skipped (not defaulted to a parse of ""). - cfg, err := answersToConfig(initAnswers{License: "MIT", Holder: "Acme"}) + cfg, err := answersToConfig(initwizard.Answers{ + License: initwizard.LicenseAnswer{SPDXID: "MIT"}, + Identity: initwizard.IdentityAnswer{Holder: "Acme"}, + LicenseFiles: initwizard.LicenseFilesAnswer{Manage: true}, + }) require.NoError(t, err) assert.Equal(t, model.YearGit, cfg.Year.Kind) assert.Equal(t, model.StyleReusePlusNotice, cfg.Style) }) t.Run("unknown license rejected", func(t *testing.T) { - _, err := answersToConfig(initAnswers{License: "NOT-A-LICENSE", Holder: "Acme"}) + _, err := answersToConfig(initwizard.Answers{ + License: initwizard.LicenseAnswer{SPDXID: "NOT-A-LICENSE"}, + Identity: initwizard.IdentityAnswer{Holder: "Acme"}, + }) require.Error(t, err) assert.Contains(t, err.Error(), "not a recognized SPDX license identifier") }) t.Run("empty holder rejected", func(t *testing.T) { - _, err := answersToConfig(initAnswers{License: "MIT", Holder: ""}) + _, err := answersToConfig(initwizard.Answers{License: initwizard.LicenseAnswer{SPDXID: "MIT"}}) require.Error(t, err) assert.Contains(t, err.Error(), "copyright holder is required") }) t.Run("bad year rejected", func(t *testing.T) { - _, err := answersToConfig(initAnswers{License: "MIT", Holder: "Acme", Year: "not-a-year"}) + _, err := answersToConfig(initwizard.Answers{ + License: initwizard.LicenseAnswer{SPDXID: "MIT"}, + Identity: initwizard.IdentityAnswer{Holder: "Acme", Year: "not-a-year"}, + }) require.Error(t, err) assert.Contains(t, err.Error(), "year") }) t.Run("bad style rejected", func(t *testing.T) { - _, err := answersToConfig(initAnswers{License: "MIT", Holder: "Acme", Style: "fancy"}) + _, err := answersToConfig(initwizard.Answers{ + License: initwizard.LicenseAnswer{SPDXID: "MIT"}, + Identity: initwizard.IdentityAnswer{Holder: "Acme"}, + HeaderStyle: initwizard.HeaderStyleAnswer{Style: "fancy"}, + }) require.Error(t, err) assert.Contains(t, err.Error(), "unknown style") }) @@ -1036,24 +1057,22 @@ func TestLicenseSelectOptions(t *testing.T) { opts := licenseSelectOptions() require.NotEmpty(t, opts, "license picker should offer renderable licenses") - values := make([]string, 0, len(opts)) - for _, opt := range opts { - values = append(values, opt.Value) - } - assert.Contains(t, values, "MIT") - assert.NotContains(t, values, "Zlib", "picker must not offer a license the tool cannot render") + assert.Contains(t, opts, "MIT") + assert.NotContains(t, opts, "Zlib", "picker must not offer a license the tool cannot render") } // TestInitCommandInteractiveCollectError covers the init RunE branch where the // interactiveCollect seam returns an error: the command must propagate it verbatim // and write nothing. The seam is overridden so the failure is deterministic without -// a real terminal (the huh wizard itself is excluded from coverage). +// a real terminal (the Bubble Tea wizard itself is excluded from coverage). func TestInitCommandInteractiveCollectError(t *testing.T) { isolateEnv(t) orig := interactiveCollect wantErr := errors.New("wizard aborted") - interactiveCollect = func(_ *initAnswers, _ bool) error { return wantErr } + interactiveCollect = func(_ string, a initwizard.Answers, _ bool) (initwizard.Answers, error) { + return a, wantErr + } t.Cleanup(func() { interactiveCollect = orig }) dir := t.TempDir() @@ -1065,6 +1084,65 @@ func TestInitCommandInteractiveCollectError(t *testing.T) { assert.True(t, os.IsNotExist(statErr), "no config should be written when collect fails") } +func TestInitCommandConsumesCollectorAnswers(t *testing.T) { + isolateEnv(t) + + orig := interactiveCollect + t.Cleanup(func() { interactiveCollect = orig }) + + dir := t.TempDir() + interactiveCollect = func(path string, initial initwizard.Answers, interactive bool) (initwizard.Answers, error) { + assert.Equal(t, dir, path) + assert.False(t, interactive) + assert.Equal(t, initwizard.ProjectModelAdvancedManual, initial.Project.Model) + assert.Equal(t, "MIT", initial.License.SPDXID) + assert.Equal(t, "Flag Holder", initial.Identity.Holder) + assert.Equal(t, "2026", initial.Identity.Year) + assert.Equal(t, "reuse", initial.HeaderStyle.Style) + assert.Equal(t, []string{"src/**"}, initial.Coverage.Include) + assert.Equal(t, []string{"vendor/**"}, initial.Coverage.Exclude) + + return initwizard.Answers{ + Project: initwizard.ProjectAnswer{Model: initwizard.ProjectModelPrivateInternal}, + License: initwizard.LicenseAnswer{ + SPDXID: "Apache-2.0", + }, + Identity: initwizard.IdentityAnswer{ + Holder: "Wizard Holder", + Year: "current", + }, + HeaderStyle: initwizard.HeaderStyleAnswer{Style: "notice"}, + LicenseFiles: initwizard.LicenseFilesAnswer{Manage: false}, + Coverage: initwizard.CoverageAnswer{ + Include: []string{"cmd/**"}, + Exclude: []string{"generated/**"}, + }, + Review: initwizard.ReviewAnswer{Confirmed: true}, + }, nil + } + + out, err := runRoot(t, "init", dir, + "--license", "MIT", + "--holder", "Flag Holder", + "--year", "2026", + "--style", "reuse", + "--include", "src/**", + "--exclude", "vendor/**", + ) + require.NoError(t, err) + + target := filepath.Join(dir, ".license-tool.yaml") + assert.Contains(t, out, "wrote "+target) + cfg, err := config.LoadFile(target) + require.NoError(t, err) + assert.Equal(t, "Apache-2.0", cfg.License) + assert.Equal(t, "Wizard Holder", cfg.Holder) + assert.Equal(t, model.YearCurrent, cfg.Year.Kind) + assert.Equal(t, model.StyleNotice, cfg.Style) + assert.False(t, cfg.ManageLicenseFile) + assert.Equal(t, []string{"generated/**"}, cfg.Excludes) +} + func TestSharedToFlags(t *testing.T) { s := &sharedFlags{ configPath: "/cfg.yaml", diff --git a/cmd/license-tool/wizard.go b/cmd/license-tool/wizard.go index dc35e3d..183b240 100644 --- a/cmd/license-tool/wizard.go +++ b/cmd/license-tool/wizard.go @@ -1,114 +1,366 @@ package main import ( - "errors" + "fmt" + "os" + "strings" - "github.com/charmbracelet/huh" + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" - "github.com/KofTwentyTwo/license-tool/internal/config" + "github.com/KofTwentyTwo/license-tool/internal/initwizard" "github.com/KofTwentyTwo/license-tool/internal/spdx" ) -// errEmptyHolder is the in-form validation error shown when the holder is blank. A -// non-empty holder is required to render a meaningful copyright line, so the wizard -// refuses to advance until one is entered. -var errEmptyHolder = errors.New("copyright holder is required") +var ( + projectModelOptions = []initwizard.ProjectModel{ + initwizard.ProjectModelOpenSource, + initwizard.ProjectModelPrivateInternal, + initwizard.ProjectModelExistingProject, + initwizard.ProjectModelAdvancedManual, + } + headerStyleOptions = []string{"reuse", "notice", "reuse+notice"} +) -// initAnswers holds the raw string answers collected by the interactive init -// wizard, before they are validated and parsed into a model.Config. WHY raw strings -// (not a model.Config): the form binds directly to these fields, and answersToConfig -// owns the single validation/parse pass, so the wizard stays a thin I/O shell with -// no business logic (this file is excluded from coverage for exactly that reason). -type initAnswers struct { - License string - Holder string - Year string - Style string - ManageLicenseFile bool - Excludes []string -} - -// licenseSelectOptions builds the filterable license picker options: the curated -// CommonIDs first (each labeled " (common)" so a user knows they are the -// recommended set), then the remaining renderable SPDX ids in sorted order with no -// duplicates. WHY common-first: the operator sees sensible defaults at the top -// before the alphabetical tail they can still filter into. -func licenseSelectOptions() []huh.Option[string] { +// licenseSelectOptions builds the license picker values: common renderable SPDX ids +// first, then the remaining renderable ids in sorted order without duplicates. +func licenseSelectOptions() []string { common := spdx.CommonIDs() seen := make(map[string]bool, len(common)) - opts := make([]huh.Option[string], 0, len(common)) + opts := make([]string, 0, len(common)) for _, id := range common { seen[id] = true - opts = append(opts, huh.NewOption(id+" (common)", id)) + opts = append(opts, id) } for _, id := range spdx.RenderableIDs() { if seen[id] { continue } - opts = append(opts, huh.NewOption(id, id)) + opts = append(opts, id) } return opts } -// runInitWizard drives the interactive init form, binding each answer into a. WHY -// the Year/License validators reuse the config parsers: the wizard must reject the -// same inputs answersToConfig would later reject, so the user fixes a bad value -// in-place rather than getting a post-submit error. -func runInitWizard(a *initAnswers) error { - // Pre-populate the year field with the safe "git" default so an operator who just - // presses enter accepts the same default the config layer would have applied. - if a.Year == "" { - a.Year = "git" - } - form := huh.NewForm( - huh.NewGroup( - huh.NewSelect[string](). - Title("Target SPDX license"). - Options(licenseSelectOptions()...). - Filtering(true). - Value(&a.License), - huh.NewInput(). - Title("Copyright holder"). - Value(&a.Holder). - Validate(func(s string) error { - if s == "" { - return errEmptyHolder - } - return nil - }), - huh.NewInput(). - Title("Year policy (current|YYYY|YYYY-YYYY|git)"). - Value(&a.Year). - Validate(func(s string) error { - if s == "" { - return nil - } - _, err := config.ParseYearSpec(s) - return err - }), - huh.NewSelect[string](). - Title("Header style"). - Options( - huh.NewOption("reuse", "reuse"), - huh.NewOption("notice", "notice"), - huh.NewOption("reuse+notice", "reuse+notice"), - ). - Value(&a.Style), - huh.NewConfirm(). - Title("Manage top-level LICENSE file?"). - Value(&a.ManageLicenseFile), - ), - ) - return form.Run() +type initWizardModel struct { + root string + answers initwizard.Answers + step initwizard.Step + input textinput.Model + licenseOptions []string + projectIndex int + licenseIndex int + styleIndex int + width int + height int } -// collectInteractive runs the wizard to populate a when interactive is true, -// otherwise it is a no-op (the non-TTY path relies entirely on flags). WHY a seam: -// commands.go swaps this out in tests so the init command's non-interactive flow can -// be exercised without a terminal. -func collectInteractive(a *initAnswers, interactive bool) error { - if !interactive { - return nil +func newInitWizardModel(root string, answers initwizard.Answers) initWizardModel { + m := initWizardModel{ + root: root, + answers: answers, + step: initwizard.StepProjectModel, + licenseOptions: licenseSelectOptions(), } - return runInitWizard(a) + if m.answers.Project.Model == "" { + m.answers.Project.Model = initwizard.ProjectModelOpenSource + } + if m.answers.License.SPDXID == "" && len(m.licenseOptions) > 0 { + m.answers.License.SPDXID = m.licenseOptions[0] + } + if m.answers.Identity.Year == "" { + m.answers.Identity.Year = "git" + } + if m.answers.HeaderStyle.Style == "" { + m.answers.HeaderStyle.Style = "reuse+notice" + } + m.projectIndex = indexProjectModel(projectModelOptions, m.answers.Project.Model) + m.licenseIndex = indexString(m.licenseOptions, m.answers.License.SPDXID) + m.styleIndex = indexString(headerStyleOptions, m.answers.HeaderStyle.Style) + m.setInput() + return m +} + +func indexProjectModel(values []initwizard.ProjectModel, value initwizard.ProjectModel) int { + for i, item := range values { + if item == value { + return i + } + } + return 0 +} + +func indexString(values []string, value string) int { + for i, item := range values { + if item == value { + return i + } + } + return 0 +} + +func (m initWizardModel) Init() tea.Cmd { + return textinput.Blink +} + +func (m initWizardModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.WindowSizeMsg: + m.width = msg.Width + m.height = msg.Height + return m, nil + case tea.KeyMsg: + switch msg.String() { + case "ctrl+c", "esc": + m.answers.Review.Confirmed = false + return m, tea.Quit + case "up", "k": + m.moveSelection(-1) + return m, nil + case "down", "j": + m.moveSelection(1) + return m, nil + case " ", "y", "n": + if m.step == initwizard.StepLicenseFiles { + m.toggleBool(msg.String()) + return m, nil + } + case "backspace": + if !m.usesTextInput() && m.step > initwizard.StepProjectModel { + m.step-- + m.setInput() + return m, nil + } + case "enter": + m.commitInput() + if m.step == initwizard.StepReview { + m.answers.Review.Confirmed = true + return m, tea.Quit + } + m.step++ + m.setInput() + return m, nil + } + } + if m.usesTextInput() { + var cmd tea.Cmd + m.input, cmd = m.input.Update(msg) + return m, cmd + } + return m, nil +} + +func (m initWizardModel) View() string { + var b strings.Builder + fmt.Fprintf(&b, "license-tool init\n") + if m.root != "" { + fmt.Fprintf(&b, "path: %s\n", m.root) + } + fmt.Fprintf(&b, "\n%s\n\n", m.stepTitle()) + b.WriteString(m.stepBody()) + fmt.Fprintf(&b, "\n\n%s\n", m.previewSummary()) + fmt.Fprintf(&b, "\nenter next, backspace back, esc cancel") + if m.step == initwizard.StepReview { + fmt.Fprintf(&b, "\nenter confirms and writes .license-tool.yaml") + } + return b.String() +} + +func (m initWizardModel) stepTitle() string { + switch m.step { + case initwizard.StepProjectModel: + return "Project model" + case initwizard.StepLicense: + return "License" + case initwizard.StepIdentity: + return "Identity" + case initwizard.StepHeaderStyle: + return "Header style" + case initwizard.StepLicenseFiles: + return "License files" + case initwizard.StepCoverage: + return "Coverage" + default: + return "Review" + } +} + +func (m initWizardModel) stepBody() string { + switch m.step { + case initwizard.StepProjectModel: + return optionList(projectModelsToStrings(projectModelOptions), m.projectIndex) + case initwizard.StepLicense: + return optionList(m.licenseOptions, m.licenseIndex) + case initwizard.StepIdentity: + return m.input.View() + case initwizard.StepHeaderStyle: + return optionList(headerStyleOptions, m.styleIndex) + case initwizard.StepLicenseFiles: + if m.answers.LicenseFiles.Manage { + return "Manage LICENSE and LICENSES/.txt: yes" + } + return "Manage LICENSE and LICENSES/.txt: no" + case initwizard.StepCoverage: + return m.input.View() + default: + return m.reviewBody() + } +} + +func projectModelsToStrings(values []initwizard.ProjectModel) []string { + out := make([]string, 0, len(values)) + for _, value := range values { + out = append(out, string(value)) + } + return out +} + +func optionList(values []string, selected int) string { + var b strings.Builder + for i, value := range values { + prefix := " " + if i == selected { + prefix = "> " + } + fmt.Fprintf(&b, "%s%s\n", prefix, value) + } + return strings.TrimRight(b.String(), "\n") +} + +func (m initWizardModel) reviewBody() string { + return strings.Join([]string{ + "Project model: " + string(m.answers.Project.Model), + "License: " + m.answers.License.SPDXID, + "Holder: " + m.answers.Identity.Holder, + "Year: " + m.answers.Identity.Year, + "Header style: " + m.answers.HeaderStyle.Style, + "Manage license files: " + yesNo(m.answers.LicenseFiles.Manage), + "Include: " + strings.Join(m.answers.Coverage.Include, ", "), + "Exclude: " + strings.Join(m.answers.Coverage.Exclude, ", "), + }, "\n") +} + +func (m initWizardModel) previewSummary() string { + return "Preview engine: pending integration with the sample renderer. Current review values are shown above." +} + +func yesNo(v bool) string { + if v { + return "yes" + } + return "no" +} + +func (m *initWizardModel) moveSelection(delta int) { + switch m.step { + case initwizard.StepProjectModel: + m.projectIndex = wrapIndex(m.projectIndex+delta, len(projectModelOptions)) + m.answers.Project.Model = projectModelOptions[m.projectIndex] + case initwizard.StepLicense: + m.licenseIndex = wrapIndex(m.licenseIndex+delta, len(m.licenseOptions)) + if len(m.licenseOptions) > 0 { + m.answers.License.SPDXID = m.licenseOptions[m.licenseIndex] + } + case initwizard.StepHeaderStyle: + m.styleIndex = wrapIndex(m.styleIndex+delta, len(headerStyleOptions)) + m.answers.HeaderStyle.Style = headerStyleOptions[m.styleIndex] + } +} + +func wrapIndex(value, size int) int { + if size == 0 { + return 0 + } + for value < 0 { + value += size + } + return value % size +} + +func (m *initWizardModel) toggleBool(key string) { + if m.step != initwizard.StepLicenseFiles { + return + } + switch key { + case "y": + m.answers.LicenseFiles.Manage = true + case "n": + m.answers.LicenseFiles.Manage = false + default: + m.answers.LicenseFiles.Manage = !m.answers.LicenseFiles.Manage + } +} + +func (m initWizardModel) usesTextInput() bool { + return m.step == initwizard.StepIdentity || m.step == initwizard.StepCoverage +} + +func (m *initWizardModel) setInput() { + ti := textinput.New() + switch m.step { + case initwizard.StepIdentity: + ti.Placeholder = "holder | year, for example Acme, LLC | git" + ti.SetValue(strings.TrimSpace(m.answers.Identity.Holder + " | " + m.answers.Identity.Year)) + ti.Focus() + case initwizard.StepCoverage: + ti.Placeholder = "exclude globs, comma-separated" + ti.SetValue(strings.Join(m.answers.Coverage.Exclude, ", ")) + ti.Focus() + } + m.input = ti +} + +func (m *initWizardModel) commitInput() { + switch m.step { + case initwizard.StepIdentity: + holder, year, ok := strings.Cut(m.input.Value(), "|") + if ok { + m.answers.Identity.Holder = strings.TrimSpace(holder) + m.answers.Identity.Year = strings.TrimSpace(year) + return + } + m.answers.Identity.Holder = strings.TrimSpace(m.input.Value()) + case initwizard.StepCoverage: + m.answers.Coverage.Exclude = splitCSV(m.input.Value()) + } +} + +func splitCSV(raw string) []string { + var out []string + for _, item := range strings.Split(raw, ",") { + item = strings.TrimSpace(item) + if item != "" { + out = append(out, item) + } + } + return out +} + +func runInitWizard(path string, a initwizard.Answers) (initwizard.Answers, error) { + program := tea.NewProgram( + newInitWizardModel(path, a), + tea.WithInput(os.Stdin), + tea.WithOutput(os.Stderr), + tea.WithAltScreen(), + ) + final, err := program.Run() + if err != nil { + return a, err + } + m, ok := final.(initWizardModel) + if !ok { + return a, fmt.Errorf("init wizard returned unexpected model") + } + if !m.answers.Review.Confirmed { + return a, initwizard.ErrAborted + } + return m.answers, nil +} + +// collectInteractive runs the wizard when interactive is true, otherwise returning +// the flag-derived answers unchanged for deterministic non-TTY behavior. +func collectInteractive(path string, a initwizard.Answers, interactive bool) (initwizard.Answers, error) { + if !interactive { + return a, nil + } + return runInitWizard(path, a) } diff --git a/internal/initwizard/model.go b/internal/initwizard/model.go new file mode 100644 index 0000000..f11cf44 --- /dev/null +++ b/internal/initwizard/model.go @@ -0,0 +1,127 @@ +// Package initwizard defines the structured answer model shared by the init +// command and the interactive collector. +package initwizard + +import "errors" + +// ErrAborted is returned when the operator exits the interactive wizard without +// confirming the review step. +var ErrAborted = errors.New("init wizard aborted") + +// ProjectModel describes the licensing posture the wizard is collecting for. +type ProjectModel string + +const ( + // ProjectModelOpenSource is for public source distributed under an SPDX license. + ProjectModelOpenSource ProjectModel = "open-source" + // ProjectModelPrivateInternal is for private source with internal policy needs. + ProjectModelPrivateInternal ProjectModel = "private-internal" + // ProjectModelExistingProject is for an existing repo where current files guide defaults. + ProjectModelExistingProject ProjectModel = "existing-project" + // ProjectModelAdvancedManual is for explicit flag or manual wizard choices. + ProjectModelAdvancedManual ProjectModel = "advanced-manual" +) + +// Step is the high-level screen/state currently active in the collector. +type Step int + +const ( + // StepProjectModel collects the project licensing model. + StepProjectModel Step = iota + // StepLicense collects the SPDX or future private license choice. + StepLicense + // StepIdentity collects holder and year policy values. + StepIdentity + // StepHeaderStyle collects the source header style. + StepHeaderStyle + // StepLicenseFiles collects top-level license file management intent. + StepLicenseFiles + // StepCoverage collects include and exclude coverage choices. + StepCoverage + // StepReview presents the final review before writing config. + StepReview +) + +// Answers is the structured payload returned by the interactive collector. +type Answers struct { + // Project records the project model choice. + Project ProjectAnswer + // License records the target license choice. + License LicenseAnswer + // Identity records copyright holder and year policy. + Identity IdentityAnswer + // HeaderStyle records the source header format. + HeaderStyle HeaderStyleAnswer + // LicenseFiles records whether top-level license files should be managed. + LicenseFiles LicenseFilesAnswer + // Coverage records include and exclude file scope answers. + Coverage CoverageAnswer + // Review records the final confirmation state. + Review ReviewAnswer +} + +// ProjectAnswer holds the project model selection. +type ProjectAnswer struct { + // Model is the selected project model. + Model ProjectModel +} + +// LicenseAnswer holds the target license selection. +type LicenseAnswer struct { + // SPDXID is the SPDX identifier selected for generated config. + SPDXID string + // Private marks a future private/internal license path without SPDX rendering. + Private bool +} + +// IdentityAnswer holds copyright identity answers. +type IdentityAnswer struct { + // Holder is the copyright holder text. + Holder string + // Year is the raw year policy token. + Year string +} + +// HeaderStyleAnswer holds the raw header style token. +type HeaderStyleAnswer struct { + // Style is reuse, notice, or reuse+notice. + Style string +} + +// LicenseFilesAnswer records license file management intent. +type LicenseFilesAnswer struct { + // Manage enables top-level LICENSE and LICENSES/.txt management. + Manage bool +} + +// CoverageAnswer records source file scope selections. +type CoverageAnswer struct { + // Include is the selected include glob list. + Include []string + // Exclude is the selected exclude glob list. + Exclude []string +} + +// ReviewAnswer records whether the final review was confirmed. +type ReviewAnswer struct { + // Confirmed is true when the operator accepted the review screen. + Confirmed bool +} + +// Preview is the narrow shell expected from the future preview engine. +type Preview struct { + // Source is the rendered example source preview. + Source string + // Config is the rendered config preview. + Config string + // LicenseFiles is the license file behavior summary. + LicenseFiles string + // Coverage is the file coverage summary. + Coverage string +} + +// PreviewProvider is intentionally narrow until the preview engine lands. +type PreviewProvider interface { + // Preview returns display text for the current answers. + Preview(Answers) (Preview, error) +} -- 2.54.0 From f80ab905f2f8b607eac8aadc710abf27da5af510 Mon Sep 17 00:00:00 2001 From: James Maes Date: Thu, 4 Jun 2026 16:36:05 -0500 Subject: [PATCH 05/14] feat(init): add source preview engine Refs #29 --- internal/filetype/filetype.go | 6 + internal/filetype/filetype_test.go | 1 + internal/initwizard/catalog.go | 344 ++++++++++++++++++++++++++++ internal/initwizard/catalog_test.go | 169 ++++++++++++++ 4 files changed, 520 insertions(+) create mode 100644 internal/initwizard/catalog.go create mode 100644 internal/initwizard/catalog_test.go diff --git a/internal/filetype/filetype.go b/internal/filetype/filetype.go index 1e01568..1bea81c 100644 --- a/internal/filetype/filetype.go +++ b/internal/filetype/filetype.go @@ -74,6 +74,12 @@ var builtin = []model.FileType{ CommentStyle: block("/*", "*/"), PreserveFirst: []model.PreserveRule{after(model.PreserveBOM)}, }, + { + Name: "C#", + Extensions: []string{".cs"}, + CommentStyle: block("/*", "*/"), + PreserveFirst: []model.PreserveRule{after(model.PreserveBOM)}, + }, { Name: "C/C++", Extensions: []string{".c", ".cc", ".cpp", ".cxx", ".h", ".hh", ".hpp", ".hxx", ".m", ".mm"}, diff --git a/internal/filetype/filetype_test.go b/internal/filetype/filetype_test.go index 9e594b7..dc28fd3 100644 --- a/internal/filetype/filetype_test.go +++ b/internal/filetype/filetype_test.go @@ -21,6 +21,7 @@ func TestLookupTable(t *testing.T) { {"build.gradle.kts", "Kotlin", true, true, false}, {"main.go", "Go", true, true, false}, {"App.swift", "Swift", true, true, false}, + {"Program.cs", "C#", true, true, false}, {"lib.c", "C/C++", true, true, false}, {"lib.cpp", "C/C++", true, true, false}, {"lib.h", "C/C++", true, true, false}, diff --git a/internal/initwizard/catalog.go b/internal/initwizard/catalog.go new file mode 100644 index 0000000..6a885af --- /dev/null +++ b/internal/initwizard/catalog.go @@ -0,0 +1,344 @@ +// Package initwizard contains pure business logic for the interactive init flow. +package initwizard + +import ( + "fmt" + "path/filepath" + "strings" + + "github.com/KofTwentyTwo/license-tool/internal/config" + "github.com/KofTwentyTwo/license-tool/internal/model" + "github.com/KofTwentyTwo/license-tool/internal/render" + "github.com/KofTwentyTwo/license-tool/internal/spdx" +) + +// LanguageFamily is the stable label for a source preview sample. +type LanguageFamily string + +const ( + LanguageTypeScriptJavaScript LanguageFamily = "TypeScript/JavaScript" + LanguagePython LanguageFamily = "Python" + LanguageJava LanguageFamily = "Java" + LanguageGo LanguageFamily = "Go" + LanguageC LanguageFamily = "C" + LanguageCPlusPlus LanguageFamily = "C++" + LanguageCSharp LanguageFamily = "C#" + LanguagePHP LanguageFamily = "PHP" + LanguageRuby LanguageFamily = "Ruby" + LanguageSwift LanguageFamily = "Swift" + LanguageKotlin LanguageFamily = "Kotlin" + LanguageRust LanguageFamily = "Rust" + LanguageShell LanguageFamily = "Shell" + LanguagePowerShell LanguageFamily = "PowerShell" + LanguageR LanguageFamily = "R" +) + +// Sample is one deterministic source file the init wizard can show in a preview. +type Sample struct { + Language LanguageFamily + Path string + Source string +} + +// SourcePreviewInput is the complete pure input for rendering a sample source +// preview. ResolvedYear is passed in so callers own clocks and git history. +type SourcePreviewInput struct { + Config model.Config + Sample Sample + ResolvedYear string +} + +// SourcePreview is a rendered example source file with the generated header applied. +type SourcePreview struct { + Language LanguageFamily + Path string + Content string +} + +var catalog = []Sample{ + { + Language: LanguageTypeScriptJavaScript, + Path: "example.ts", + Source: strings.TrimLeft(` +export function greet(name: string): string { + return "Hello, " + name; +} +`, "\n"), + }, + { + Language: LanguagePython, + Path: "example.py", + Source: strings.TrimLeft(` +def greet(name: str) -> str: + return f"Hello, {name}" +`, "\n"), + }, + { + Language: LanguageJava, + Path: "Example.java", + Source: strings.TrimLeft(` +package preview; + +public class Example { + public String greet(String name) { + return "Hello, " + name; + } +} +`, "\n"), + }, + { + Language: LanguageGo, + Path: "example.go", + Source: strings.TrimLeft(` +package main + +func greet(name string) string { + return "Hello, " + name +} +`, "\n"), + }, + { + Language: LanguageC, + Path: "example.c", + Source: strings.TrimLeft(` +#include + +void greet(const char *name) { + printf("Hello, %s\n", name); +} +`, "\n"), + }, + { + Language: LanguageCPlusPlus, + Path: "example.cpp", + Source: strings.TrimLeft(` +#include + +void greet(const std::string& name) { + std::cout << "Hello, " << name << std::endl; +} +`, "\n"), + }, + { + Language: LanguageCSharp, + Path: "Example.cs", + Source: strings.TrimLeft(` +public class Example +{ + public string Greet(string name) + { + return "Hello, " + name; + } +} +`, "\n"), + }, + { + Language: LanguagePHP, + Path: "example.php", + Source: strings.TrimLeft(` + String { + "Hello, \(name)" +} +`, "\n"), + }, + { + Language: LanguageKotlin, + Path: "Example.kt", + Source: strings.TrimLeft(` +package preview + +fun greet(name: String): String { + return "Hello, $name" +} +`, "\n"), + }, + { + Language: LanguageRust, + Path: "example.rs", + Source: strings.TrimLeft(` +fn greet(name: &str) -> String { + format!("Hello, {}", name) +} +`, "\n"), + }, + { + Language: LanguageShell, + Path: "example.sh", + Source: strings.TrimLeft(` +#!/usr/bin/env bash + +greet() { + printf 'Hello, %s\n' "$1" +} +`, "\n"), + }, + { + Language: LanguagePowerShell, + Path: "example.ps1", + Source: strings.TrimLeft(` +function Get-Greeting { + param([string]$Name) + "Hello, $Name" +} +`, "\n"), + }, + { + Language: LanguageR, + Path: "example.R", + Source: strings.TrimLeft(` +greet <- function(name) { + paste("Hello", name) +} +`, "\n"), + }, +} + +var extensionFamilies = map[string]LanguageFamily{ + ".ts": LanguageTypeScriptJavaScript, + ".tsx": LanguageTypeScriptJavaScript, + ".mts": LanguageTypeScriptJavaScript, + ".cts": LanguageTypeScriptJavaScript, + ".js": LanguageTypeScriptJavaScript, + ".jsx": LanguageTypeScriptJavaScript, + ".mjs": LanguageTypeScriptJavaScript, + ".cjs": LanguageTypeScriptJavaScript, + ".py": LanguagePython, + ".pyi": LanguagePython, + ".java": LanguageJava, + ".go": LanguageGo, + ".c": LanguageC, + ".h": LanguageC, + ".cc": LanguageCPlusPlus, + ".cpp": LanguageCPlusPlus, + ".cxx": LanguageCPlusPlus, + ".hh": LanguageCPlusPlus, + ".hpp": LanguageCPlusPlus, + ".hxx": LanguageCPlusPlus, + ".cs": LanguageCSharp, + ".php": LanguagePHP, + ".phtml": LanguagePHP, + ".rb": LanguageRuby, + ".swift": LanguageSwift, + ".kt": LanguageKotlin, + ".kts": LanguageKotlin, + ".rs": LanguageRust, + ".sh": LanguageShell, + ".bash": LanguageShell, + ".zsh": LanguageShell, + ".ksh": LanguageShell, + ".ps1": LanguagePowerShell, + ".psm1": LanguagePowerShell, + ".r": LanguageR, +} + +// Catalog returns the full, stable source preview catalog. +func Catalog() []Sample { + return append([]Sample(nil), catalog...) +} + +// SelectSample returns the catalog sample that best matches repo file paths. If no +// catalog language is detected, it returns the C fallback. +func SelectSample(paths []string) Sample { + detected := make(map[LanguageFamily]bool) + for _, path := range paths { + if sample, ok := SampleForPath(path); ok { + detected[sample.Language] = true + } + } + for _, sample := range catalog { + if detected[sample.Language] { + return sample + } + } + return fallbackSample() +} + +// SampleForPath maps one repository path to its preview sample when the extension +// belongs to the supported catalog. +func SampleForPath(path string) (Sample, bool) { + ext := strings.ToLower(filepath.Ext(filepath.Base(path))) + if ext == "" { + return Sample{}, false + } + family, ok := extensionFamilies[ext] + if !ok { + return Sample{}, false + } + return sampleForFamily(family) +} + +// BuildSourcePreview renders a generated header and inserts it into the selected +// sample source using the same SPDX, filetype, and render behavior as apply. +func BuildSourcePreview(in SourcePreviewInput) (SourcePreview, error) { + sample := in.Sample + if sample.Language == "" { + sample = fallbackSample() + } + if in.ResolvedYear == "" { + return SourcePreview{}, fmt.Errorf("initwizard: resolved year is required") + } + license, ok := spdx.Lookup(in.Config.License) + if !ok { + return SourcePreview{}, fmt.Errorf("initwizard: unknown license %q", in.Config.License) + } + ft, ok := config.LookupFunc(in.Config)(sample.Path) + if !ok { + return SourcePreview{}, fmt.Errorf("initwizard: no file type for sample %q", sample.Path) + } + header, err := render.Header(render.HeaderInput{ + License: license, + Holder: in.Config.Holder, + Year: in.ResolvedYear, + Style: in.Config.Style, + FileType: ft, + }) + if err != nil { + return SourcePreview{}, err + } + content, _ := render.Insert([]byte(sample.Source), ft, header) + return SourcePreview{ + Language: sample.Language, + Path: sample.Path, + Content: string(content), + }, nil +} + +// BuildYAMLPreview renders the .license-tool.yaml preview for cfg. +func BuildYAMLPreview(cfg model.Config) ([]byte, error) { + return config.RenderFile(cfg) +} + +func fallbackSample() Sample { + sample, _ := sampleForFamily(LanguageC) + return sample +} + +func sampleForFamily(family LanguageFamily) (Sample, bool) { + for _, sample := range catalog { + if sample.Language == family { + return sample, true + } + } + return Sample{}, false +} diff --git a/internal/initwizard/catalog_test.go b/internal/initwizard/catalog_test.go new file mode 100644 index 0000000..a325cd2 --- /dev/null +++ b/internal/initwizard/catalog_test.go @@ -0,0 +1,169 @@ +package initwizard + +import ( + "testing" + + "github.com/KofTwentyTwo/license-tool/internal/config" + "github.com/KofTwentyTwo/license-tool/internal/model" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCatalogContainsExactlySupportedLanguageFamiliesInStableOrder(t *testing.T) { + got := Catalog() + require.Len(t, got, 15) + + want := []LanguageFamily{ + LanguageTypeScriptJavaScript, + LanguagePython, + LanguageJava, + LanguageGo, + LanguageC, + LanguageCPlusPlus, + LanguageCSharp, + LanguagePHP, + LanguageRuby, + LanguageSwift, + LanguageKotlin, + LanguageRust, + LanguageShell, + LanguagePowerShell, + LanguageR, + } + for i, family := range want { + assert.Equal(t, family, got[i].Language) + assert.NotEmpty(t, got[i].Path) + assert.NotEmpty(t, got[i].Source) + } +} + +func TestCatalogReturnsACopy(t *testing.T) { + first := Catalog() + require.NotEmpty(t, first) + first[0].Language = LanguagePython + + second := Catalog() + assert.Equal(t, LanguageTypeScriptJavaScript, second[0].Language) +} + +func TestSelectSamplePrefersDetectedCatalogFamiliesInCatalogOrder(t *testing.T) { + got := SelectSample([]string{ + "cmd/license-tool/main.go", + "web/src/app.ts", + }) + + assert.Equal(t, LanguageTypeScriptJavaScript, got.Language) + assert.Equal(t, "example.ts", got.Path) +} + +func TestSelectSampleFallsBackToCWhenNoCatalogLanguageIsDetected(t *testing.T) { + got := SelectSample([]string{ + "README.md", + "package.json", + "styles/app.css", + }) + + assert.Equal(t, LanguageC, got.Language) + assert.Equal(t, "example.c", got.Path) +} + +func TestSelectSampleSplitsCAndCPlusPlusExtensions(t *testing.T) { + cases := []struct { + name string + path string + want LanguageFamily + }{ + {name: "c source", path: "src/main.c", want: LanguageC}, + {name: "c header", path: "include/project.h", want: LanguageC}, + {name: "cpp source", path: "src/main.cpp", want: LanguageCPlusPlus}, + {name: "cpp header", path: "include/project.hpp", want: LanguageCPlusPlus}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := SelectSample([]string{tc.path}) + assert.Equal(t, tc.want, got.Language) + }) + } +} + +func TestSelectSampleDetectsCSharp(t *testing.T) { + got := SelectSample([]string{"src/Program.cs"}) + + assert.Equal(t, LanguageCSharp, got.Language) + assert.Equal(t, "Example.cs", got.Path) +} + +func TestBuildSourcePreviewAppliesGeneratedHeaderToSelectedSample(t *testing.T) { + sample := SelectSample([]string{"cmd/license-tool/main.go"}) + preview, err := BuildSourcePreview(SourcePreviewInput{ + Config: model.Config{ + License: "MIT", + Holder: "Acme, Inc.", + Style: model.StyleReuse, + }, + Sample: sample, + ResolvedYear: "2026", + }) + require.NoError(t, err) + + assert.Equal(t, LanguageGo, preview.Language) + assert.Equal(t, "example.go", preview.Path) + assert.Contains(t, preview.Content, "SPDX-FileCopyrightText: 2026 Acme, Inc.") + assert.Contains(t, preview.Content, "SPDX-License-Identifier: MIT") + assert.Contains(t, preview.Content, "package main") + assert.Less(t, + indexOf(t, preview.Content, "SPDX-License-Identifier: MIT"), + indexOf(t, preview.Content, "package main"), + ) +} + +func TestBuildSourcePreviewUsesCSharpFileType(t *testing.T) { + sample := SelectSample([]string{"src/Program.cs"}) + preview, err := BuildSourcePreview(SourcePreviewInput{ + Config: model.Config{ + License: "MIT", + Holder: "Acme, Inc.", + Style: model.StyleReuse, + }, + Sample: sample, + ResolvedYear: "2026", + }) + require.NoError(t, err) + + assert.Equal(t, LanguageCSharp, preview.Language) + assert.Contains(t, preview.Content, "/*") + assert.Contains(t, preview.Content, "*/") + assert.Contains(t, preview.Content, "public class Example") +} + +func TestBuildYAMLPreviewDelegatesToConfigRenderFile(t *testing.T) { + cfg := model.Config{ + License: "MIT", + Holder: "Acme, Inc.", + Year: model.YearSpec{Kind: model.YearExplicit, Start: 2026}, + Style: model.StyleReuse, + ManageLicenseFile: true, + Excludes: []string{"vendor/**"}, + } + + got, err := BuildYAMLPreview(cfg) + require.NoError(t, err) + want, err := config.RenderFile(cfg) + require.NoError(t, err) + + assert.Equal(t, string(want), string(got)) +} + +func indexOf(t *testing.T, s, substr string) int { + t.Helper() + idx := -1 + for i := range s { + if len(s[i:]) >= len(substr) && s[i:i+len(substr)] == substr { + idx = i + break + } + } + require.NotEqualf(t, -1, idx, "%q not found in %q", substr, s) + return idx +} -- 2.54.0 From 44d49860631cc11996a2470afd0c7bb379c5da73 Mon Sep 17 00:00:00 2001 From: James Maes Date: Mon, 8 Jun 2026 09:28:03 -0500 Subject: [PATCH 06/14] feat(init): add pane-based TUI wizard Refs #29 --- .testcoverage.yml | 12 +- CHANGELOG.md | 5 + DEVELOPERS.md | 2 + README.md | 12 +- cmd/license-tool/commands.go | 2 +- cmd/license-tool/commands_test.go | 3 + cmd/license-tool/wizard.go | 705 ++++++++++++++++++++++++++-- docs/PLAN-GH-29-init-tui-wizard.md | 14 +- docs/SESSION-STATE.md | 6 +- docs/TODO.md | 28 +- go.mod | 12 +- go.sum | 26 - internal/initwizard/catalog.go | 1 + internal/initwizard/catalog_test.go | 93 ++++ internal/initwizard/model.go | 18 - 15 files changed, 812 insertions(+), 127 deletions(-) diff --git a/.testcoverage.yml b/.testcoverage.yml index 0a73db0..29ca3b6 100644 --- a/.testcoverage.yml +++ b/.testcoverage.yml @@ -34,12 +34,12 @@ threshold: # and defense-in-depth. It is not part of the shipped binary. # # 3. cmd/license-tool/wizard.go -# The interactive init wizard is a thin huh-backed TUI shell: it builds the form, -# binds answers, and runs the terminal event loop (form.Run). Like the main() -# shim, it has no business logic of its own -- all validation and parsing live in -# answersToConfig (in commands.go) and the config/spdx packages, which ARE -# covered. Driving a real huh form requires an interactive PTY that an in-process -# unit test cannot provide, so it is excluded for the same reason as main.go. +# The interactive init wizard is a Bubble Tea terminal shell: it renders panels, +# binds answers, and runs the terminal event loop. Like the main() shim, it has +# no write-path validation of its own; answersToConfig, config, spdx, and +# internal/initwizard carry the covered behavior. Driving a real TUI requires an +# interactive PTY that an in-process unit test cannot provide, so it is excluded +# for the same reason as main.go. exclude: paths: - ^cmd/license-tool/main\.go$ diff --git a/CHANGELOG.md b/CHANGELOG.md index dff4fe0..90608f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- `init` now opens a full-screen Bubble Tea wizard with project-model, license, identity, header-style, license-file, coverage, and review steps. +- Added live example source previews for 15 language families, plus `.license-tool.yaml` preview and C fallback when no supported source language is detected. +- Added persisted `include` config support and wired wizard/flag include values into audit, apply, license, and init behavior. + ## [0.3.0] - 2026-06-04 ### Install diff --git a/DEVELOPERS.md b/DEVELOPERS.md index f705b79..5aa7011 100644 --- a/DEVELOPERS.md +++ b/DEVELOPERS.md @@ -2,4 +2,6 @@ Use feature branches for normal work, merge through `develop`, and promote only green, release-ready commits to `main`. The required local quality gate is the same shape as CI: `gofmt -l .`, `go vet ./...`, `golangci-lint run`, race-enabled tests with `cover.out`, the configured 100% coverage checker, and `go build ./...`. +The interactive `init` wizard keeps terminal rendering in `cmd/license-tool/wizard.go`. Covered behavior belongs in `answersToConfig`, `internal/config`, and `internal/initwizard`; the TUI shell should stay thin and delegate preview rendering to the pure initwizard helpers. + Releases are documented in [RELEASING.md](RELEASING.md). In short: update [CHANGELOG.md](CHANGELOG.md), run `./scripts/verify-release.sh`, commit the release notes with a conventional commit, push `main`, wait for CI and CodeQL, then push a signed semver tag such as `v0.3.0`. The tag triggers GoReleaser, which creates the GitHub Release and publishes the Homebrew cask. diff --git a/README.md b/README.md index f31a1c3..de5ceda 100644 --- a/README.md +++ b/README.md @@ -114,15 +114,17 @@ license-tool license --license AGPL-3.0-or-later --holder "Kingsrook, LLC" --wri ### init -Scaffold a `.license-tool.yaml` for the repo. On a TTY, `init` runs a wizard with -a filterable SPDX license picker that lists common licenses first, then prompts -for holder, year policy, header style, and whether to manage the top-level -`LICENSE` files. The holder prompt requires a non-empty value, and the license -and year prompts validate against the same parsers used by the flag path. +Scaffold a `.license-tool.yaml` for the repo. On a TTY, `init` opens a +full-screen wizard with a progress rail, active controls, and a live preview +panel. The preview renders the current answers onto an example source file, +shows the YAML that will be written, summarizes license-file behavior, and shows +include/exclude scope. The example source is chosen from supported language +families detected in the repo, with C as the fallback. ```bash license-tool init license-tool init --license MIT --holder "Example, Inc." --year git --style reuse+notice +license-tool init --include "src/**" --exclude "**/generated/**" ``` In a non-TTY environment, `init` skips the wizard, uses only the supplied flags, diff --git a/cmd/license-tool/commands.go b/cmd/license-tool/commands.go index 997c80f..898626c 100644 --- a/cmd/license-tool/commands.go +++ b/cmd/license-tool/commands.go @@ -434,6 +434,7 @@ func answersToConfig(a initwizard.Answers) (model.Config, error) { cfg.Style = st } cfg.ManageLicenseFile = a.LicenseFiles.Manage + cfg.Includes = append([]string(nil), a.Coverage.Include...) cfg.Excludes = append([]string(nil), a.Coverage.Exclude...) return cfg, nil } @@ -466,7 +467,6 @@ func newInitCmd(shared *sharedFlags) *cobra.Command { if err != nil { return usageError(err) } - cfg.Includes = shared.include target, err := config.WriteFile(path, cfg, f.force) if err != nil { return writeOrInternalError(err) diff --git a/cmd/license-tool/commands_test.go b/cmd/license-tool/commands_test.go index 4a43ad0..811e67b 100644 --- a/cmd/license-tool/commands_test.go +++ b/cmd/license-tool/commands_test.go @@ -989,6 +989,7 @@ func TestAnswersToConfig(t *testing.T) { Manage: false, }, Coverage: initwizard.CoverageAnswer{ + Include: []string{"src/**"}, Exclude: []string{"**/vendor/**"}, }, }) @@ -1000,6 +1001,7 @@ func TestAnswersToConfig(t *testing.T) { assert.Equal(t, 2026, cfg.Year.End) assert.Equal(t, model.StyleReuse, cfg.Style) assert.False(t, cfg.ManageLicenseFile) + assert.Equal(t, []string{"src/**"}, cfg.Includes) assert.Equal(t, []string{"**/vendor/**"}, cfg.Excludes) }) @@ -1185,6 +1187,7 @@ func TestInitCommandConsumesCollectorAnswers(t *testing.T) { assert.Equal(t, model.YearCurrent, cfg.Year.Kind) assert.Equal(t, model.StyleNotice, cfg.Style) assert.False(t, cfg.ManageLicenseFile) + assert.Equal(t, []string{"cmd/**"}, cfg.Includes) assert.Equal(t, []string{"generated/**"}, cfg.Excludes) } diff --git a/cmd/license-tool/wizard.go b/cmd/license-tool/wizard.go index 183b240..064f930 100644 --- a/cmd/license-tool/wizard.go +++ b/cmd/license-tool/wizard.go @@ -2,13 +2,20 @@ package main import ( "fmt" + "io/fs" "os" + "path/filepath" + "sort" "strings" + "time" "github.com/charmbracelet/bubbles/textinput" tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/KofTwentyTwo/license-tool/internal/config" "github.com/KofTwentyTwo/license-tool/internal/initwizard" + "github.com/KofTwentyTwo/license-tool/internal/model" "github.com/KofTwentyTwo/license-tool/internal/spdx" ) @@ -20,6 +27,23 @@ var ( initwizard.ProjectModelAdvancedManual, } headerStyleOptions = []string{"reuse", "notice", "reuse+notice"} + + appTitleStyle = lipgloss.NewStyle(). + Bold(true). + Foreground(lipgloss.Color("15")). + Background(lipgloss.Color("62")). + Padding(0, 1) + paneStyle = lipgloss.NewStyle(). + Border(lipgloss.RoundedBorder()). + BorderForeground(lipgloss.Color("240")). + Padding(0, 1) + activePaneStyle = paneStyle. + BorderForeground(lipgloss.Color("62")) + paneTitleStyle = lipgloss.NewStyle(). + Bold(true). + Foreground(lipgloss.Color("15")) + mutedStyle = lipgloss.NewStyle(). + Foreground(lipgloss.Color("245")) ) // licenseSelectOptions builds the license picker values: common renderable SPDX ids @@ -47,6 +71,8 @@ type initWizardModel struct { step initwizard.Step input textinput.Model licenseOptions []string + licenseFilter string + previewPaths []string projectIndex int licenseIndex int styleIndex int @@ -60,6 +86,7 @@ func newInitWizardModel(root string, answers initwizard.Answers) initWizardModel answers: answers, step: initwizard.StepProjectModel, licenseOptions: licenseSelectOptions(), + previewPaths: previewCandidatePaths(root), } if m.answers.Project.Model == "" { m.answers.Project.Model = initwizard.ProjectModelOpenSource @@ -75,6 +102,9 @@ func newInitWizardModel(root string, answers initwizard.Answers) initWizardModel } m.projectIndex = indexProjectModel(projectModelOptions, m.answers.Project.Model) m.licenseIndex = indexString(m.licenseOptions, m.answers.License.SPDXID) + if len(m.licenseOptions) > 0 && m.answers.License.SPDXID != m.licenseOptions[m.licenseIndex] { + m.answers.License.SPDXID = m.licenseOptions[m.licenseIndex] + } m.styleIndex = indexString(headerStyleOptions, m.answers.HeaderStyle.Style) m.setInput() return m @@ -107,8 +137,14 @@ func (m initWizardModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { case tea.WindowSizeMsg: m.width = msg.Width m.height = msg.Height + m.input.Width = m.inputWidth() return m, nil case tea.KeyMsg: + if m.step == initwizard.StepLicense { + if m.handleLicenseKey(msg) { + return m, nil + } + } switch msg.String() { case "ctrl+c", "esc": m.answers.Review.Confirmed = false @@ -119,6 +155,18 @@ func (m initWizardModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { case "down", "j": m.moveSelection(1) return m, nil + case "pgup": + m.moveSelection(-10) + return m, nil + case "pgdown": + m.moveSelection(10) + return m, nil + case "home": + m.moveSelectionToStart() + return m, nil + case "end": + m.moveSelectionToEnd() + return m, nil case " ", "y", "n": if m.step == initwizard.StepLicenseFiles { m.toggleBool(msg.String()) @@ -131,6 +179,9 @@ func (m initWizardModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil } case "enter": + if m.step == initwizard.StepLicense && len(m.filteredLicenseChoices()) == 0 { + return m, nil + } m.commitInput() if m.step == initwizard.StepReview { m.answers.Review.Confirmed = true @@ -150,23 +201,36 @@ func (m initWizardModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } func (m initWizardModel) View() string { - var b strings.Builder - fmt.Fprintf(&b, "license-tool init\n") - if m.root != "" { - fmt.Fprintf(&b, "path: %s\n", m.root) + width := m.width + if width <= 0 { + width = 120 } - fmt.Fprintf(&b, "\n%s\n\n", m.stepTitle()) - b.WriteString(m.stepBody()) - fmt.Fprintf(&b, "\n\n%s\n", m.previewSummary()) - fmt.Fprintf(&b, "\nenter next, backspace back, esc cancel") - if m.step == initwizard.StepReview { - fmt.Fprintf(&b, "\nenter confirms and writes .license-tool.yaml") + height := m.height + if height <= 0 { + height = 34 } - return b.String() + + header := m.headerView(width) + footer := m.footerView(width) + bodyHeight := height - lipgloss.Height(header) - lipgloss.Height(footer) - 2 + if bodyHeight < 14 { + bodyHeight = 14 + } + + return strings.TrimRight(lipgloss.JoinVertical( + lipgloss.Left, + header, + m.bodyView(width, bodyHeight), + footer, + ), "\n") } func (m initWizardModel) stepTitle() string { - switch m.step { + return stepTitle(m.step) +} + +func stepTitle(step initwizard.Step) string { + switch step { case initwizard.StepProjectModel: return "Project model" case initwizard.StepLicense: @@ -184,28 +248,168 @@ func (m initWizardModel) stepTitle() string { } } -func (m initWizardModel) stepBody() string { +func (m initWizardModel) headerView(width int) string { + title := "license-tool init" + if m.root != "" { + title += " " + m.root + } + return appTitleStyle.Width(maxInt(1, width-2)).Render(title) +} + +func (m initWizardModel) footerView(width int) string { + keys := "enter next" + if m.step == initwizard.StepReview { + keys = "enter write" + } + keys += " | back back | esc cancel | arrows/pg move" + if m.step == initwizard.StepLicense { + keys += " | type filter | ctrl+u clear" + } + return mutedStyle.Width(width).Render(keys) +} + +func (m initWizardModel) bodyView(width int, height int) string { + if width < 100 { + topHeight := height / 2 + if height >= 18 && topHeight < 11 { + topHeight = 11 + } + if height < 18 && topHeight < 7 { + topHeight = 7 + } + if topHeight > height-7 { + topHeight = height - 7 + } + if topHeight < 6 { + topHeight = 6 + } + previewHeight := height - topHeight - 1 + if previewHeight < 6 { + previewHeight = 6 + topHeight = maxInt(6, height-previewHeight-1) + } + navWidth := 22 + if width < 70 { + navWidth = 18 + } + controlWidth := maxInt(24, width-navWidth-1) + top := lipgloss.JoinHorizontal( + lipgloss.Top, + m.renderPane("Steps", m.navigationBody(), navWidth, topHeight, false), + " ", + m.renderPane(m.stepTitle(), m.stepBody(topHeight-3), controlWidth, topHeight, true), + ) + return lipgloss.JoinVertical( + lipgloss.Left, + top, + m.renderPane("Live preview", m.previewSummary(), width, previewHeight, false), + ) + } + + gutter := 1 + navWidth := 24 + previewWidth := width / 2 + if previewWidth < 46 { + previewWidth = 46 + } + if previewWidth > 72 { + previewWidth = 72 + } + controlWidth := width - navWidth - previewWidth - gutter*2 + if controlWidth < 34 { + controlWidth = 34 + previewWidth = width - navWidth - controlWidth - gutter*2 + } + + return lipgloss.JoinHorizontal( + lipgloss.Top, + m.renderPane("Steps", m.navigationBody(), navWidth, height, false), + strings.Repeat(" ", gutter), + m.renderPane(m.stepTitle(), m.stepBody(height-3), controlWidth, height, true), + strings.Repeat(" ", gutter), + m.renderPane("Live preview", m.previewSummary(), previewWidth, height, false), + ) +} + +func (m initWizardModel) renderPane(title string, content string, width int, height int, active bool) string { + if width < 12 { + width = 12 + } + if height < 6 { + height = 6 + } + innerWidth := maxInt(1, width-4) + innerHeight := maxInt(1, height-2) + body := paneTitleStyle.Render(title) + "\n" + fitText(content, innerWidth, innerHeight-1) + style := paneStyle + if active { + style = activePaneStyle + } + return style.Width(innerWidth).Height(innerHeight).Render(body) +} + +func (m initWizardModel) stepBody(rows int) string { switch m.step { case initwizard.StepProjectModel: - return optionList(projectModelsToStrings(projectModelOptions), m.projectIndex) + return selectionList(projectModelsToStrings(projectModelOptions), m.projectIndex, rows) case initwizard.StepLicense: - return optionList(m.licenseOptions, m.licenseIndex) + return m.licenseBody(rows) case initwizard.StepIdentity: - return m.input.View() + return strings.Join([]string{ + "Copyright holder and year policy", + "", + m.input.View(), + "", + "Format: holder | year", + "Year accepts current, git, YYYY, or YYYY-YYYY.", + }, "\n") case initwizard.StepHeaderStyle: - return optionList(headerStyleOptions, m.styleIndex) + return selectionList(headerStyleOptions, m.styleIndex, rows) case initwizard.StepLicenseFiles: if m.answers.LicenseFiles.Manage { - return "Manage LICENSE and LICENSES/.txt: yes" + return "Manage LICENSE and LICENSES/.txt\n\nCurrent value: yes\n\nPress space, y, or n to change." } - return "Manage LICENSE and LICENSES/.txt: no" + return "Manage LICENSE and LICENSES/.txt\n\nCurrent value: no\n\nPress space, y, or n to change." case initwizard.StepCoverage: - return m.input.View() + return strings.Join([]string{ + "Default file scope", + "", + m.input.View(), + "", + "Format: include globs | exclude globs", + "Examples: src/** | **/generated/**, vendor/**", + "Leave include empty to scan all supported files.", + }, "\n") default: return m.reviewBody() } } +func (m initWizardModel) navigationBody() string { + steps := []initwizard.Step{ + initwizard.StepProjectModel, + initwizard.StepLicense, + initwizard.StepIdentity, + initwizard.StepHeaderStyle, + initwizard.StepLicenseFiles, + initwizard.StepCoverage, + initwizard.StepReview, + } + var b strings.Builder + fmt.Fprintf(&b, "Step %d/%d\n", int(m.step)+1, len(steps)) + for _, step := range steps { + mark := " " + if step < m.step { + mark = "x " + } + if step == m.step { + mark = "> " + } + fmt.Fprintf(&b, "%s%s\n", mark, stepTitle(step)) + } + return strings.TrimRight(b.String(), "\n") +} + func projectModelsToStrings(values []initwizard.ProjectModel) []string { out := make([]string, 0, len(values)) for _, value := range values { @@ -214,33 +418,112 @@ func projectModelsToStrings(values []initwizard.ProjectModel) []string { return out } -func optionList(values []string, selected int) string { +func selectionList(values []string, selected int, rows int) string { + if rows < 4 { + rows = 4 + } + visibleRows := rows - 2 + start := windowStart(selected, len(values), visibleRows) var b strings.Builder - for i, value := range values { + fmt.Fprintf(&b, "%-4s %s\n", "Sel", "Value") + fmt.Fprintf(&b, "%-4s %s\n", "---", "-----") + for i := start; i < len(values) && i < start+visibleRows; i++ { prefix := " " if i == selected { prefix = "> " } - fmt.Fprintf(&b, "%s%s\n", prefix, value) + fmt.Fprintf(&b, "%-4s %s\n", prefix, values[i]) + } + if len(values) > visibleRows { + fmt.Fprintf(&b, "\n%d/%d", selected+1, len(values)) } return strings.TrimRight(b.String(), "\n") } +func (m initWizardModel) licenseBody(rows int) string { + choices := m.filteredLicenseChoices() + filter := m.licenseFilter + if filter == "" { + filter = "(none)" + } + var b strings.Builder + fmt.Fprintf(&b, "Filter: %s Selected: %s\n", filter, m.answers.License.SPDXID) + if len(choices) == 0 { + b.WriteString("No matching renderable licenses.\n\nBackspace or ctrl+u to change the filter.") + return b.String() + } + + selectedPos := m.licenseChoicePosition(choices) + visibleRows := rows - 4 + if visibleRows < 4 { + visibleRows = 4 + } + start := windowStart(selectedPos, len(choices), visibleRows) + fmt.Fprintf(&b, "%-4s %-24s %s\n", "Sel", "SPDX id", "Group") + fmt.Fprintf(&b, "%-4s %-24s %s\n", "---", "-------", "-----") + for pos := start; pos < len(choices) && pos < start+visibleRows; pos++ { + choice := choices[pos] + mark := " " + if choice.index == m.licenseIndex { + mark = "> " + } + group := "other" + if isCommonLicense(choice.id) { + group = "common" + } + fmt.Fprintf(&b, "%-4s %-24s %s\n", mark, choice.id, group) + } + fmt.Fprintf(&b, "\n%d/%d matches, %d renderable total", selectedPos+1, len(choices), len(m.licenseOptions)) + return strings.TrimRight(b.String(), "\n") +} + func (m initWizardModel) reviewBody() string { - return strings.Join([]string{ - "Project model: " + string(m.answers.Project.Model), - "License: " + m.answers.License.SPDXID, - "Holder: " + m.answers.Identity.Holder, - "Year: " + m.answers.Identity.Year, - "Header style: " + m.answers.HeaderStyle.Style, - "Manage license files: " + yesNo(m.answers.LicenseFiles.Manage), - "Include: " + strings.Join(m.answers.Coverage.Include, ", "), - "Exclude: " + strings.Join(m.answers.Coverage.Exclude, ", "), - }, "\n") + rows := [][2]string{ + {"Project model", string(m.answers.Project.Model)}, + {"License", m.answers.License.SPDXID}, + {"Holder", valueOrPlaceholder(m.answers.Identity.Holder, "(required)")}, + {"Year", valueOrPlaceholder(m.answers.Identity.Year, "git")}, + {"Header style", m.answers.HeaderStyle.Style}, + {"Manage license files", yesNo(m.answers.LicenseFiles.Manage)}, + {"Include", listOrAll(m.answers.Coverage.Include)}, + {"Exclude", listOrNone(m.answers.Coverage.Exclude)}, + } + var b strings.Builder + fmt.Fprintf(&b, "%-22s %s\n", "Field", "Value") + fmt.Fprintf(&b, "%-22s %s\n", "-----", "-----") + for _, row := range rows { + fmt.Fprintf(&b, "%-22s %s\n", row[0], row[1]) + } + b.WriteString("\nPress enter to write .license-tool.yaml.") + return strings.TrimRight(b.String(), "\n") } func (m initWizardModel) previewSummary() string { - return "Preview engine: pending integration with the sample renderer. Current review values are shown above." + cfg := m.previewConfig() + sample := initwizard.SelectSample(m.previewPaths) + sourcePreview, sourceErr := initwizard.BuildSourcePreview(initwizard.SourcePreviewInput{ + Config: cfg, + Sample: sample, + ResolvedYear: previewResolvedYear(cfg.Year), + }) + yamlPreview, yamlErr := initwizard.BuildYAMLPreview(cfg) + + var b strings.Builder + if sourceErr == nil { + fmt.Fprintf(&b, "%s %s\n\n", sourcePreview.Language, sourcePreview.Path) + b.WriteString(sourcePreview.Content) + } else { + fmt.Fprintf(&b, "Source preview unavailable: %s\n", sourceErr) + } + if yamlErr == nil { + fmt.Fprintf(&b, "\n\n.license-tool.yaml\n\n%s", strings.TrimRight(string(yamlPreview), "\n")) + } else { + fmt.Fprintf(&b, "\n\nYAML preview unavailable: %s", yamlErr) + } + fmt.Fprintf(&b, "\n\nLicense files: %s", yesNo(cfg.ManageLicenseFile)) + fmt.Fprintf(&b, "\nCoverage include: %s", listOrAll(cfg.Includes)) + fmt.Fprintf(&b, "\nCoverage exclude: %s", listOrNone(cfg.Excludes)) + return strings.TrimRight(b.String(), "\n") } func yesNo(v bool) string { @@ -250,22 +533,154 @@ func yesNo(v bool) string { return "no" } +func (m *initWizardModel) handleLicenseKey(msg tea.KeyMsg) bool { + switch msg.Type { + case tea.KeyRunes: + m.licenseFilter += string(msg.Runes) + m.alignLicenseSelection() + return true + case tea.KeyBackspace: + if m.licenseFilter == "" { + return false + } + runes := []rune(m.licenseFilter) + m.licenseFilter = string(runes[:len(runes)-1]) + m.alignLicenseSelection() + return true + } + switch msg.String() { + case "ctrl+u": + m.licenseFilter = "" + m.alignLicenseSelection() + return true + case "up", "k": + m.moveSelection(-1) + return true + case "down", "j": + m.moveSelection(1) + return true + case "pgup": + m.moveSelection(-10) + return true + case "pgdown": + m.moveSelection(10) + return true + case "home": + m.moveSelectionToStart() + return true + case "end": + m.moveSelectionToEnd() + return true + } + return false +} + func (m *initWizardModel) moveSelection(delta int) { switch m.step { case initwizard.StepProjectModel: m.projectIndex = wrapIndex(m.projectIndex+delta, len(projectModelOptions)) m.answers.Project.Model = projectModelOptions[m.projectIndex] case initwizard.StepLicense: - m.licenseIndex = wrapIndex(m.licenseIndex+delta, len(m.licenseOptions)) - if len(m.licenseOptions) > 0 { - m.answers.License.SPDXID = m.licenseOptions[m.licenseIndex] + choices := m.filteredLicenseChoices() + if len(choices) == 0 { + return } + pos := clampInt(m.licenseChoicePosition(choices)+delta, 0, len(choices)-1) + m.licenseIndex = choices[pos].index + m.answers.License.SPDXID = choices[pos].id case initwizard.StepHeaderStyle: m.styleIndex = wrapIndex(m.styleIndex+delta, len(headerStyleOptions)) m.answers.HeaderStyle.Style = headerStyleOptions[m.styleIndex] } } +func (m *initWizardModel) moveSelectionToStart() { + switch m.step { + case initwizard.StepProjectModel: + m.projectIndex = 0 + m.answers.Project.Model = projectModelOptions[m.projectIndex] + case initwizard.StepLicense: + choices := m.filteredLicenseChoices() + if len(choices) == 0 { + return + } + m.licenseIndex = choices[0].index + m.answers.License.SPDXID = choices[0].id + case initwizard.StepHeaderStyle: + m.styleIndex = 0 + m.answers.HeaderStyle.Style = headerStyleOptions[m.styleIndex] + } +} + +func (m *initWizardModel) moveSelectionToEnd() { + switch m.step { + case initwizard.StepProjectModel: + m.projectIndex = len(projectModelOptions) - 1 + m.answers.Project.Model = projectModelOptions[m.projectIndex] + case initwizard.StepLicense: + choices := m.filteredLicenseChoices() + if len(choices) == 0 { + return + } + last := choices[len(choices)-1] + m.licenseIndex = last.index + m.answers.License.SPDXID = last.id + case initwizard.StepHeaderStyle: + m.styleIndex = len(headerStyleOptions) - 1 + m.answers.HeaderStyle.Style = headerStyleOptions[m.styleIndex] + } +} + +type licenseChoice struct { + index int + id string +} + +func (m initWizardModel) filteredLicenseChoices() []licenseChoice { + filter := strings.ToLower(strings.TrimSpace(m.licenseFilter)) + choices := make([]licenseChoice, 0, len(m.licenseOptions)) + for i, id := range m.licenseOptions { + if filter != "" && !strings.Contains(strings.ToLower(id), filter) { + continue + } + choices = append(choices, licenseChoice{index: i, id: id}) + } + return choices +} + +func (m initWizardModel) licenseChoicePosition(choices []licenseChoice) int { + for i, choice := range choices { + if choice.index == m.licenseIndex { + return i + } + } + return 0 +} + +func (m *initWizardModel) alignLicenseSelection() { + choices := m.filteredLicenseChoices() + if len(choices) == 0 { + return + } + for _, choice := range choices { + if choice.index == m.licenseIndex { + m.answers.License.SPDXID = choice.id + return + } + } + m.licenseIndex = choices[0].index + m.answers.License.SPDXID = choices[0].id +} + +func isCommonLicense(id string) bool { + for _, common := range spdx.CommonIDs() { + if common == id { + return true + } + } + return false +} + func wrapIndex(value, size int) int { if size == 0 { return 0 @@ -296,14 +711,15 @@ func (m initWizardModel) usesTextInput() bool { func (m *initWizardModel) setInput() { ti := textinput.New() + ti.Width = m.inputWidth() switch m.step { case initwizard.StepIdentity: ti.Placeholder = "holder | year, for example Acme, LLC | git" ti.SetValue(strings.TrimSpace(m.answers.Identity.Holder + " | " + m.answers.Identity.Year)) ti.Focus() case initwizard.StepCoverage: - ti.Placeholder = "exclude globs, comma-separated" - ti.SetValue(strings.Join(m.answers.Coverage.Exclude, ", ")) + ti.Placeholder = "include globs | exclude globs" + ti.SetValue(coverageInputValue(m.answers.Coverage)) ti.Focus() } m.input = ti @@ -320,10 +736,26 @@ func (m *initWizardModel) commitInput() { } m.answers.Identity.Holder = strings.TrimSpace(m.input.Value()) case initwizard.StepCoverage: - m.answers.Coverage.Exclude = splitCSV(m.input.Value()) + include, exclude, hasSeparator := strings.Cut(m.input.Value(), "|") + if hasSeparator { + m.answers.Coverage.Include = splitCSV(include) + m.answers.Coverage.Exclude = splitCSV(exclude) + return + } + m.answers.Coverage.Include = splitCSV(m.input.Value()) + m.answers.Coverage.Exclude = nil } } +func coverageInputValue(a initwizard.CoverageAnswer) string { + include := strings.Join(a.Include, ", ") + exclude := strings.Join(a.Exclude, ", ") + if include == "" && exclude == "" { + return "" + } + return include + " | " + exclude +} + func splitCSV(raw string) []string { var out []string for _, item := range strings.Split(raw, ",") { @@ -335,6 +767,199 @@ func splitCSV(raw string) []string { return out } +func (m initWizardModel) previewConfig() model.Config { + cfg := config.Defaults() + licenseID := strings.TrimSpace(m.answers.License.SPDXID) + if _, ok := spdx.Lookup(licenseID); !ok && len(m.licenseOptions) > 0 { + licenseID = m.licenseOptions[m.licenseIndex] + } + cfg.License = licenseID + + holder := strings.TrimSpace(m.answers.Identity.Holder) + if holder == "" { + holder = "Example, Inc." + } + cfg.Holder = holder + + if year := strings.TrimSpace(m.answers.Identity.Year); year != "" { + if ys, err := config.ParseYearSpec(year); err == nil { + cfg.Year = ys + } + } + if style := strings.TrimSpace(m.answers.HeaderStyle.Style); style != "" { + if st, err := config.ParseStyle(style); err == nil { + cfg.Style = st + } + } + cfg.ManageLicenseFile = m.answers.LicenseFiles.Manage + cfg.Includes = append([]string(nil), m.answers.Coverage.Include...) + cfg.Excludes = append([]string(nil), m.answers.Coverage.Exclude...) + return cfg +} + +func previewResolvedYear(y model.YearSpec) string { + current := time.Now().Year() + switch y.Kind { + case model.YearCurrent: + return fmt.Sprintf("%d", current) + case model.YearExplicit: + if y.Start > 0 { + return fmt.Sprintf("%d", y.Start) + } + case model.YearRange: + if y.Start > 0 && y.End > 0 { + return fmt.Sprintf("%d-%d", y.Start, y.End) + } + } + return fmt.Sprintf("2021-%d", current) +} + +func previewCandidatePaths(root string) []string { + if root == "" { + return nil + } + var paths []string + _ = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return nil + } + if d.IsDir() { + if path != root && ignoredPreviewDir(d.Name()) { + return filepath.SkipDir + } + return nil + } + rel, relErr := filepath.Rel(root, path) + if relErr != nil { + rel = path + } + rel = filepath.ToSlash(rel) + if _, ok := initwizard.SampleForPath(rel); ok { + paths = append(paths, rel) + } + return nil + }) + sort.Strings(paths) + return paths +} + +func ignoredPreviewDir(name string) bool { + switch name { + case ".git", ".hg", ".svn", ".cache", ".next", "build", "dist", "node_modules", "target", "vendor": + return true + default: + return false + } +} + +func listOrAll(values []string) string { + if len(values) == 0 { + return "all supported files" + } + return strings.Join(values, ", ") +} + +func listOrNone(values []string) string { + if len(values) == 0 { + return "none" + } + return strings.Join(values, ", ") +} + +func valueOrPlaceholder(value string, placeholder string) string { + if strings.TrimSpace(value) == "" { + return placeholder + } + return value +} + +func (m initWizardModel) inputWidth() int { + width := m.width + if width <= 0 { + width = 120 + } + if width < 100 { + return maxInt(20, width-8) + } + previewWidth := width / 2 + if previewWidth < 46 { + previewWidth = 46 + } + if previewWidth > 72 { + previewWidth = 72 + } + controlWidth := width - 24 - previewWidth - 2 + return maxInt(20, controlWidth-8) +} + +func fitText(text string, width int, height int) string { + if width <= 0 || height <= 0 { + return "" + } + raw := strings.Split(text, "\n") + lines := make([]string, 0, minInt(len(raw), height)) + for _, line := range raw { + lines = append(lines, ellipsize(line, width)) + if len(lines) == height { + break + } + } + if len(raw) > height && height > 0 { + lines[height-1] = ellipsize("...", width) + } + return strings.Join(lines, "\n") +} + +func ellipsize(line string, width int) string { + runes := []rune(line) + if len(runes) <= width { + return line + } + if width <= 3 { + return string(runes[:width]) + } + return string(runes[:width-3]) + "..." +} + +func windowStart(selected int, total int, rows int) int { + if total <= rows || rows <= 0 { + return 0 + } + selected = clampInt(selected, 0, total-1) + start := selected - rows/2 + if start < 0 { + return 0 + } + if start+rows > total { + return total - rows + } + return start +} + +func clampInt(value int, minValue int, maxValue int) int { + if value < minValue { + return minValue + } + if value > maxValue { + return maxValue + } + return value +} + +func maxInt(a int, b int) int { + if a > b { + return a + } + return b +} + +func minInt(a int, b int) int { + if a < b { + return a + } + return b +} + func runInitWizard(path string, a initwizard.Answers) (initwizard.Answers, error) { program := tea.NewProgram( newInitWizardModel(path, a), diff --git a/docs/PLAN-GH-29-init-tui-wizard.md b/docs/PLAN-GH-29-init-tui-wizard.md index 0b56958..5f8190c 100644 --- a/docs/PLAN-GH-29-init-tui-wizard.md +++ b/docs/PLAN-GH-29-init-tui-wizard.md @@ -60,13 +60,13 @@ exclude: Private/internal is supported as a guided path, but the tool must not invent proprietary license terms. The MVP can allow a private/internal project to choose metadata-only behavior or a renderable SPDX license used internally. Deeper `LicenseRef-*` support requires explicit user-provided license text and can be deferred if it would spread across render, policy, and license-file management. ## Steps -1. [ ] Add persisted config `include` support with TDD. -2. [ ] Add init answers and preview model capable of rendering config and sample headers. -3. [ ] Add language sample catalog and deterministic detection/fallback. -4. [ ] Implement Bubble Tea wizard model with review flow. -5. [ ] Wire interactive `init` to the new TUI while preserving non-TTY behavior. -6. [ ] Update docs and issue status. -7. [ ] Run full local quality and 100% coverage gates. +1. [x] Add persisted config `include` support with TDD. +2. [x] Add init answers and preview model capable of rendering config and sample headers. +3. [x] Add language sample catalog and deterministic detection/fallback. +4. [x] Implement Bubble Tea wizard model with review flow. +5. [x] Wire interactive `init` to the new TUI while preserving non-TTY behavior. +6. [x] Update docs and issue status. +7. [x] Run full local quality and 100% coverage gates. ## Open Questions - How complete should the private/internal license path be in this first slice if no proprietary license renderer exists yet? diff --git a/docs/SESSION-STATE.md b/docs/SESSION-STATE.md index 6389fe0..6d0cd5d 100644 --- a/docs/SESSION-STATE.md +++ b/docs/SESSION-STATE.md @@ -10,7 +10,9 @@ Implement GitHub issue #29: redesign `license-tool init` as a full-screen config - `v0.3.0` is released. - Feature branch created from `main` at `7e177a9`. - Plan created in `docs/PLAN-GH-29-init-tui-wizard.md`. -- Feature-definition agent Huygens is running. +- Feature-definition and worker slices are integrated into the feature branch. +- The init TUI now uses Bubble Tea with a progress rail, active controls, and live source/YAML preview. +- Include patterns persist through config, CLI flags, collector answers, and written init output. ## Next Step -Split implementation into worker-owned slices and integrate each behind tests. +Manual TUI review with `/private/tmp/license-tool-gh29` or `go run ./cmd/license-tool init ` before promoting the feature branch. diff --git a/docs/TODO.md b/docs/TODO.md index e3ff639..25e5fde 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -1,21 +1,21 @@ # TODO: GH-29 Init TUI Wizard ## Definition -- [ ] Define full feature specification and MVP boundaries. -- [ ] Update issue #29 with implementation plan once finalized. +- [x] Define full feature specification and MVP boundaries. +- [x] Update issue #29 with implementation plan once finalized. ## Implementation -- [ ] Persist `include` patterns in `.license-tool.yaml`. -- [ ] Add init wizard sample-language catalog and C fallback. -- [ ] Add live preview rendering for example source files. -- [ ] Replace interactive `init` form with full-screen TUI. -- [ ] Preserve deterministic non-TTY `init` behavior. -- [ ] Update README/DEVELOPERS documentation. +- [x] Persist `include` patterns in `.license-tool.yaml`. +- [x] Add init wizard sample-language catalog and C fallback. +- [x] Add live preview rendering for example source files. +- [x] Replace interactive `init` form with full-screen TUI. +- [x] Preserve deterministic non-TTY `init` behavior. +- [x] Update README/DEVELOPERS documentation. ## Verification -- [ ] `gofmt -l .` -- [ ] `go vet ./...` -- [ ] `golangci-lint run` -- [ ] `go test ./... -race -coverpkg=./internal/...,./cmd/... -covermode=atomic -coverprofile=cover.out` -- [ ] `go run github.com/vladopajic/go-test-coverage/v2@v2.18.8 --config=.testcoverage.yml` -- [ ] `go build ./...` +- [x] `gofmt -l .` +- [x] `go vet ./...` +- [x] `golangci-lint run` +- [x] `go test ./... -race -coverpkg=./internal/...,./cmd/... -covermode=atomic -coverprofile=cover.out` +- [x] `go run github.com/vladopajic/go-test-coverage/v2@v2.18.8 --config=.testcoverage.yml` +- [x] `go build ./...` diff --git a/go.mod b/go.mod index f28595e..5a7c49c 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,9 @@ module github.com/KofTwentyTwo/license-tool go 1.25.0 require ( - github.com/charmbracelet/huh v1.0.0 + github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7 + github.com/charmbracelet/bubbletea v1.3.6 + github.com/charmbracelet/lipgloss v1.1.0 github.com/github/go-spdx/v2 v2.7.0 github.com/google/licensecheck v0.3.1 github.com/hexops/gotextdiff v1.0.3 @@ -17,24 +19,17 @@ require ( require ( github.com/atotto/clipboard v0.1.4 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect - github.com/catppuccin/go v0.3.0 // indirect - github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7 // indirect - github.com/charmbracelet/bubbletea v1.3.6 // indirect github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect - github.com/charmbracelet/lipgloss v1.1.0 // indirect github.com/charmbracelet/x/ansi v0.9.3 // indirect github.com/charmbracelet/x/cellbuf v0.0.13 // indirect - github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect github.com/charmbracelet/x/term v0.2.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/dustin/go-humanize v1.0.1 // indirect github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/lucasb-eyer/go-colorful v1.2.0 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-localereader v0.0.1 // indirect github.com/mattn/go-runewidth v0.0.16 // indirect - github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect github.com/muesli/cancelreader v0.2.2 // indirect github.com/muesli/termenv v0.16.0 // indirect @@ -42,6 +37,7 @@ require ( github.com/rivo/uniseg v0.4.7 // indirect github.com/spf13/pflag v1.0.9 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect + golang.org/x/exp v0.0.0-20231006140011-7918f672742d // indirect golang.org/x/sync v0.15.0 // indirect golang.org/x/sys v0.44.0 // indirect golang.org/x/text v0.23.0 // indirect diff --git a/go.sum b/go.sum index b40072a..84dbcf5 100644 --- a/go.sum +++ b/go.sum @@ -1,49 +1,25 @@ -github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= -github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= -github.com/aymanbagabas/go-udiff v0.3.1 h1:LV+qyBQ2pqe0u42ZsUEtPiCaUoqgA9gYRDs3vj1nolY= -github.com/aymanbagabas/go-udiff v0.3.1/go.mod h1:G0fsKmG+P6ylD0r6N/KgQD/nWzgfnl8ZBcNLgcbrw8E= -github.com/catppuccin/go v0.3.0 h1:d+0/YicIq+hSTo5oPuRi5kOpqkVA5tAsU6dNhvRu+aY= -github.com/catppuccin/go v0.3.0/go.mod h1:8IHJuMGaUUjQM82qBrGNBv7LFq6JI3NnQCF6MOlZjpc= github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7 h1:JFgG/xnwFfbezlUnFMJy0nusZvytYysV4SCS2cYbvws= github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7/go.mod h1:ISC1gtLcVilLOf23wvTfoQuYbW2q0JevFxPfUzZ9Ybw= github.com/charmbracelet/bubbletea v1.3.6 h1:VkHIxPJQeDt0aFJIsVxw8BQdh/F/L2KKZGsK6et5taU= github.com/charmbracelet/bubbletea v1.3.6/go.mod h1:oQD9VCRQFF8KplacJLo28/jofOI2ToOfGYeFgBBxHOc= github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= -github.com/charmbracelet/huh v1.0.0 h1:wOnedH8G4qzJbmhftTqrpppyqHakl/zbbNdXIWJyIxw= -github.com/charmbracelet/huh v1.0.0/go.mod h1:5YVc+SlZ1IhQALxRPpkGwwEKftN/+OlJlnJYlDRFqN4= github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY= github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30= github.com/charmbracelet/x/ansi v0.9.3 h1:BXt5DHS/MKF+LjuK4huWrC6NCvHtexww7dMayh6GXd0= github.com/charmbracelet/x/ansi v0.9.3/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE= github.com/charmbracelet/x/cellbuf v0.0.13 h1:/KBBKHuVRbq1lYx5BzEHBAFBP8VcQzJejZ/IA3iR28k= github.com/charmbracelet/x/cellbuf v0.0.13/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs= -github.com/charmbracelet/x/conpty v0.1.0 h1:4zc8KaIcbiL4mghEON8D72agYtSeIgq8FSThSPQIb+U= -github.com/charmbracelet/x/conpty v0.1.0/go.mod h1:rMFsDJoDwVmiYM10aD4bH2XiRgwI7NYJtQgl5yskjEQ= -github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86 h1:JSt3B+U9iqk37QUU2Rvb6DSBYRLtWqFqfxf8l5hOZUA= -github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86/go.mod h1:2P0UgXMEa6TsToMSuFqKFQR+fZTO9CNGUNokkPatT/0= -github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ= -github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U= -github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 h1:qko3AQ4gK1MTS/de7F5hPGx6/k1u0w4TeYmBFwzYVP4= -github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0/go.mod h1:pBhA0ybfXv6hDjQUZ7hk1lVxBiUbupdw5R31yPUViVQ= github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ= github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= -github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY= -github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo= -github.com/charmbracelet/x/xpty v0.1.2 h1:Pqmu4TEJ8KeA9uSkISKMU3f+C1F6OGBn8ABuGlqCbtI= -github.com/charmbracelet/x/xpty v0.1.2/go.mod h1:XK2Z0id5rtLWcpeNiMYBccNNBrP2IJnzHI0Lq13Xzq4= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= -github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= -github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= -github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= github.com/github/go-spdx/v2 v2.7.0 h1:GzfXx4wFdlilARxmFRXW/mgUy3A4vSqZocCMFV6XFdQ= @@ -62,8 +38,6 @@ github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2J github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= -github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4= -github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE= github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= diff --git a/internal/initwizard/catalog.go b/internal/initwizard/catalog.go index 6a885af..ec439ca 100644 --- a/internal/initwizard/catalog.go +++ b/internal/initwizard/catalog.go @@ -15,6 +15,7 @@ import ( // LanguageFamily is the stable label for a source preview sample. type LanguageFamily string +// Language family labels supported by the source preview catalog. const ( LanguageTypeScriptJavaScript LanguageFamily = "TypeScript/JavaScript" LanguagePython LanguageFamily = "Python" diff --git a/internal/initwizard/catalog_test.go b/internal/initwizard/catalog_test.go index a325cd2..ebb2297 100644 --- a/internal/initwizard/catalog_test.go +++ b/internal/initwizard/catalog_test.go @@ -137,6 +137,99 @@ func TestBuildSourcePreviewUsesCSharpFileType(t *testing.T) { assert.Contains(t, preview.Content, "public class Example") } +func TestBuildSourcePreviewEdgeCases(t *testing.T) { + t.Run("path with no extension has no sample", func(t *testing.T) { + sample, ok := SampleForPath("LICENSE") + assert.False(t, ok) + assert.Equal(t, Sample{}, sample) + }) + + t.Run("unknown family has no sample", func(t *testing.T) { + sample, ok := sampleForFamily(LanguageFamily("Unknown")) + assert.False(t, ok) + assert.Equal(t, Sample{}, sample) + }) + + t.Run("empty sample falls back to C", func(t *testing.T) { + preview, err := BuildSourcePreview(SourcePreviewInput{ + Config: model.Config{ + License: "MIT", + Holder: "Acme, Inc.", + Style: model.StyleReuse, + }, + ResolvedYear: "2026", + }) + require.NoError(t, err) + assert.Equal(t, LanguageC, preview.Language) + assert.Equal(t, "example.c", preview.Path) + }) + + t.Run("resolved year is required", func(t *testing.T) { + _, err := BuildSourcePreview(SourcePreviewInput{ + Config: model.Config{ + License: "MIT", + Holder: "Acme, Inc.", + Style: model.StyleReuse, + }, + Sample: SelectSample([]string{"main.go"}), + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "resolved year is required") + }) + + t.Run("unknown license is rejected", func(t *testing.T) { + _, err := BuildSourcePreview(SourcePreviewInput{ + Config: model.Config{ + License: "Nope", + Holder: "Acme, Inc.", + Style: model.StyleReuse, + }, + Sample: SelectSample([]string{"main.go"}), + ResolvedYear: "2026", + }) + require.Error(t, err) + assert.Contains(t, err.Error(), `unknown license "Nope"`) + }) + + t.Run("sample path must have a file type", func(t *testing.T) { + _, err := BuildSourcePreview(SourcePreviewInput{ + Config: model.Config{ + License: "MIT", + Holder: "Acme, Inc.", + Style: model.StyleReuse, + }, + Sample: Sample{ + Language: LanguageFamily("Unknown"), + Path: "example.unknown", + Source: "content\n", + }, + ResolvedYear: "2026", + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "no file type") + }) + + t.Run("uncommentable override rejects preview rendering", func(t *testing.T) { + _, err := BuildSourcePreview(SourcePreviewInput{ + Config: model.Config{ + License: "MIT", + Holder: "Acme, Inc.", + Style: model.StyleReuse, + FileTypeOverrides: map[string]model.FileType{ + ".c": { + Name: "custom-c", + Skip: true, + }, + }, + }, + Sample: SelectSample([]string{"main.c"}), + ResolvedYear: "2026", + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "uncommentable") + }) +} + func TestBuildYAMLPreviewDelegatesToConfigRenderFile(t *testing.T) { cfg := model.Config{ License: "MIT", diff --git a/internal/initwizard/model.go b/internal/initwizard/model.go index f11cf44..cfdfd4b 100644 --- a/internal/initwizard/model.go +++ b/internal/initwizard/model.go @@ -107,21 +107,3 @@ type ReviewAnswer struct { // Confirmed is true when the operator accepted the review screen. Confirmed bool } - -// Preview is the narrow shell expected from the future preview engine. -type Preview struct { - // Source is the rendered example source preview. - Source string - // Config is the rendered config preview. - Config string - // LicenseFiles is the license file behavior summary. - LicenseFiles string - // Coverage is the file coverage summary. - Coverage string -} - -// PreviewProvider is intentionally narrow until the preview engine lands. -type PreviewProvider interface { - // Preview returns display text for the current answers. - Preview(Answers) (Preview, error) -} -- 2.54.0 From 4e3561ef29edbdd59b581e3a406f59e1becbfc87 Mon Sep 17 00:00:00 2001 From: James Maes Date: Mon, 8 Jun 2026 11:44:56 -0500 Subject: [PATCH 07/14] fix(#32): include globs honor ** via shared gitignore matcher --- internal/enumerate/enumerate.go | 40 ++++++------------------- internal/enumerate/enumerate_test.go | 45 +++++++++++++--------------- internal/enumerate/glob.go | 40 +++++++++++++++++++++++++ internal/enumerate/glob_test.go | 45 ++++++++++++++++++++++++++++ 4 files changed, 115 insertions(+), 55 deletions(-) create mode 100644 internal/enumerate/glob.go create mode 100644 internal/enumerate/glob_test.go diff --git a/internal/enumerate/enumerate.go b/internal/enumerate/enumerate.go index 16ff643..38a15de 100644 --- a/internal/enumerate/enumerate.go +++ b/internal/enumerate/enumerate.go @@ -109,24 +109,22 @@ func enumerate(root string, opts Options, classify ContentClassifier, contentAwa return nil, err } - // Config/flag excludes apply uniformly on both paths. On the git path they layer - // on top of git's own .gitignore handling; on the walk path they layer on top of - // the .gitignore matcher already applied during the walk. - var excluder *ignore.GitIgnore - if len(opts.Excludes) > 0 { - excluder = ignore.CompileIgnoreLines(opts.Excludes...) - } + // Includes and excludes share one gitignore-style matcher so their glob semantics + // (** and slash-less "any depth") cannot diverge. Excludes apply uniformly on both + // discovery paths, layering on top of git's / the walk's own .gitignore handling. + includer := CompileMatcher(opts.Includes) + excluder := CompileMatcher(opts.Excludes) entries := make([]Entry, 0, len(relPaths)) for _, rel := range relPaths { - // Normalize to forward slashes so glob/gitignore matching is OS-independent; - // MatchesPath itself also normalizes, but Includes use filepath.Match. + // Normalize to forward slashes so matching is OS-independent. rel = filepath.ToSlash(rel) - if !matchesIncludes(rel, opts.Includes) { + // An empty include set matches everything (the common case). + if !includer.Empty() && !includer.Match(rel) { continue } - if excluder != nil && excluder.MatchesPath(rel) { + if excluder.Match(rel) { continue } @@ -261,26 +259,6 @@ func readHead(abs string) ([]byte, error) { return buf[:n], nil } -// matchesIncludes reports whether rel satisfies the include globs. An empty include -// set matches everything (the common case); otherwise a path must match at least one -// glob, tested against both the full relative path and its base name so a bare -// "*.go" works regardless of directory depth. -func matchesIncludes(rel string, includes []string) bool { - if len(includes) == 0 { - return true - } - base := filepath.Base(rel) - for _, pat := range includes { - if ok, _ := filepath.Match(pat, rel); ok { - return true - } - if ok, _ := filepath.Match(pat, base); ok { - return true - } - } - return false -} - // isGitRepo reports whether path is inside a git working tree. WHY shell out rather // than look for a .git directory: git rev-parse correctly resolves worktrees, nested // repos, and the GIT_DIR/GIT_WORK_TREE environment, which a bare directory probe diff --git a/internal/enumerate/enumerate_test.go b/internal/enumerate/enumerate_test.go index a260300..c66a390 100644 --- a/internal/enumerate/enumerate_test.go +++ b/internal/enumerate/enumerate_test.go @@ -46,30 +46,6 @@ func TestIsBinary(t *testing.T) { } } -// TestMatchesIncludes verifies include-glob semantics: empty includes match all, and -// a non-empty set matches against both the full relative path and the base name. -func TestMatchesIncludes(t *testing.T) { - cases := []struct { - name string - rel string - includes []string - want bool - }{ - {"empty includes match all", "src/Main.java", nil, true}, - {"base-name glob matches at depth", "a/b/c/x.go", []string{"*.go"}, true}, - {"full-path glob matches", "src/x.go", []string{"src/*.go"}, true}, - {"full-path glob does not span dirs", "src/sub/x.go", []string{"src/*.go"}, false}, - {"no glob matches", "x.ts", []string{"*.go", "*.py"}, false}, - {"one of several matches", "x.py", []string{"*.go", "*.py"}, true}, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - assert.Equal(t, tc.want, matchesIncludes(tc.rel, tc.includes)) - }) - } -} - // indexEntries maps an enumeration result to relative-path -> Entry for assertions. func indexEntries(entries []Entry) map[string]Entry { m := make(map[string]Entry, len(entries)) @@ -238,6 +214,27 @@ func TestEnumerateGitRepoIncludes(t *testing.T) { assert.NotContains(t, byPath, "b.py") } +// TestEnumerateGitRepoIncludesDoublestar verifies that ** include globs span +// directories (issue #32): a src/** include must reach nested files, not just the +// top level. The previous filepath.Match include path failed this silently. +func TestEnumerateGitRepoIncludesDoublestar(t *testing.T) { + root := t.TempDir() + gitInit(t, root) + + writeFile(t, root, "src/a.go", "package x\n") + writeFile(t, root, "src/deep/nested/b.go", "package y\n") + writeFile(t, root, "other/c.go", "package z\n") + gitAddCommit(t, root) + + entries, err := Enumerate(root, Options{Includes: []string{"src/**"}}, filetype.Lookup) + require.NoError(t, err) + byPath := indexEntries(entries) + + assert.Contains(t, byPath, "src/a.go") + assert.Contains(t, byPath, "src/deep/nested/b.go") + assert.NotContains(t, byPath, "other/c.go") +} + // TestEnumerateNonGitWalk covers the fallback walk: no git repo, .gitignore honored, // the .git-style pruning is irrelevant, directories descended, classification applied. func TestEnumerateNonGitWalk(t *testing.T) { diff --git a/internal/enumerate/glob.go b/internal/enumerate/glob.go new file mode 100644 index 0000000..cfafb89 --- /dev/null +++ b/internal/enumerate/glob.go @@ -0,0 +1,40 @@ +package enumerate + +import ( + ignore "github.com/sabhiram/go-gitignore" +) + +// Matcher matches repo-relative, forward-slash paths against a set of +// gitignore-style glob patterns. WHY gitignore semantics rather than filepath.Match: +// gitignore supports ** (cross-directory) and treats a slash-less pattern as +// matching at any depth, which is what include/exclude globs are documented to do. +// filepath.Match has neither behavior, so "src/**" and "**/generated/**" silently +// matched nothing on the include path (issue #32). Includes and excludes now share +// this one matcher so their semantics cannot drift. +type Matcher struct { + ig *ignore.GitIgnore +} + +// CompileMatcher builds a Matcher from glob patterns. An empty set yields an Empty +// matcher; callers decide whether empty means "match all" (includes) or "match +// nothing" (excludes). +func CompileMatcher(patterns []string) Matcher { + if len(patterns) == 0 { + return Matcher{} + } + return Matcher{ig: ignore.CompileIgnoreLines(patterns...)} +} + +// Empty reports whether the matcher was built from no patterns. +func (m Matcher) Empty() bool { + return m.ig == nil +} + +// Match reports whether rel (forward-slash, relative to the scan root) matches any +// pattern. An Empty matcher matches nothing. +func (m Matcher) Match(rel string) bool { + if m.ig == nil { + return false + } + return m.ig.MatchesPath(rel) +} diff --git a/internal/enumerate/glob_test.go b/internal/enumerate/glob_test.go new file mode 100644 index 0000000..b520851 --- /dev/null +++ b/internal/enumerate/glob_test.go @@ -0,0 +1,45 @@ +package enumerate + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +// TestCompileMatcher verifies the shared gitignore-style glob matcher used by both +// includes and excludes. The load-bearing cases are the ** ones: the previous +// filepath.Match include path silently failed them (issue #32). +func TestCompileMatcher(t *testing.T) { + cases := []struct { + name string + patterns []string + rel string + want bool + }{ + {"basename glob matches at depth", []string{"*.go"}, "a/b/c/x.go", true}, + {"single-segment glob does not span dirs", []string{"src/*.go"}, "src/sub/x.go", false}, + {"single-segment glob matches direct child", []string{"src/*.go"}, "src/x.go", true}, + {"doublestar matches direct child", []string{"src/**"}, "src/x.go", true}, + {"doublestar matches nested", []string{"src/**"}, "src/sub/deep/x.go", true}, + {"leading doublestar matches any depth", []string{"**/generated/**"}, "a/b/generated/c.go", true}, + {"leading doublestar non-match", []string{"**/generated/**"}, "a/b/src/c.go", false}, + {"no pattern matches", []string{"*.go", "*.py"}, "x.ts", false}, + {"one of several matches", []string{"*.go", "*.py"}, "x.py", true}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + m := CompileMatcher(tc.patterns) + assert.False(t, m.Empty()) + assert.Equal(t, tc.want, m.Match(tc.rel)) + }) + } +} + +// TestCompileMatcherEmpty verifies an empty pattern set is Empty and matches nothing +// (callers translate "empty includes" into "match all" themselves). +func TestCompileMatcherEmpty(t *testing.T) { + m := CompileMatcher(nil) + assert.True(t, m.Empty()) + assert.False(t, m.Match("anything.go")) +} -- 2.54.0 From bafa2810a6b4b664ae03ff13ab1fdf64030c0ee3 Mon Sep 17 00:00:00 2001 From: James Maes Date: Mon, 8 Jun 2026 11:50:28 -0500 Subject: [PATCH 08/14] refactor(#29): unify Answers->Config behind one translator --- CLAUDE.md | 67 ++++++ cmd/license-tool/commands.go | 47 +--- cmd/license-tool/commands_test.go | 82 ------- cmd/license-tool/wizard.go | 33 +-- docs/DESIGN-init-tui-redesign.md | 127 +++++++++++ docs/PLAN-GH-29-init-tui-redesign.md | 80 +++++++ docs/review/01-write-path-safety.md | 287 +++++++++++++++++++++++++ docs/review/02-audit-policy-resolve.md | 264 +++++++++++++++++++++++ docs/review/03-cmd-tui-tests.md | 235 ++++++++++++++++++++ internal/initwizard/translate.go | 76 +++++++ internal/initwizard/translate_test.go | 126 +++++++++++ 11 files changed, 1264 insertions(+), 160 deletions(-) create mode 100644 CLAUDE.md create mode 100644 docs/DESIGN-init-tui-redesign.md create mode 100644 docs/PLAN-GH-29-init-tui-redesign.md create mode 100644 docs/review/01-write-path-safety.md create mode 100644 docs/review/02-audit-policy-resolve.md create mode 100644 docs/review/03-cmd-tui-tests.md create mode 100644 internal/initwizard/translate.go create mode 100644 internal/initwizard/translate_test.go diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..9d5076c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,67 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## What this is + +`license-tool` is a license-agnostic Go CLI that audits and standardizes license metadata across codebases. Target license, holder, year policy, and header style are all *inputs*, never assumptions (AGPL-3.0-or-later + Kingsrook is only the default profile). It has two halves: an **audit/check** half (read-only reporting + CI gate) and an **apply/license** half (writes canonical headers and top-level LICENSE files). License text is never invented — it comes from a vendored SPDX snapshot. + +## Commands + +The local quality gate mirrors CI; run all of it before considering work done: + +```bash +gofmt -l . # must print nothing (tabs, not spaces); CI fails on any output +go vet ./... +golangci-lint run +go test ./... -race -cover +go build ./... +``` + +```bash +go test ./internal/render -run TestSplice -race # single package / single test +go run ./scripts/gen_spdx.go # regenerate the vendored SPDX snapshot +./scripts/verify-release.sh # the full 6-gate release preflight +``` + +**100% coverage is a hard gate.** CI runs `go-test-coverage` over `./internal/...` and `./cmd/...` and fails below 100% total. Only three files are excluded (see `.testcoverage.yml`): `cmd/license-tool/main.go`, `cmd/license-tool/wizard.go`, and `scripts/gen_spdx.go` — each because it is an untestable shell (process entry point, Bubble Tea TUI, or build-tagged generator). **All behavior must live in covered packages**, not in these three files. This is why `wizard.go` delegates to `answersToConfig` + `internal/initwizard` + `internal/config`, and why business logic never accretes in `main.go`. + +## Architecture + +### `internal/model` is the frozen contract + +`internal/model/model.go` defines every shared type and interface (`Config`, `License`, `FileType`, `DetectedHeader`, `FileResult`, `Report`, `Resolver`, `YearResolver`, etc.). It is **stdlib-only and dependency-free** so every other package can import it without cycles. Changing a field or signature here ripples into all consumers — treat it as load-bearing and change it deliberately, not casually. + +### The pipeline (what flows through model) + +``` +config.Resolve → enumerate → detect → render → applier (apply/license: the write half) + ↓ ↓ + detect → report (+ resolve for deps) (audit/check: the read half) +``` + +- **`internal/config`** — resolves effective config by layering, high→low: flags > repo `.license-tool.yaml` > user/global (`$XDG_CONFIG_HOME/license-tool/config.yaml`) > built-in defaults. `include` takes the highest non-empty layer; `exclude` accumulates across layers. +- **`internal/enumerate`** — produces the ordered file set. In a git repo, `git ls-files` (authoritative `.gitignore` honoring); otherwise a tree walk via go-gitignore. Skips symlinks/binaries, classifies each file via the file-type table. +- **`internal/filetype`** — the data-driven comment-syntax table mapping path → `FileType` (comment delimiters + ordered preserve-first rules). Data-driven so render/apply stays generic and users extend coverage via config, not code. +- **`internal/detect`** — *safety-critical.* Identifies an existing managed header by, in confidence order: own sentinel → `SPDX-License-Identifier` → known SPDX standard header → curated phrase fingerprint. A false positive means apply deletes a real doc comment, so detection demands a positive license signal inside the leading comment block and never scans below the header. +- **`internal/render`** — produces canonical header text *and* performs the byte-level splice (insert/replace). Rendering and mutation live together so producer and splicer can't drift on header shape, line endings, or the blank-line separator. Carries explicit SAFETY INVARIANTS in its package doc. +- **`internal/applier`** — Mode B orchestration: render per file, compute unified diff, atomically (temp-then-rename) write or replace. Also manages top-level `LICENSE` + `LICENSES/.txt` (REUSE). +- **`internal/resolve`** — per-ecosystem dependency license resolution (maven/npm/gradle). Tiered: on-disk metadata by default, opt-in tool shell-out behind a flag. **Never guesses** — an unresolvable dep is reported `unresolved` with a reason. +- **`internal/report`** — folds per-file + dependency + policy results into one `Report`, renders text/JSON/Markdown deterministically (byte-identical for identical input regardless of order), and owns `Report.Passed` (the `check` exit decision) plus the "not legal advice" disclaimer. +- **`internal/policy`** — classifies licenses and enforces allow/deny/required + curated incompatibilities, emitting violation tokens that drive `check`'s `fail_on` exit. Routes classification through `internal/spdx` so there's no second drifting opinion. +- **`internal/spdx`** — exposes the vendored snapshot with zero runtime network. Two surfaces: `Validate(id)` accepts *any* real SPDX id (permissive — any valid id is a legal target); `Lookup(id)` returns full text/header/category only for the curated set the tool ships rendering for. +- **`internal/gitutil`** — shells out to `git` (clean-tree check, first-commit year, atomic commit) because `git ls-files` is the authoritative `.gitignore` honorer. + +### Command layer (`cmd/license-tool`) + +`commands.go` builds the cobra tree (`audit`, `check`, `apply`, `license`, `init`, `version`) and wires the concrete `internal` packages into a `report.Pipeline` indirection (`buildAuditPipeline`) so the report layer stays decoupled from enumeration/detection. `main.go` is a thin shim mapping errors to exit codes via `commandError`/`withExitCode`. + +## Safety invariants (these are the product, not nice-to-haves) + +- **`apply` and `license` are dry-run by default.** Writing without an explicit `--write` is a bug. They require a clean git tree (`--allow-dirty` to override), refuse non-git dirs without `--force`, write atomically, and are idempotent — a second apply is a no-op and headers never stack. Git is the undo. +- **Never invent license text.** New/updated text comes from re-running `gen_spdx.go` against a pinned upstream ref, never hand-edited. (The one documented override is the wrapped AGPL standard header — see `internal/spdx`.) +- **Exit codes are an API:** `0` ok · `1` policy/check failure · `2` usage · `3` write refused · `4` internal. + +## Workflow + +Feature branches → PR into `develop` → promote green commits to `main`; tags `vX.Y.Z` from `main` drive GoReleaser (GitHub Release + Homebrew cask). When changing header generation, detection, comment-syntax, or policy, add/adjust tests and update golden files (explain the golden diff in the PR). Release flow: `RELEASING.md`. diff --git a/cmd/license-tool/commands.go b/cmd/license-tool/commands.go index 898626c..7ad02e3 100644 --- a/cmd/license-tool/commands.go +++ b/cmd/license-tool/commands.go @@ -394,51 +394,6 @@ func bindApplyFlags(cmd *cobra.Command, f *applyFlags) { // Bubble Tea collector, which no-ops when interactive is false. var interactiveCollect = collectInteractive -// answersToConfig validates and converts collected init answers into a model.Config, -// starting from the built-in Defaults so unset answers carry the documented default -// behavior. WHY validation lives here, not in the wizard: the wizard is the -// interactive shell (excluded from coverage); answersToConfig is the single tested -// gate that both the TTY and flag-only paths funnel through, so an invalid or -// unrenderable license and an empty holder are rejected identically regardless of -// how the answers arrived. -func answersToConfig(a initwizard.Answers) (model.Config, error) { - licenseID := strings.TrimSpace(a.License.SPDXID) - holder := strings.TrimSpace(a.Identity.Holder) - year := strings.TrimSpace(a.Identity.Year) - style := strings.TrimSpace(a.HeaderStyle.Style) - - if !spdx.Validate(licenseID) { - return model.Config{}, fmt.Errorf("init: %q is not a recognized SPDX license identifier", licenseID) - } - if _, ok := spdx.Lookup(licenseID); !ok { - return model.Config{}, fmt.Errorf("init: %q is a recognized SPDX license identifier, but license-tool cannot render it", licenseID) - } - if holder == "" { - return model.Config{}, fmt.Errorf("init: copyright holder is required") - } - cfg := config.Defaults() - cfg.License = licenseID - cfg.Holder = holder - if year != "" { - ys, err := config.ParseYearSpec(year) - if err != nil { - return model.Config{}, err - } - cfg.Year = ys - } - if style != "" { - st, err := config.ParseStyle(style) - if err != nil { - return model.Config{}, err - } - cfg.Style = st - } - cfg.ManageLicenseFile = a.LicenseFiles.Manage - cfg.Includes = append([]string(nil), a.Coverage.Include...) - cfg.Excludes = append([]string(nil), a.Coverage.Exclude...) - return cfg, nil -} - func newInitCmd(shared *sharedFlags) *cobra.Command { f := &applyFlags{} cmd := &cobra.Command{ @@ -463,7 +418,7 @@ func newInitCmd(shared *sharedFlags) *cobra.Command { if err != nil { return usageError(err) } - cfg, err := answersToConfig(a) + cfg, err := initwizard.Translate(a, initwizard.TranslateOptions{}) if err != nil { return usageError(err) } diff --git a/cmd/license-tool/commands_test.go b/cmd/license-tool/commands_test.go index 811e67b..a1e628a 100644 --- a/cmd/license-tool/commands_test.go +++ b/cmd/license-tool/commands_test.go @@ -971,88 +971,6 @@ func TestInitCommand(t *testing.T) { }) } -// TestAnswersToConfig drives the single tested gate that both the TTY wizard and -// the flag-only path funnel through: the valid case plus each rejection (unknown -// license, empty holder, bad year, bad style). WHY exhaustive here: the wizard shell -// is excluded from coverage, so this is the only place the validation/parse arms are -// exercised, and they must reject identically regardless of how answers arrived. -func TestAnswersToConfig(t *testing.T) { - t.Run("valid answers build a config from defaults", func(t *testing.T) { - cfg, err := answersToConfig(initwizard.Answers{ - License: initwizard.LicenseAnswer{SPDXID: "MIT"}, - Identity: initwizard.IdentityAnswer{ - Holder: "Acme, LLC", - Year: "2021-2026", - }, - HeaderStyle: initwizard.HeaderStyleAnswer{Style: "reuse"}, - LicenseFiles: initwizard.LicenseFilesAnswer{ - Manage: false, - }, - Coverage: initwizard.CoverageAnswer{ - Include: []string{"src/**"}, - Exclude: []string{"**/vendor/**"}, - }, - }) - require.NoError(t, err) - assert.Equal(t, "MIT", cfg.License) - assert.Equal(t, "Acme, LLC", cfg.Holder) - assert.Equal(t, model.YearRange, cfg.Year.Kind) - assert.Equal(t, 2021, cfg.Year.Start) - assert.Equal(t, 2026, cfg.Year.End) - assert.Equal(t, model.StyleReuse, cfg.Style) - assert.False(t, cfg.ManageLicenseFile) - assert.Equal(t, []string{"src/**"}, cfg.Includes) - assert.Equal(t, []string{"**/vendor/**"}, cfg.Excludes) - }) - - t.Run("empty year and style keep the built-in defaults", func(t *testing.T) { - // Unset year/style answers must leave the Defaults() values untouched, so the - // year/style parse branches are skipped (not defaulted to a parse of ""). - cfg, err := answersToConfig(initwizard.Answers{ - License: initwizard.LicenseAnswer{SPDXID: "MIT"}, - Identity: initwizard.IdentityAnswer{Holder: "Acme"}, - LicenseFiles: initwizard.LicenseFilesAnswer{Manage: true}, - }) - require.NoError(t, err) - assert.Equal(t, model.YearGit, cfg.Year.Kind) - assert.Equal(t, model.StyleReusePlusNotice, cfg.Style) - }) - - t.Run("unknown license rejected", func(t *testing.T) { - _, err := answersToConfig(initwizard.Answers{ - License: initwizard.LicenseAnswer{SPDXID: "NOT-A-LICENSE"}, - Identity: initwizard.IdentityAnswer{Holder: "Acme"}, - }) - require.Error(t, err) - assert.Contains(t, err.Error(), "not a recognized SPDX license identifier") - }) - - t.Run("empty holder rejected", func(t *testing.T) { - _, err := answersToConfig(initwizard.Answers{License: initwizard.LicenseAnswer{SPDXID: "MIT"}}) - require.Error(t, err) - assert.Contains(t, err.Error(), "copyright holder is required") - }) - - t.Run("bad year rejected", func(t *testing.T) { - _, err := answersToConfig(initwizard.Answers{ - License: initwizard.LicenseAnswer{SPDXID: "MIT"}, - Identity: initwizard.IdentityAnswer{Holder: "Acme", Year: "not-a-year"}, - }) - require.Error(t, err) - assert.Contains(t, err.Error(), "year") - }) - - t.Run("bad style rejected", func(t *testing.T) { - _, err := answersToConfig(initwizard.Answers{ - License: initwizard.LicenseAnswer{SPDXID: "MIT"}, - Identity: initwizard.IdentityAnswer{Holder: "Acme"}, - HeaderStyle: initwizard.HeaderStyleAnswer{Style: "fancy"}, - }) - require.Error(t, err) - assert.Contains(t, err.Error(), "unknown style") - }) -} - func TestParseFailOnFlags(t *testing.T) { got, err := parseFailOnFlags([]string{"missing-header, unknown-license", "policy-violation", "unresolved-dependency"}) require.NoError(t, err) diff --git a/cmd/license-tool/wizard.go b/cmd/license-tool/wizard.go index 064f930..7af6c96 100644 --- a/cmd/license-tool/wizard.go +++ b/cmd/license-tool/wizard.go @@ -13,7 +13,6 @@ import ( tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" - "github.com/KofTwentyTwo/license-tool/internal/config" "github.com/KofTwentyTwo/license-tool/internal/initwizard" "github.com/KofTwentyTwo/license-tool/internal/model" "github.com/KofTwentyTwo/license-tool/internal/spdx" @@ -499,7 +498,7 @@ func (m initWizardModel) reviewBody() string { } func (m initWizardModel) previewSummary() string { - cfg := m.previewConfig() + cfg, _ := initwizard.Translate(m.answers, initwizard.TranslateOptions{AllowPlaceholders: true}) sample := initwizard.SelectSample(m.previewPaths) sourcePreview, sourceErr := initwizard.BuildSourcePreview(initwizard.SourcePreviewInput{ Config: cfg, @@ -767,36 +766,6 @@ func splitCSV(raw string) []string { return out } -func (m initWizardModel) previewConfig() model.Config { - cfg := config.Defaults() - licenseID := strings.TrimSpace(m.answers.License.SPDXID) - if _, ok := spdx.Lookup(licenseID); !ok && len(m.licenseOptions) > 0 { - licenseID = m.licenseOptions[m.licenseIndex] - } - cfg.License = licenseID - - holder := strings.TrimSpace(m.answers.Identity.Holder) - if holder == "" { - holder = "Example, Inc." - } - cfg.Holder = holder - - if year := strings.TrimSpace(m.answers.Identity.Year); year != "" { - if ys, err := config.ParseYearSpec(year); err == nil { - cfg.Year = ys - } - } - if style := strings.TrimSpace(m.answers.HeaderStyle.Style); style != "" { - if st, err := config.ParseStyle(style); err == nil { - cfg.Style = st - } - } - cfg.ManageLicenseFile = m.answers.LicenseFiles.Manage - cfg.Includes = append([]string(nil), m.answers.Coverage.Include...) - cfg.Excludes = append([]string(nil), m.answers.Coverage.Exclude...) - return cfg -} - func previewResolvedYear(y model.YearSpec) string { current := time.Now().Year() switch y.Kind { diff --git a/docs/DESIGN-init-tui-redesign.md b/docs/DESIGN-init-tui-redesign.md new file mode 100644 index 0000000..fed6f53 --- /dev/null +++ b/docs/DESIGN-init-tui-redesign.md @@ -0,0 +1,127 @@ +# DESIGN: `init` TUI Clean-Room Redesign + +Status: **proposed** (decisions confirmed in a grill-me session; not yet planned/implemented) +Supersedes the TUI shape from `docs/PLAN-GH-29-init-tui-wizard.md`. +Companion review findings: `docs/review/01-write-path-safety.md`, `02-audit-policy-resolve.md`, `03-cmd-tui-tests.md`. + +## 1. Problem + +The current `init` wizard (`cmd/license-tool/wizard.go`, ~990 lines, excluded from coverage) is functionally close but, per the user, "terrible and more or less not usable." Concrete causes, confirmed by code review: + +- **3 panes fight for width** (Steps nav | controls | preview); collapses to a stacked mess below 100 cols. +- **Cram-fields:** Identity is one text input parsed as `holder | year`; Coverage is one input parsed as `include | exclude` with each side comma-split. Nobody guesses these grammars. +- **A dead step:** "Project model" is collected, previewed, and written to `Answers.Project`, but `answersToConfig` never reads it — the first screen has zero effect. +- **End-loaded validation:** an empty holder is accepted through Review and only rejected *after* the user confirms write, bouncing them out. +- **Two `Answers→Config` translators** (`previewConfig` vs `answersToConfig`) that can silently drift — so the preview can render something different from what gets written. +- **~400 lines of pure logic trapped** in the uncoverable `wizard.go` (selection math, filtering, parsing, preview assembly, layout sizing). + +The *what* (collect config, teach via preview, write `.license-tool.yaml`) is right. The *how* is being redesigned clean-room. + +## 2. North star & principles + +**North star: a teaching tool driven by a live preview.** Every choice immediately re-renders an example source header (and the YAML) so the user understands the effect before writing. (Chosen over "fast correct config," "power config," and "minimal bootstrap.") + +Principles, in priority order: +1. **See the effect, always.** The preview is persistent and never blank. +2. **Detect, don't interrogate.** Open pre-filled from the repo; the user confirms/tweaks. +3. **Can't reach a bad write.** Validate live; disable Write until valid. +4. **One source of truth.** A single `Answers→Config` translator feeds both preview and write. +5. **Honest coverage.** Logic is tested; the TUI shell is trivial enough that its exclusion is legitimate. + +## 3. Resolved decisions + +| # | Decision | Choice | Rejected alternatives | +|---|----------|--------|----------------------| +| 1 | North star | **Teaching tool via live preview** | fast-correct-config; power config; minimal bootstrap | +| 2 | Interaction model | **Single always-visible form**, all fields, edit in any order, persistent preview | linear stepper; grouped sections; preview-dominant overlay | +| 3 | Layout | **Adaptive panel count** (3 cols wide / 2 medium / stacked narrow); hard floor refuses the TUI | fixed responsive 2-pane; hard-min two-column; single-column peek | +| 4 | Defaults | **Detect & pre-fill, badged + editable** (retires the Project-model step) | light detection; static only; detection-on-keypress | +| 5 | Complex-field editing | **Inline-expanding rows** (filter-list / list editor / text expand in place) | modal overlay; full-pane focus; drill-in sub-screen | +| 6 | Validation | **Live inline; Write disabled until valid**, footer shows why, preview uses placeholder holder | validate-on-commit; validate-at-write; live + confirm-anyway | +| 7 | Code structure | **Thin shell + fat tested core**; single `Answers→Config` translator | eliminate exclusion via teatest; extract-only; spike-first | +| 8 | Write flow | **No review screen**; write disabled until valid; **confirm + old→new diff only when overwriting** | explicit final review; immediate no-confirm; always-diff | +| 9 | Private/internal path | **Cut now, track as a separate feature** | minimal "internal" marker; build LicenseRef-* now; leave dead | + +## 4. Redesigned UX + +### 4.1 The form (single screen, fields editable in any order) + +Rows, top to bottom; each shows `label: ` (with a `detected` badge where seeded), expands in place on Enter: + +1. **License** — inline filter-as-you-type list over the *renderable* SPDX set (common ids first, then the rest). (Validation can accept any SPDX id, but `init` writes only renderable ids — so the picker is constrained to renderable, eliminating the "valid but unrenderable" error class.) +2. **Holder** — text input. Required. +3. **Year** — pick: `current` · `git` · `explicit` (then `YYYY` or `YYYY-YYYY`). Default `git`. +4. **Header style** — pick: `reuse` · `notice` · `reuse+notice`, each with a one-line plain-language implication. Default `reuse+notice`. +5. **Manage license files** — toggle (`LICENSE` + `LICENSES/.txt`). Default true if no `LICENSE` exists yet; if one exists, default to standardize-with-confirm. +6. **Include globs** — inline list editor (add / select / remove). Empty ⇒ "all supported files." +7. **Exclude globs** — inline list editor; accumulates on top of `.gitignore`. + +Bottom: a focusable **`Write .license-tool.yaml`** affordance, hard-disabled while any field is invalid; footer shows the blocking reason. + +### 4.2 Layout breakpoints (starting values; validate during implementation) + +- **Wide (≥ ~110 cols):** 3 columns — Form (~40) · Source preview (flex) · YAML preview (~40). +- **Medium (~80–109):** 2 columns — Form (~40) · Source preview (flex). YAML shown as a switchable tab on the preview pane (or stacked beneath source preview if height allows). +- **Narrow (≥ floor, < ~80):** single column — Form full width, Source preview stacked below (shorter, still persistent). +- **Below floor (< ~60 cols or < ~20 rows):** refuse the TUI; print a message pointing to the flag-only non-TTY path (`init --license ... --holder ...`) or to widen the terminal. + +The dedicated "Steps" nav rail is **removed** (no steps to track in a single form), reclaiming ~24 cols. A compact validity/affordance line lives in the footer. + +### 4.3 Preview content + +- **Source preview** is the hero — the example file (language auto-selected from the repo; C fallback) with the generated header applied, re-rendered on every edit via the *same* `render` path apply uses. +- **YAML preview** shows the exact `.license-tool.yaml` to be written. +- **License-files** behavior and **coverage** summary become compact status lines (within/under the YAML panel), not full panels. +- On overwrite, the YAML panel switches to an **old→new diff**. + +### 4.4 Keymap (replaces today's overloaded `backspace`) + +- `Tab`/`Shift+Tab` or `↑`/`↓`: move field focus. +- `Enter`: expand focused row / commit an open editor. +- `Esc`: collapse an open editor without committing; if nothing is open, quit without writing. +- Filter-list editor: type to filter, `↑`/`↓` select, `Enter` commit, `Esc` cancel. +- Glob-list editor: type + `Enter` to add, `↑`/`↓` to select an entry, `d`/`Delete` to remove, `Esc` to finish. +- `Ctrl+S` (or focus the Write row + `Enter`): write — disabled while invalid; confirm if overwriting. +- `?`: toggle help. `Ctrl+C`: quit without writing. + +### 4.5 Detection seeding (decision 4) + +On launch, seed `Answers` (reusing tested code), badging each value and falling back to static defaults when detection is empty: +- **License / Holder:** run `internal/detect` over enumerated source files for existing managed/recognized headers → dominant SPDX id and holder. Cross-check a top-level `LICENSE` / `LICENSES/` for an id. +- **Holder fallback:** `git config user.name` (or repo org) when headers yield nothing. +- **Manage flag:** seeded from whether a top-level `LICENSE` already exists. +- **Preview sample:** `enumerate` language classification → `initwizard.SelectSample` (already implemented). +- Nothing is written unreviewed; seeds are editable form values, consistent with the tool's "never guess silently" ethos. + +## 5. Architecture (decision 7) + +**All logic in `internal/initwizard` (tested); `wizard.go` is a trivial Bubble Tea adapter.** + +`internal/initwizard` gains: +- `Translate(Answers) (model.Config, error)` — the **single** translator. `cmd`'s `answersToConfig` and the preview's `previewConfig` both collapse into this. Kills the drift class (review 03). +- `Seed(root, env) Answers` — detection seeding (reuses `detect`/`enumerate`/`gitutil`). +- A pure form state machine: field focus, per-field expansion state, per-field validation results, derived "can write" flag — as plain types + transition functions. +- `Layout(width, height) PanelPlan` — pure breakpoint selection. +- View helpers returning strings (unit-testable; drive selected transitions with synthetic `tea.Msg` where cheap). + +`cmd/license-tool/wizard.go`: an `Init/Update/View` adapter that routes `tea.KeyMsg` to `initwizard` transitions and renders via `initwizard` view helpers. Small enough that its coverage exclusion is honest. (Eliminating the exclusion via `teatest` was considered and deferred.) + +## 6. Entangled review fixes + +**Hard dependency (must fix to ship this design):** +- **[HIGH] `include` `**` globs match nothing** (`enumerate.go`, review 02 #1). Includes use `filepath.Match` (no `**`); excludes use go-gitignore (has `**`). Decision 5 validates globs against "the real matcher" and the Coverage rows teach glob authoring — so includes must move to the **same gitignore-style matcher** as excludes, and the test that enshrines the broken single-segment behavior must be removed. Without this, the wizard would actively teach broken globs. + +**Independent but recommended to track alongside (not blockers):** +- **[HIGH]** `detect` absorbs an adjacent doc comment across a blank line and deletes it on replace (review 01 #1). +- **[HIGH]** `spdxnorm` alias table *guesses* licenses (`"bsd"`->BSD-2-Clause, LGPL->`-or-later`), violating "never guess" (review 02 #2). +- **[MED]** `detect` matches `SPDX-License-Identifier` mentioned anywhere in a leading comment (01); symlinked `LICENSE` clobber (01); `--quiet`/`--verbose` are no-op flags (03). + +## 7. Out of scope + +- **Proprietary / `LicenseRef-*` licenses** (decision 9): cut the dead `LicenseAnswer.Private` / private-model scaffolding; file proprietary support as its own issue spanning `render`/`policy`/license-file management. The "standard SPDX used internally" case is already served by picking that license. + +## 8. Lower-confidence details to confirm during planning + +- Exact breakpoint widths/heights and the medium-layout YAML treatment (tab vs stacked). +- Whether `Manage license files` defaulting to "standardize an existing LICENSE" needs its own confirm. +- Help affordance depth (`?` overlay vs persistent footer hints). diff --git a/docs/PLAN-GH-29-init-tui-redesign.md b/docs/PLAN-GH-29-init-tui-redesign.md new file mode 100644 index 0000000..48c012d --- /dev/null +++ b/docs/PLAN-GH-29-init-tui-redesign.md @@ -0,0 +1,80 @@ +# PLAN: GH-29 Init TUI Redesign + +> Execution-oriented plan. Design rationale lives in `docs/DESIGN-init-tui-redesign.md`; review findings in `docs/review/`. Supersedes the TUI shape in `PLAN-GH-29-init-tui-wizard.md`. Implemented on the existing `feature/GH-29-init-tui-wizard` branch (issue #29 is unmerged). + +**Goal:** Replace the 7-step 3-pane wizard with a single always-visible, repo-seeded form + persistent adaptive live preview, with all logic in a tested `internal/initwizard` package and `wizard.go` reduced to a thin Bubble Tea adapter. + +**Architecture:** Pure logic (translate, seed, form state machine, validation, layout, view rendering) lives in `internal/initwizard` and is unit-tested to 100%. `cmd/license-tool/wizard.go` becomes an `Init/Update/View` adapter that delegates to those pure functions. A single `Translate` feeds both the live preview and the write path, eliminating the `previewConfig`/`answersToConfig` drift. + +**Tech Stack:** Go 1.25, Bubble Tea / Bubbles / Lip Gloss (already present), go-gitignore (already present), testify. No new dependencies. + +--- + +## File map + +| File | Responsibility | Status | +|------|----------------|--------| +| `internal/enumerate/glob.go` (+ existing enumerate.go) | gitignore-style matcher reused by includes, excludes, and wizard glob validation | new + modify (#32) | +| `internal/initwizard/model.go` | `Answers` (trimmed: drop Project/Review/Private dead types), `Field` enum | modify | +| `internal/initwizard/translate.go` | single `Translate(Answers, TranslateOptions) (model.Config, error)` | new | +| `internal/initwizard/seed.go` | `Seed(root, SeedDeps) (Answers, Detected)` repo detection | new | +| `internal/initwizard/validate.go` | per-field validation (`Validate`, `FieldError`) | new | +| `internal/initwizard/form.go` | `FormState` + transitions (focus, expand, commit, glob/license editors, `CanWrite`) | new | +| `internal/initwizard/layout.go` | `Layout(w,h) PanelPlan` adaptive breakpoints + too-small sentinel | new | +| `internal/initwizard/view.go` | pure string rendering from `FormState`+`PanelPlan` | new | +| `internal/initwizard/catalog.go` | sample catalog + preview builders | keep | +| `cmd/license-tool/wizard.go` | thin `tea.Model` adapter delegating to initwizard | rewrite (shrink) | +| `cmd/license-tool/commands.go` | `newInitCmd` seeds + runs form; `answersToConfig` -> `initwizard.Translate` | modify | + +--- + +## Task sequence (each task: red -> green -> refactor -> commit; commit references `#29`/`#32`) + +### Task 1 - Fix include `**` (issue #32, unblocks wizard glob teaching) +- Test: `internal/enumerate/glob_test.go` - `include: ["src/**"]` matches `src/sub/x.go`; `["**/generated/**"]` matches `a/generated/b.go`; single-segment still works. +- Impl: route includes through the same go-gitignore matcher as excludes (extract `internal/enumerate/glob.go` with `CompileMatcher(patterns) Matcher` + `Matcher.Match(rel) bool`). Replace `filepath.Match` include path. +- Remove `TestMatchesIncludes`'s assertion that enshrines single-segment-only behavior; replace with `**` cases. +- Gate: `go test ./internal/enumerate -race`. Commit: `fix(#32): include globs honor ** via gitignore matcher`. + +### Task 2 - Single translator +- Test: `internal/initwizard/translate_test.go` - strict mode rejects empty holder / unrenderable license; placeholder mode substitutes `Example, Inc.` and never errors on holder; both map year/style/manage/include/exclude identically. +- Impl: `Translate(a Answers, opts TranslateOptions) (model.Config, error)` starting from `config.Defaults()`. `TranslateOptions{AllowPlaceholders bool}`. +- Rewire: `commands.go answersToConfig` -> `Translate(a, TranslateOptions{})`; `catalog.go`/preview path + `wizard.go previewConfig` -> `Translate(a, TranslateOptions{AllowPlaceholders:true})`. Delete `previewConfig`. +- Gate: `go test ./internal/initwizard ./cmd/... -race`. Commit: `refactor(#29): single Answers->Config translator`. + +### Task 3 - Trim dead types + seed detection +- Test: `internal/initwizard/seed_test.go` - holder/license seeded from existing managed headers; holder falls back to git author then empty; manage flag false when LICENSE present; `Detected` flags set accordingly; empty repo -> static defaults. +- Impl: remove `ProjectModel*`, `Step*`, `ReviewAnswer`, `ProjectAnswer`, `LicenseAnswer.Private`. Add `Seed(root string, deps SeedDeps) (Answers, Detected)` reusing `detect`, `enumerate`, `spdx`, and a `GitAuthor` seam (default `gitutil`). `Detected struct{ License, Holder, Manage bool }`. +- Gate: `go test ./... -race` (catches removed-type fallout). Commit: `feat(#29): seed init answers from repo detection`. + +### Task 4 - Form state machine + validation +- Test: `internal/initwizard/form_test.go`, `validate_test.go` - focus wraps across fields incl. Write row; Enter expands focused field and Esc collapses; license filter narrows choices and commit updates Answers; glob editor adds/removes entries; `Validate` flags empty holder, unparseable year, malformed glob; `CanWrite` false until valid. +- Impl: `Field` enum; `FormState{ Answers; Detected; Focus Field; Expanded bool; License editor state; Glob editor state }`; transitions `MoveFocus`, `Toggle/Expand/Collapse`, `Commit`, `SetFilter`, `AddGlob/RemoveGlob`, `Validate() []FieldError`, `CanWrite() bool`. License options from `licenseSelectOptions` (moved in from wizard.go). +- Gate: `go test ./internal/initwizard -race`. Commit: `feat(#29): pure form state machine and live validation`. + +### Task 5 - Adaptive layout +- Test: `internal/initwizard/layout_test.go` - >=110 cols -> 3 panels; 80-109 -> 2; floor..79 -> stacked; <60 or <20 rows -> `TooSmall`; widths sum within bounds. +- Impl: `PanelPlan{ Panels []Panel; TooSmall bool; ... }`; `Layout(w,h int) PanelPlan`. +- Gate: `go test ./internal/initwizard -race`. Commit: `feat(#29): adaptive panel layout planner`. + +### Task 6 - Pure view rendering +- Test: `internal/initwizard/view_test.go` - renders form rows with values + detected badges; focused/expanded row shows editor; footer shows blocking validation reason when `!CanWrite`; too-small plan renders the fallback message; preview panels present per plan. +- Impl: `Render(s FormState, plan PanelPlan) string` (+ row/preview/footer helpers) using lipgloss. Move `fitText`/`ellipsize`/`selectionList` in from wizard.go. +- Gate: `go test ./internal/initwizard -race`. Commit: `feat(#29): pure view rendering for init form`. + +### Task 7 - Thin Bubble Tea adapter + wire-up + full gate +- Impl: rewrite `wizard.go` to hold `initwizard.FormState`+size; `Update` maps `tea.KeyMsg`/`WindowSizeMsg` to transitions, triggers write on the Write action via `config.WriteFile` (confirm + diff when overwriting), quits on Esc/ctrl+c; `View` calls `initwizard.Render`. Update `newInitCmd` to `Seed` then run. Update `commands_test.go` for the new collector contract. +- Update `.testcoverage.yml` comment if the wizard.go exclusion rationale changes (it stays excluded; now genuinely thin). +- Update `README.md`/`DEVELOPERS.md` init sections. +- Gate (full, per CONTRIBUTING): `gofmt -l .`, `go vet ./...`, `golangci-lint run`, `go test ./... -race -coverpkg=./internal/...,./cmd/... -covermode=atomic -coverprofile=cover.out`, `go run github.com/vladopajic/go-test-coverage/v2@v2.18.8 --config=.testcoverage.yml`, `go build ./...`. +- Commit: `feat(#29): single-form init wizard with adaptive live preview`. + +--- + +## Out of scope (tracked separately) +- Proprietary / `LicenseRef-*` licenses (design decision 9). +- Issues #30, #31, #33, #34 (independent review bugs; not required for #29). #32 is in-scope as Task 1. + +## Risks +- 100% coverage gate: every new exported/branch path needs a test before the gate passes. Form state transitions are the largest surface; budget most test effort there. +- View rendering tests can be brittle; assert on stable substrings/structure, not full styled output. diff --git a/docs/review/01-write-path-safety.md b/docs/review/01-write-path-safety.md new file mode 100644 index 0000000..73fab00 --- /dev/null +++ b/docs/review/01-write-path-safety.md @@ -0,0 +1,287 @@ +# Write-Path Safety Review — license-tool + +Scope: the safety-critical header rewrite path. +`internal/detect`, `internal/render`, `internal/header`, `internal/filetype`, +`internal/applier`, `internal/gitutil` (plus their tests). + +Reviewer focus: any path where `apply` could mutate or delete non-header +content; LF/CRLF and BOM handling; off-by-one in byte spans; detection +false positives/negatives; non-idempotent (stacking) paths; temp-then-rename +crash safety; symlink/encoding edge cases. Verdict on each stated SAFETY +INVARIANT in `render.go`. + +## Overall assessment + +The architecture is sound and unusually careful for this class of tool: a +single byte-splice entry point (`render.Splice`), span-exact replacement, +EOL/ BOM/trailing-newline preservation, atomic temp-then-rename, a dirty-tree +gate, and symlinks excluded upstream in `enumerate`. The stated render +invariants mostly hold. The real exposure is concentrated in **detection**, +where two behaviors can cause `apply` to absorb and delete a non-license +leading comment that merely sits next to (or mentions) a license signal. Those +are the findings to fix before trusting `--write` on arbitrary repos. + +No crash-corruption or partial-write bug was found; the atomic write is +correct. No panic path was found (out-of-range spans are refused). + +## Severity-sorted summary + +| # | Severity | Area | Finding | +|---|----------|------|---------| +| 1 | High | detect | A leading non-license comment sitting one blank line below a managed header is absorbed into the header span and DELETED on replace (line-comment types). | +| 2 | Medium | detect | `SPDX-License-Identifier:` matched anywhere in a leading comment marks it managed — a doc comment that *mentions* the tag is a false positive and gets replaced. | +| 3 | Medium | applier | `AtomicWrite` on a symlinked managed file (`LICENSE`) follows it for mode but `os.Rename` replaces the symlink with a regular file. Source files are safe (excluded in enumerate); `LICENSE`/`LICENSES/*` are not. | +| 4 | Low | render | `normalizeEOL`'s "input is LF-only" invariant is asserted, not enforced; a CR inside a vendored `StandardHeader` would yield `\r\r\n` on CRLF files. | +| 5 | Low | detect | `extractYear` fallback scans the whole comment, so a year inside license-body prose can be reported as the copyright year for fingerprint-only matches. | +| 6 | Low | detect | Block-comment detection spans only the first `/* */`; a header authored as two adjacent blocks is partially replaced (cosmetic stacking, not data loss). | +| 7 | Info | gitutil | `ls-files` output is newline-split; paths with embedded newlines (core.quotepath off + literal newline) are mishandled. Extremely rare; documented for completeness. | + +--- + +## Finding 1 — Adjacent leading comment absorbed and deleted on replace (High) + +`internal/detect/detect.go:290` (`lineCommentRegion`) and `:238` +(`leadingCommentRegion` → `consumeTrailingBlankLines`). + +`lineCommentRegion` tolerates blank lines *between* comment lines and folds +them into one region: + +```go +case strings.TrimSpace(body) == "": + // Blank line: tolerate it only between comment lines... + pendingBlank++ +... +case strings.HasPrefix(trimmed, prefix): + for i := 0; i < pendingBlank; i++ { lines = append(lines, "") } + pendingBlank = 0 + ... + end = lineEnd +``` + +This is intentional for a header split by a blank line (test at +`detect_test.go:554`, "blank line then comment is still one region"). But it +does not distinguish a *continuation of the header* from an *unrelated leading +doc comment*. Consider a Rust/Go-`//` or Python-`#` file: + +``` +// SPDX-License-Identifier: MIT +// +// Some hand-written file-level doc comment that is NOT part of the license. + +func ... +``` + +or worse, two visually separate blocks: + +``` +// SPDX-License-Identifier: MIT + +// Package foo does X. Authored by the team; please keep this. +package foo +``` + +Both comment blocks plus the blank line between them become a single detected +span (`StartByte..EndByte`). `render.replaceSpan` then swaps that **entire** +span for the new header, so on a relicense/refresh the second, non-license +comment is silently deleted. This is exactly the "false positive deletes a real +doc comment" hazard the package doc warns against — here triggered not by a +prose license-name but by adjacency to a genuine header. + +Failure scenario: any repo whose convention is "license header, blank line, +file doc comment" loses the doc comment on the first `apply --write` that +performs a replace (e.g. a year refresh or relicense). + +Fix options: +- Bound the header region to the *contiguous* comment run (stop at the first + blank line), and only fold an interior blank line when the following comment + also carries a license signal; or +- When replacing, recompute the minimal span that actually contains the + license signal (sentinel/tag/fingerprint lines) rather than the whole + tolerated run, so trailing non-license comment lines are preserved. + +The block-comment path is not affected by the blank-line tolerance (it spans a +single `/* */`), so this is specific to line-comment types — which is most of +the table (Rust, Python, Shell, Ruby, SQL, YAML, etc.). + +## Finding 2 — `SPDX-License-Identifier:` matched anywhere marks a comment managed (Medium) + +`internal/detect/detect.go:130` and `:339` (`spdxIdentifierTag`). + +```go +const tag = "spdx-license-identifier:" +lower := strings.ToLower(commentText) +idx := strings.Index(lower, tag) +``` + +Any leading comment whose text *contains* the tag substring — anywhere, not +only as a line-leading REUSE tag — sets `Present = true`. A file that documents +SPDX usage, a code comment explaining the convention, a template/example, or a +generated doc comment that quotes `SPDX-License-Identifier: ` is treated as +a managed header and its whole comment block is replaced on `apply`. This is +realistic inside a licensing tool's own repository, in docs-as-code, and in +test fixtures. + +The package doc claims "mere mention of a license name in prose never +qualifies" — true for the fingerprint path, but the SPDX-tag path has no such +guard. Combined with Finding 1, a stray tag mention can also drag an adjacent +comment into the deleted span. + +Fix: require the tag to be the start of a (decoration-stripped) comment line, +i.e. match `^\s*(\*\s*)?SPDX-License-Identifier:` per line rather than +`strings.Index` over the whole region. The detector already splits to lines for +`extractHolder`; do the same here. + +Severity is Medium rather than High because a true REUSE tag in prose is +uncommon and the sentinel/standard-header paths are not affected. + +## Finding 3 — AtomicWrite replaces a symlinked managed file (Medium) + +`internal/applier/applier.go:283` (`AtomicWrite`). + +```go +if fi, err := os.Stat(path); err == nil { // follows symlink -> target's mode + mode = fi.Mode().Perm() +} +tmp, _ := os.CreateTemp(dir, ".license-tool-*") +... +return os.Rename(tmpName, path) // replaces the link, not the target +``` + +`os.Stat` follows a symlink, so the mode is read from the *target*; `os.Rename` +then drops the new file at the *link path*, replacing the symlink with a regular +file. For source files this never happens because `enumerate` skips symlinks +(`enumerate.go:158`, `:207`, with tests), so the source-rewrite path is safe. +But `writeManaged` (`applier.go:241`) calls `AtomicWrite` on +`/LICENSE` and `/LICENSES/.txt` with no symlink check. A repo +that symlinks `LICENSE` to a shared file would have the link clobbered (and the +shared target left stale), or worse, if the temp lands in a different dir than +the link target, the link is silently converted. + +Severity Medium: it does not corrupt content (the intended bytes are written), +but it can break an intentional symlink layout and is a surprise mutation of a +non-regular file. + +Fix: in `AtomicWrite` (or `writeManaged`), `os.Lstat` the path and refuse / +warn when it is a symlink, mirroring the source-file policy; or resolve and +write through to the link target deliberately if that is the desired semantics. +Document whichever is chosen. + +## Finding 4 — `normalizeEOL` LF-only precondition is unenforced (Low) + +`internal/render/render.go:320` (`normalizeEOL`) and `:72` (`Header`). + +```go +// normalizeEOL ... s must not already contain CR characters; Header guarantees LF-only output. +func normalizeEOL(s, eol string) string { + if eol == "\n" { return s } + return strings.ReplaceAll(s, "\n", eol) +} +``` + +`Header` builds the body from `in.License.StandardHeader` via +`strings.TrimRight(notice, "\n")` and `strings.Split(notice, "\n")` — it never +strips `\r`. If any vendored `StandardHeader` (or a future user-supplied +notice) contained CRLF, the CRs survive into the LF "canonical" header, and on +a CRLF file `normalizeEOL` turns each `\n` into `\r\n`, producing `\r\r\n`. +That is a malformed line ending spliced into the user's file. + +Today the SPDX snapshot is almost certainly LF-only, so this is latent, hence +Low. But the safety story rests on an asserted invariant rather than an +enforced one. + +Fix: normalize the assembled body to LF in `Header`/`plaintextHeader` +(`strings.ReplaceAll(s, "\r\n", "\n")` then strip stray `\r`) before wrapping, +so the precondition `normalizeEOL` relies on is actually true regardless of +source data. + +## Finding 5 — `extractYear` can report a license-body year as the copyright year (Low) + +`internal/detect/detect.go:425` (`extractYear`). + +```go +for _, line := range strings.Split(commentText, "\n") { + if !strings.Contains(lower, "copyright") { continue } + if y := findYearSpan(line); y != "" { return y } +} +// Fall back to any copyright-bearing fragment even if the keyword case differed. +if y := findYearSpan(commentText); y != "" { return y } // scans EVERYTHING +``` + +The fallback scans the entire comment for the first 4-digit run. For a +fingerprint-only legacy header (no `Copyright` line, e.g. a bare GNU notice +that contains "version 3" / a URL / "1989, 1991"), the first 4-digit token in +the license boilerplate is returned as the holder's copyright year. This only +feeds the report's holder/year fields and the re-rendered header's year when +the policy is "explicit/derived", so it is not destructive, but it can write an +incorrect year. Low severity; worth tightening the fallback to require a +copyright-context token near the digits. + +## Finding 6 — Block detection spans only the first comment block (Low / cosmetic) + +`internal/detect/detect.go:259` (`blockCommentRegion`): "WHY only one block: a +license header is one comment block; a second block below is file content." +Reasonable, but a header authored as two adjacent `/* */` blocks (e.g. a +copyright block then a separate license block, a real legacy pattern in +C/Java) is only partially detected; replace swaps the first and leaves the +second, producing a stacked/contradictory notice. Not data loss, but it +violates the "no stacked notice" intent for that input shape. Low. + +## Finding 7 — `git ls-files` newline split (Info) + +`internal/gitutil/gitutil.go:51`: `strings.Split(out, "\n")`. With default git +quoting this is safe, but a tracked path containing a literal newline (possible +with `core.quotepath=off` and an exotic filename) would split into bogus paths. +Vanishingly rare; noted only for completeness. If hardening is desired, use +`ls-files -z` and split on NUL. + +--- + +## SAFETY INVARIANT verification (render.go:17-25) + +1. "Bytes outside the header region are never altered (BOM, shebang, XML/PHP + prolog, pragma, EOL, trailing-newline survive)." + **Upheld in render.** `insertAt`/`replaceSpan` only touch `[start,end)` or + the computed insertion offset; BOM/CRLF/no-trailing-newline are preserved + (verified by code trace and by `TestSplicePreservesBOM`, + `TestSplicePreservesCRLF`, `TestSplicePreservesNoTrailingNewline`, + `TestSpliceNeverAltersBytesOutsideHeaderRegion`). The caveat is upstream: if + `detect` reports a span that *includes* a non-license comment (Findings 1/2), + render faithfully deletes exactly that wrongly-sized span. The invariant + holds for render given a correct span; the span can be wrong. + +2. "Header placed after preserve-first / before package decl." + **Upheld.** `PreserveBoundary` (header.go) is well-tested across BOM, + shebang (universal), xml-decl, php-open, pragma, go:build, @charset, + doctype, and the Before (package) rule is never consumed. + +3. "Replacement uses the detected header's exact byte span; no stacking." + **Upheld at the byte level** (single span swap, idempotent no-op when equal, + out-of-range refused — `TestReplaceRejectsOutOfRangeSpan`, + `TestSpliceIdempotent`). CRLF replace idempotency also holds: the detector + absorbs the CRLF terminator and trailing blank line so the re-detected span + equals the freshly normalized CRLF header (traced: `blockCommentRegion` + handles `\r\n` at `:280`, `consumeTrailingBlankLines` folds the blank). The + "no stacking" guarantee can still be defeated by Finding 6's two-block input. + +## Test-quality notes + +Tests are substantive, not coverage-padding: assertions check byte prefixes, +ordering (header-before-package, after-shebang), exact spans, idempotency +(byte-equality on second apply), and real `go/build` constraint evaluation +(`goFileMatches`) to prove a build tag is not voided. Error seams (`tmpWrite`, +`tmpClose`, `chmodFn`, `detectFn`, `preserveBoundaryFn`, `run`) are used to +drive otherwise-unreachable failure branches honestly. Atomic-write mode +preservation, dirty-tree gating, and per-file error isolation are all +exercised against real git repos. + +Gaps that the 100%-line target does not catch (all behavioral, not line +coverage): +- No test inserts a license header *above an unrelated leading comment* and + then relicenses, which would surface Finding 1. The existing + "blank line then comment is still one region" test (`detect_test.go:554`) + actually documents the buggy behavior as intended. +- No test for an `SPDX-License-Identifier:` string appearing in a non-header + doc comment (Finding 2). +- No test for `AtomicWrite` onto a symlink (Finding 3). +- No CRLF in a vendored `StandardHeader` (Finding 4) — currently impossible to + trigger from data, so untested by construction. diff --git a/docs/review/02-audit-policy-resolve.md b/docs/review/02-audit-policy-resolve.md new file mode 100644 index 0000000..6e2f231 --- /dev/null +++ b/docs/review/02-audit-policy-resolve.md @@ -0,0 +1,264 @@ +# Code Review — Audit / Reporting Half (config, enumerate, spdx, policy, resolve, report) + +Reviewer: automated deep review. Scope: correctness of policy verdicts, exit codes, config +layering, enumeration filtering, SPDX normalization, and deterministic output. Lead bias: +a *false pass* (something that should fail CI but does not) is the worst outcome here. + +## Summary (severity-sorted) + +| # | Severity | Area | File:Line | One-line | +|---|----------|------|-----------|----------| +| 1 | High | enumerate | enumerate.go:268-282 | `**` include globs silently never match (uses `filepath.Match`); excludes DO support `**`, so the two filters disagree | +| 2 | High | resolve | spdxnorm.go:89-98 | Alias table **guesses** a license version/clause it cannot know (`bsd`→BSD-2-Clause, `gnu lesser general public license`→LGPL-3.0-or-later), violating the documented "never guess" invariant | +| 3 | Medium | resolve | spdxnorm.go:95-97, 102 | Aliases resolve to EPL-2.0 / AGPL etc. that pass `spdx.Validate` but are NOT in the curated set, so `policy.Classify` returns Unknown — a resolved dep can carry a license the policy layer treats as unknown without anyone noticing | +| 4 | Medium | resolve | gradle.go:51, 94-109 | Gradle dep regex requires a literal `group:artifact:version`; versionless / BOM-managed coordinates are silently dropped (not reported unresolved), so a Gradle dependency can be invisible to the audit | +| 5 | Medium | report | report.go:378-387 | `Check` only ever returns 0/1/4; the unresolved-dependency gate works only if `unresolved-dependency` is in `fail_on`, and the default `fail_on` set omits it — unresolved deps are a default *pass* | +| 6 | Low | resolve | npm.go:56-84 | Only **direct** declared deps are resolved; transitive deps installed under nested `node_modules` are never audited (documented, but a real coverage gap for a CI gate) | +| 7 | Low | config | config.go:456-461 | Flag excludes append while flag includes replace — correct per spec, but there is no test that a flag exclude *adds to* (rather than replaces) repo/user excludes through the flag layer specifically | +| 8 | Low | enumerate | enumerate.go:328-334 | Non-git walk reads only the **root** `.gitignore`; nested/global ignores are not honored (documented), so the git and non-git paths can enumerate different sets | +| 9 | Info | policy | policy.go:277-286 | Incompatibility table omits AGPL/GPL-3 vs GPL-2-only-family pairs that the prose claims to cover; heterogeneity still flags them, so no false pass, but the curated table is narrower than its doc comment | + +No critical (provably wrong hard-fail/hard-pass with default config) issue was found in the +policy verdict logic itself; the policy package is solid. The dangerous items are #2 (a guessed +license can launder a copyleft dep into a wrong-but-resolved verdict) and #1 (include scoping +silently mis-filters). + +--- + +## Details + +### 1. (High) `**` include globs silently match nothing — include/exclude filters disagree + +`internal/enumerate/enumerate.go:268-282`: + +```go +func matchesIncludes(rel string, includes []string) bool { + if len(includes) == 0 { + return true + } + base := filepath.Base(rel) + for _, pat := range includes { + if ok, _ := filepath.Match(pat, rel); ok { + return true + } + if ok, _ := filepath.Match(pat, base); ok { + return true + } + } + return false +} +``` + +Includes are matched with the standard library `filepath.Match`, which has **no `**` +support**: `**` collapses to a single `*`, and `*` never matches a path separator. So an +include pattern of `src/**` matches `src/x.go` but **not** `src/sub/x.go`, and `**/generated/**` +matches nothing at any depth. The config layer explicitly accepts and round-trips these +patterns — `internal/config/config_test.go:173-175,535-543` use `src/**`, `**/generated/**`, +`repo/**`, `flags/**` as first-class include values — so a user who writes the documented +recursive include will silently get an empty or wrong file set. + +The asymmetry is the real trap: **excludes** are compiled with `go-gitignore` +(`enumerate.go:116-117`, `ignore.CompileIgnoreLines`), which *does* implement `**`. So +`exclude: ["**/vendor/**"]` works as written while `include: ["src/**"]` does not. Two filters +on the same config, one honoring `**` and one not. + +The test `TestMatchesIncludes` (enumerate_test.go:51-71) only exercises `*.go` and `src/*.go` +and even *asserts* the non-spanning behavior (`"full-path glob does not span dirs" ... false`) — +so this is locked-in behavior, not an oversight in coverage. That makes it coverage-padding +relative to the actual user contract: 100% lines, zero `**` include cases. + +Fix: match includes with the same `go-gitignore`/doublestar engine used for excludes (or +`github.com/bmatcuk/doublestar`), so include and exclude glob semantics are identical. At +minimum, document loudly that includes are shell-glob (single-segment) not gitignore-glob, and +reject/normalize `**` in include patterns at config load so the user gets an error instead of a +silent empty set. + +--- + +### 2. (High) Alias table guesses a license it cannot actually determine — "never guess" violated + +`internal/resolve/spdxnorm.go:81-103`: + +```go +var spdxAliases = map[string]string{ + ... + "bsd": "BSD-2-Clause", + "bsd license": "BSD-2-Clause", + ... + "gnu lesser general public license": "LGPL-3.0-or-later", + ... +} +``` + +The package contract (resolve.go:1-15, spdxnorm.go:11-20) is emphatic that the tool **never +guesses** a license. These two entries do exactly that: + +- `"bsd"` / `"bsd license"` → `BSD-2-Clause`. The bare string "BSD" does not state the clause + count. It could be 2-clause, 3-clause, or 4-clause. Picking BSD-2-Clause is a guess, and it + can be the *wrong* license for policy purposes (a 4-clause/advertising-clause BSD is a + materially different obligation). +- `"gnu lesser general public license"` → `LGPL-3.0-or-later`. The name carries **no version**. + SPDX has `LGPL-2.0-*`, `LGPL-2.1-*`, `LGPL-3.0-*` (both `-only` and `-or-later`). Mapping the + versionless name to `3.0-or-later` invents both a version and the "or-later" grant. That is a + guess with legal weight: it can turn an LGPL-2.1-only dependency into a reported + LGPL-3.0-or-later, and `-or-later` vs `-only` is exactly the distinction the incompatibility + table (policy.go:277-286) cares about. + +Because `EvaluateDependency` checks the resolved id against deny/allow, a wrong guess here can +produce a *wrong policy verdict* (pass a denied license, or fail an allowed one). Contrast the +conservative entries in the same table (`apache 2.0`→Apache-2.0) which are genuinely +unambiguous and SPDX-documented equivalences — those are fine. + +Fix: delete the two ambiguous aliases. A versionless/clauseless name must stay **unresolved** +with a reason ("declared license %q is ambiguous (no version/clause); not guessed"), which is +the honest answer the package promises everywhere else. + +--- + +### 3. (Medium) Aliases can resolve to a valid-but-uncurated id that policy then can't classify + +`spdxnorm.go:95-97,102` map to `EPL-2.0`, `EPL-1.0`, `AGPL-3.0-or-later`, etc. +`internal/spdx/data/licenses/` ships only 14 curated detail files (no `EPL-*.json`), while the +full index used by `Validate` contains EPL. So for an EPL dependency: + +- `normalizeSPDX("Eclipse Public License 2.0")` → `EPL-2.0`, `spdx.Validate("EPL-2.0")` is true → + the dep is marked **Resolved** with id `EPL-2.0`. +- But `policy.Classify("EPL-2.0")` calls `spdx.Lookup`, which fails (uncurated) → + `CategoryUnknown`. + +`EvaluateDependency` (policy.go:109-152) only consults deny/allow for resolved deps, and +unknown-category does not feed any dependency-level signal, so an EPL dep with no allow-list +slips through as a clean resolved pass even though the tool cannot actually categorize it. +This is internally consistent (deps aren't classified), but it means "resolved" can quietly mean +"valid SPDX string we can't reason about". Worth either (a) curating EPL so the alias targets are +all classifiable, or (b) noting in the report when a resolved id is outside the curated set. + +--- + +### 4. (Medium) Gradle coordinates without a literal version are silently dropped + +`internal/resolve/gradle.go:51`: + +```go +var gradleDepRE = regexp.MustCompile(`["']([\w.\-]+:[\w.\-]+:[\w.\-${}]+)["']`) +``` + +The regex requires three colon-separated segments, i.e. `group:artifact:version`. Real Gradle +builds frequently declare dependencies **without** an inline version when the version comes from +a platform/BOM or version catalog: `implementation 'com.google.guava:guava'`, +`implementation libs.guava`, or `implementation(platform("..."))`. None of these match, so the +dependency is not even emitted as `Unresolved` — it is **invisible** to the audit. + +The package's stated value (gradle.go:18-23) is to "surface that a Gradle project's dependency +licenses are unknown, not silently treat the project as license-free." A versionless dep is +silently dropped, partially defeating that. The comment at scanGradleManifest:99-101 ("always +yields at least three parts; no short-coordinate guard is needed") is true only because the regex +pre-filters to 3-part matches — but that pre-filter is itself the silent drop. + +Fix: also match 2-segment coordinates (`group:artifact`) and emit them as Unresolved with +version empty and a reason. Not high severity because Gradle is detect-only anyway, but a +dropped dependency is a worse failure mode than a listed-unresolved one. + +--- + +### 5. (Medium) Unresolved dependencies are a *pass* under the default policy + +`internal/config/config.go:98-104` — `Defaults()` sets `FailOn` to +`{missing-header, unknown-license, policy-violation}` and deliberately omits +`unresolved-dependency`. + +`report.Build` (report.go:158-162) correctly folds an `unresolved-dependency` condition for every +non-resolved dep, and `Check` (report.go:378-387) gates on `Report.Passed`. But `Passed` +(policy.go:315-326) only trips for conditions in `fail_on`. So with the default config, a repo +full of unresolved Gradle/Maven/npm dependencies **passes** `check` (exit 0). + +This is arguably intentional (resolution is best-effort), and it is consistent across the code, +but it is a sharp edge for a tool teams "trust to block bad licenses": the most common real-world +gap (unresolvable third-party licenses) is off by default. No code bug, but flag it in docs and +consider whether `unresolved-dependency` belongs in the shipped default for `check`. There is no +test asserting that the default `fail_on` excludes it, so the default is also untested intent. + +--- + +### 6. (Low) npm resolves only direct declared dependencies + +`internal/resolve/npm.go:56-84` builds the dep set from the **root** package.json's +`dependencies`+`devDependencies` only (`declaredDependencyNames`). Transitive packages that exist +under `node_modules` (including nested `node_modules//node_modules/`) are never enumerated. +For a license CI gate, transitive licenses are usually the *point*. This is documented +(npm.go:14-19 frames node_modules as authoritative for the *declared* set), but "authoritative +and complete" in the Resolve doc comment (lines 53-55) overstates it — it is complete for direct +deps only. Consider walking installed `node_modules/*/package.json` for full coverage, or soften +the comment. + +--- + +### 7. (Low) Flag-exclude accumulation lacks a dedicated test + +`config.go:456-461`: flag excludes append (`cfg.Excludes = append(cfg.Excludes, flags.Exclude...)`), +flag includes replace. This matches the documented contract (excludes accumulate, include is the +highest-precedence *replacing* layer). `TestResolveLayering` (config_test.go:514-522) does verify +the three-layer exclude *union* including the flag layer, so this is covered — downgrade to info. +The include replace-semantics are well tested (lines 534-561). No action required; listed for +completeness. + +--- + +### 8. (Low) Non-git walk honors only the root `.gitignore` + +`enumerate.go:328-334` compiles a single matcher from `/.gitignore`. Nested `.gitignore` +files, the global excludes file, and `.git/info/exclude` are ignored on the walk path. This is +explicitly documented (enumerate.go:321-327) and the git path defers to `git ls-files` which gets +it right. The risk is only that auditing a non-git checkout yields a *different* (larger) file set +than the same tree in git. Acceptable for v1; documented. + +--- + +### 9. (Info) Incompatibility table narrower than its doc comment + +`policy.go:266-286`: the prose says strong/network copyleft "cannot be combined into a single +permissive redistribution" and that GPL-2.0-only has no upgrade path to the v3 family. The table +covers GPL-2.0-only × {Apache, GPL-3-or-later, AGPL-3, LGPL-3} and the copyleft×Apache pairs, but +omits e.g. AGPL-3 × GPL-3 or GPL-3 × LGPL-2.1. Because `EvaluateRepo` also runs the heterogeneity +check (distinct categories > 1), most such pairs still surface as a `policy-violation`, so there +is **no false pass**. This is only a doc/coverage mismatch in the curated table, not a verdict +bug. The function logic (symmetric, self-pair guard, empty guard) is correct. + +--- + +## Things checked and found correct (no finding) + +- **Config precedence** (flags > repo > user > defaults) is implemented correctly: lower layers + seed `cfg`, each higher layer overrides only non-empty fields; `manage_license_file` uses + `*bool` so explicit `false` is distinguishable from absent (config.go:370-372). `KnownFields(true)` + rejects typo'd keys. Empty-document handling returns defaults (decodeYAML:330-342). +- **Excludes accumulate, includes replace** across layers — matches spec and is tested with `**` + patterns at every layer. +- **Year/style parsing** is strict: 4-digit clamp rejects `21`/`20260`, range end Date: Mon, 8 Jun 2026 11:58:01 -0500 Subject: [PATCH 09/14] feat(#29): seed init answers from repo detection --- internal/initwizard/seed.go | 148 ++++++++++++++++++++++++ internal/initwizard/seed_test.go | 190 +++++++++++++++++++++++++++++++ 2 files changed, 338 insertions(+) create mode 100644 internal/initwizard/seed.go create mode 100644 internal/initwizard/seed_test.go diff --git a/internal/initwizard/seed.go b/internal/initwizard/seed.go new file mode 100644 index 0000000..60c8017 --- /dev/null +++ b/internal/initwizard/seed.go @@ -0,0 +1,148 @@ +package initwizard + +import ( + "os" + "os/exec" + "path/filepath" + "sort" + "strings" + + "github.com/KofTwentyTwo/license-tool/internal/config" + "github.com/KofTwentyTwo/license-tool/internal/detect" + "github.com/KofTwentyTwo/license-tool/internal/enumerate" + "github.com/KofTwentyTwo/license-tool/internal/spdx" +) + +// Detected marks which seeded Answers fields came from repo detection, so the form +// can badge them and the user sees what was inferred versus defaulted. +type Detected struct { + License bool + Holder bool + Manage bool +} + +// SeedDeps holds injectable seams for Seed. WHY only the git author is a seam: the +// header scan is deterministic against a temp directory (the project's test style), +// but the configured git author depends on machine/CI git config, so it is injected. +type SeedDeps struct { + // GitAuthor returns the configured author name for root, or "" when unknown. + GitAuthor func(root string) string +} + +// seedReadFile is a seam over os.ReadFile so the per-file read-error path is testable. +var seedReadFile = os.ReadFile + +// Seed pre-fills base from repository detection and reports which fields were +// inferred. It never overrides a non-empty base field (e.g. one set from a flag). +// Detection reuses the same enumerate + detect + spdx machinery as audit, so it +// agrees with the rest of the tool, and it writes nothing: these are editable +// defaults the user reviews against the live preview. +func Seed(root string, base Answers, deps SeedDeps) (Answers, Detected) { + if deps.GitAuthor == nil { + deps.GitAuthor = gitAuthor + } + var detected Detected + + licenseID, holder := scanHeaders(root) + + if base.License.SPDXID == "" && licenseID != "" { + // Only seed a license the tool can actually render; an existing header in an + // id we cannot emit is left for the user to choose explicitly. + if _, ok := spdx.Lookup(licenseID); ok { + base.License.SPDXID = licenseID + detected.License = true + } + } + + if base.Identity.Holder == "" { + switch { + case holder != "": + base.Identity.Holder = holder + detected.Holder = true + default: + if name := deps.GitAuthor(root); name != "" { + base.Identity.Holder = name + detected.Holder = true + } + } + } + + if licenseFileExists(root) { + detected.Manage = true + } + + return base, detected +} + +// scanHeaders enumerates source files and returns the most common detected license +// id and holder among recognized headers; empty strings when none are found. +func scanHeaders(root string) (licenseID, holder string) { + classify := config.ContentLookupFunc(config.Defaults()) + entries, err := enumerate.WithContent(root, enumerate.Options{}, classify) + if err != nil { + return "", "" + } + + licenseCounts := map[string]int{} + holderCounts := map[string]int{} + for _, e := range entries { + if e.Skip { + continue + } + content, rerr := seedReadFile(e.AbsPath) + if rerr != nil { + continue + } + dh, derr := detect.Detect(content, e.FileType) + if derr != nil || !dh.Present { + continue + } + if dh.SPDXID != "" { + licenseCounts[dh.SPDXID]++ + } + if h := strings.TrimSpace(dh.Holder); h != "" { + holderCounts[h]++ + } + } + return mostCommon(licenseCounts), mostCommon(holderCounts) +} + +// mostCommon returns the highest-count key, breaking ties by lexical order for +// determinism; empty when the map is empty. +func mostCommon(counts map[string]int) string { + keys := make([]string, 0, len(counts)) + for k := range counts { + keys = append(keys, k) + } + sort.Strings(keys) + + best, bestCount := "", 0 + for _, k := range keys { + if counts[k] > bestCount { + best, bestCount = k, counts[k] + } + } + return best +} + +// licenseFileExists reports whether a top-level LICENSE file or LICENSES/ directory +// already exists, which the form uses to badge the manage-license-files choice. +func licenseFileExists(root string) bool { + if _, err := os.Stat(filepath.Join(root, "LICENSE")); err == nil { + return true + } + if info, err := os.Stat(filepath.Join(root, "LICENSES")); err == nil && info.IsDir() { + return true + } + return false +} + +// gitAuthor returns the configured git author name for root, or "" when git is +// absent or the value is unset. +func gitAuthor(root string) string { + out, err := exec.Command("git", "-C", root, "config", "user.name").Output() + if err != nil { + return "" + } + return strings.TrimSpace(string(out)) +} diff --git a/internal/initwizard/seed_test.go b/internal/initwizard/seed_test.go new file mode 100644 index 0000000..d42fa95 --- /dev/null +++ b/internal/initwizard/seed_test.go @@ -0,0 +1,190 @@ +package initwizard + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "testing" + + "github.com/KofTwentyTwo/license-tool/internal/config" + "github.com/KofTwentyTwo/license-tool/internal/model" + "github.com/KofTwentyTwo/license-tool/internal/render" + "github.com/KofTwentyTwo/license-tool/internal/spdx" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func seedWriteFile(t *testing.T, root, rel, content string) { + t.Helper() + abs := filepath.Join(root, rel) + require.NoError(t, os.MkdirAll(filepath.Dir(abs), 0o755)) + require.NoError(t, os.WriteFile(abs, []byte(content), 0o644)) +} + +// seedWriteHeadered writes a Go file carrying a real managed header for licID/holder, +// built through the same render path apply uses so detect is guaranteed to recognize +// it. WHY round-trip through render: it ties the test to the tool's actual header +// shape rather than a hand-rolled approximation that could drift from detect. +func seedWriteHeadered(t *testing.T, root, rel, pkg, licID, holder string) { + t.Helper() + ft, ok := config.LookupFunc(config.Defaults())(rel) + require.True(t, ok) + lic, ok := spdx.Lookup(licID) + require.True(t, ok) + hdr, err := render.Header(render.HeaderInput{ + License: lic, + Holder: holder, + Year: "2024", + Style: model.StyleReusePlusNotice, + FileType: ft, + }) + require.NoError(t, err) + content, _ := render.Insert([]byte(pkg), ft, hdr) + seedWriteFile(t, root, rel, string(content)) +} + +func noAuthor(string) string { return "" } +func gitPerson(string) string { return "Git Person" } + +func TestSeedFromHeaders(t *testing.T) { + root := t.TempDir() + seedWriteHeadered(t, root, "a.go", "package a\n", "MIT", "Acme, LLC") + seedWriteHeadered(t, root, "b.go", "package b\n", "MIT", "Acme, LLC") + + got, detected := Seed(root, Answers{}, SeedDeps{GitAuthor: gitPerson}) + + assert.Equal(t, "MIT", got.License.SPDXID) + assert.Equal(t, "Acme, LLC", got.Identity.Holder) + assert.True(t, detected.License) + assert.True(t, detected.Holder) +} + +func TestSeedTieBreaksLexically(t *testing.T) { + root := t.TempDir() + seedWriteHeadered(t, root, "a.go", "package a\n", "MIT", "Bravo Co") + seedWriteHeadered(t, root, "b.go", "package b\n", "Apache-2.0", "Alpha Co") + + got, detected := Seed(root, Answers{}, SeedDeps{GitAuthor: noAuthor}) + + // 1-1 ties resolve to the lexically-first key for determinism. + assert.Equal(t, "Apache-2.0", got.License.SPDXID) + assert.Equal(t, "Alpha Co", got.Identity.Holder) + assert.True(t, detected.License) + assert.True(t, detected.Holder) +} + +func TestSeedGitAuthorFallback(t *testing.T) { + root := t.TempDir() + // A plain source file with no header exercises detect's not-present path. + seedWriteFile(t, root, "main.go", "package main\n") + + got, detected := Seed(root, Answers{}, SeedDeps{GitAuthor: gitPerson}) + + assert.Equal(t, "Git Person", got.Identity.Holder) + assert.True(t, detected.Holder) + assert.Empty(t, got.License.SPDXID) + assert.False(t, detected.License) +} + +func TestSeedNoDetection(t *testing.T) { + root := t.TempDir() + seedWriteFile(t, root, "main.go", "package main\n") + + got, detected := Seed(root, Answers{}, SeedDeps{GitAuthor: noAuthor}) + + assert.Empty(t, got.License.SPDXID) + assert.Empty(t, got.Identity.Holder) + assert.Equal(t, Detected{}, detected) +} + +func TestSeedDoesNotOverridePreset(t *testing.T) { + root := t.TempDir() + seedWriteHeadered(t, root, "a.go", "package a\n", "MIT", "Acme, LLC") + + base := Answers{ + License: LicenseAnswer{SPDXID: "GPL-3.0-or-later"}, + Identity: IdentityAnswer{Holder: "Preset Holder"}, + } + got, detected := Seed(root, base, SeedDeps{GitAuthor: gitPerson}) + + assert.Equal(t, "GPL-3.0-or-later", got.License.SPDXID) + assert.Equal(t, "Preset Holder", got.Identity.Holder) + assert.False(t, detected.License) + assert.False(t, detected.Holder) +} + +func TestSeedUnrenderableLicenseNotSeeded(t *testing.T) { + root := t.TempDir() + // A real SPDX id the tool does not ship rendering for; detect reads the tag, but + // Seed must not adopt a license it cannot render. + seedWriteFile(t, root, "x.go", "// SPDX-License-Identifier: Glide\n\npackage x\n") + + got, detected := Seed(root, Answers{}, SeedDeps{GitAuthor: noAuthor}) + + assert.Empty(t, got.License.SPDXID) + assert.False(t, detected.License) +} + +func TestSeedDetectsLicenseFile(t *testing.T) { + t.Run("LICENSE file present", func(t *testing.T) { + root := t.TempDir() + seedWriteFile(t, root, "LICENSE", "MIT License\n") + _, detected := Seed(root, Answers{}, SeedDeps{GitAuthor: noAuthor}) + assert.True(t, detected.Manage) + }) + + t.Run("LICENSES directory present", func(t *testing.T) { + root := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(root, "LICENSES"), 0o755)) + _, detected := Seed(root, Answers{}, SeedDeps{GitAuthor: noAuthor}) + assert.True(t, detected.Manage) + }) +} + +func TestSeedReadErrorSkipsFile(t *testing.T) { + root := t.TempDir() + seedWriteHeadered(t, root, "a.go", "package a\n", "MIT", "Acme, LLC") + + orig := seedReadFile + seedReadFile = func(string) ([]byte, error) { return nil, errors.New("boom") } + defer func() { seedReadFile = orig }() + + got, detected := Seed(root, Answers{}, SeedDeps{GitAuthor: noAuthor}) + + assert.Empty(t, got.License.SPDXID) + assert.False(t, detected.License) +} + +func TestSeedEnumerateErrorIsSafe(t *testing.T) { + got, detected := Seed(filepath.Join(t.TempDir(), "does-not-exist"), Answers{}, SeedDeps{GitAuthor: noAuthor}) + assert.Empty(t, got.License.SPDXID) + assert.Empty(t, got.Identity.Holder) + assert.Equal(t, Detected{}, detected) +} + +// TestGitAuthorErrorIsEmpty covers gitAuthor's failure path: git cannot chdir into a +// nonexistent directory, so it exits non-zero and the helper yields "". +func TestGitAuthorErrorIsEmpty(t *testing.T) { + assert.Empty(t, gitAuthor(filepath.Join(t.TempDir(), "missing", "deeper"))) +} + +// TestSeedDefaultGitAuthor exercises the default seam (deps.GitAuthor nil) against a +// real repo whose author is configured, covering the nil-default branch and the real +// gitAuthor helper. +func TestSeedDefaultGitAuthor(t *testing.T) { + root := t.TempDir() + for _, args := range [][]string{ + {"init"}, + {"config", "user.name", "Repo Author"}, + {"config", "user.email", "repo@example.com"}, + } { + cmd := exec.Command("git", append([]string{"-C", root}, args...)...) + require.NoError(t, cmd.Run()) + } + seedWriteFile(t, root, "main.go", "package main\n") + + got, detected := Seed(root, Answers{}, SeedDeps{}) + assert.Equal(t, "Repo Author", got.Identity.Holder) + assert.True(t, detected.Holder) +} -- 2.54.0 From 45dcfd90e120e5bcd769acd64b23bce387bacbdd Mon Sep 17 00:00:00 2001 From: James Maes Date: Mon, 8 Jun 2026 12:13:25 -0500 Subject: [PATCH 10/14] feat(#29): pure form state machine with live validation --- internal/initwizard/form.go | 435 +++++++++++++++++++++++++++++++ internal/initwizard/form_test.go | 307 ++++++++++++++++++++++ 2 files changed, 742 insertions(+) create mode 100644 internal/initwizard/form.go create mode 100644 internal/initwizard/form_test.go diff --git a/internal/initwizard/form.go b/internal/initwizard/form.go new file mode 100644 index 0000000..c2e5f0e --- /dev/null +++ b/internal/initwizard/form.go @@ -0,0 +1,435 @@ +package initwizard + +import ( + "strings" + + "github.com/KofTwentyTwo/license-tool/internal/config" + "github.com/KofTwentyTwo/license-tool/internal/model" + "github.com/KofTwentyTwo/license-tool/internal/spdx" +) + +// Field identifies one editable row of the single-screen init form, in display +// order. FieldWrite is the trailing "write" affordance, not a value. +type Field int + +const ( + FieldLicense Field = iota + FieldHolder + FieldYear + FieldStyle + FieldManageFiles + FieldInclude + FieldExclude + FieldWrite +) + +// fieldCount is the number of focusable rows (values + the write action). +const fieldCount = int(FieldWrite) + 1 + +// Label is the human label for a field row. +func (f Field) Label() string { + switch f { + case FieldLicense: + return "License" + case FieldHolder: + return "Holder" + case FieldYear: + return "Year" + case FieldStyle: + return "Header style" + case FieldManageFiles: + return "Manage license files" + case FieldInclude: + return "Include globs" + case FieldExclude: + return "Exclude globs" + default: + return "Write .license-tool.yaml" + } +} + +// Action is the outcome the adapter must act on after a transition: write the config +// or quit. Most transitions return ActionNone. +type Action int + +const ( + // ActionNone means the transition only changed in-form state. + ActionNone Action = iota + // ActionWrite means the user confirmed a valid write. + ActionWrite + // ActionQuit means the user asked to leave without writing. + ActionQuit +) + +// FieldError is a single failed validation, addressed to the field that owns it. +type FieldError struct { + Field Field + Msg string +} + +// styleOptions are the selectable header styles, in display order. +var styleOptions = []string{"reuse", "notice", "reuse+notice"} + +// FormState is the pure, PTY-free state of the init form: the answers being edited, +// which fields were repo-detected, the focused row, and any open editor's transient +// cursor/buffer. The Bubble Tea adapter maps keystrokes to the transition methods +// and renders via Render; all behavior is unit-tested here so the adapter stays a +// trivial, coverage-excluded shell. +type FormState struct { + answers Answers + detected Detected + focus Field + editing bool + + licenseOptions []string + licenseFilter string + licenseCursor int + + styleCursor int + + textBuffer string + + globBuffer string + globCursor int +} + +// NewForm builds a form from seeded answers, applying the documented defaults for any +// field the caller left unset (license = first option, year = git, style = reuse+notice). +func NewForm(a Answers, detected Detected) FormState { + s := FormState{ + answers: a, + detected: detected, + focus: FieldLicense, + licenseOptions: licenseSelectOptions(), + } + if s.answers.License.SPDXID == "" && len(s.licenseOptions) > 0 { + s.answers.License.SPDXID = s.licenseOptions[0] + } + if s.answers.Identity.Year == "" { + s.answers.Identity.Year = "git" + } + if s.answers.HeaderStyle.Style == "" { + s.answers.HeaderStyle.Style = "reuse+notice" + } + return s +} + +// licenseSelectOptions lists renderable SPDX ids with the common ones first, then the +// remaining renderable ids in sorted order, without duplicates. +func licenseSelectOptions() []string { + return selectOptions(spdx.CommonIDs(), spdx.RenderableIDs()) +} + +// selectOptions merges the editorial common list (kept first, in order) with the full +// renderable list (appended, deduped). Split out from licenseSelectOptions so the +// dedup/append behavior is unit-testable independent of the vendored snapshot, where +// the common set currently happens to cover every renderable id. +func selectOptions(common, renderable []string) []string { + seen := make(map[string]bool, len(common)) + opts := make([]string, 0, len(common)+len(renderable)) + for _, id := range common { + seen[id] = true + opts = append(opts, id) + } + for _, id := range renderable { + if !seen[id] { + opts = append(opts, id) + } + } + return opts +} + +// Editing reports whether the focused field's inline editor is open. +func (s FormState) Editing() bool { return s.editing } + +// Focused returns the focused field. +func (s FormState) Focused() Field { return s.focus } + +// Answers returns the current answers (a snapshot for the adapter to translate). +func (s FormState) Answers() Answers { return s.answers } + +// WriteConfig translates the current answers strictly, for the write path. +func (s FormState) WriteConfig() (model.Config, error) { + return Translate(s.answers, TranslateOptions{}) +} + +// MoveFocus moves the focused row by delta, wrapping. No-op while an editor is open. +func (s *FormState) MoveFocus(delta int) { + if s.editing { + return + } + s.focus = Field(((int(s.focus)+delta)%fieldCount + fieldCount) % fieldCount) +} + +// Activate handles Enter (or space) on the focused row: toggles the manage flag, +// requests a write from the write row (only when valid), or opens an inline editor. +func (s *FormState) Activate() Action { + switch s.focus { + case FieldManageFiles: + s.answers.LicenseFiles.Manage = !s.answers.LicenseFiles.Manage + return ActionNone + case FieldWrite: + if s.CanWrite() { + return ActionWrite + } + return ActionNone + default: + s.openEditor() + return ActionNone + } +} + +func (s *FormState) openEditor() { + s.editing = true + switch s.focus { + case FieldLicense: + s.licenseFilter = "" + s.licenseCursor = s.licenseIndexOf(s.answers.License.SPDXID) + case FieldHolder: + s.textBuffer = s.answers.Identity.Holder + case FieldYear: + s.textBuffer = s.answers.Identity.Year + case FieldStyle: + s.styleCursor = optionIndex(styleOptions, s.answers.HeaderStyle.Style) + case FieldInclude, FieldExclude: + s.globBuffer = "" + s.globCursor = 0 + } +} + +// Cancel handles Esc: close an open editor (discarding its buffer), or quit when no +// editor is open. +func (s *FormState) Cancel() Action { + if s.editing { + s.editing = false + return ActionNone + } + return ActionQuit +} + +// Input feeds a typed rune into the active editor's buffer (license filter, text +// field, or glob entry). No-op outside an editor or for non-text editors. +func (s *FormState) Input(r rune) { + if !s.editing { + return + } + switch s.focus { + case FieldLicense: + s.licenseFilter += string(r) + s.clampLicenseCursor() + case FieldHolder, FieldYear: + s.textBuffer += string(r) + case FieldInclude, FieldExclude: + s.globBuffer += string(r) + } +} + +// Backspace deletes the last rune of the active editor's buffer. +func (s *FormState) Backspace() { + if !s.editing { + return + } + switch s.focus { + case FieldLicense: + s.licenseFilter = dropLastRune(s.licenseFilter) + s.clampLicenseCursor() + case FieldHolder, FieldYear: + s.textBuffer = dropLastRune(s.textBuffer) + case FieldInclude, FieldExclude: + s.globBuffer = dropLastRune(s.globBuffer) + } +} + +// MoveCursor moves the selection within an open list/choice editor (license choices, +// style options, or existing glob entries). +func (s *FormState) MoveCursor(delta int) { + if !s.editing { + return + } + switch s.focus { + case FieldLicense: + if n := len(s.filteredLicenses()); n > 0 { + s.licenseCursor = clamp(s.licenseCursor+delta, 0, n-1) + } + case FieldStyle: + s.styleCursor = clamp(s.styleCursor+delta, 0, len(styleOptions)-1) + case FieldInclude, FieldExclude: + if n := len(s.globEntries()); n > 0 { + s.globCursor = clamp(s.globCursor+delta, 0, n-1) + } + } +} + +// Commit handles Enter inside an editor: choose the selected license/style, store the +// text field, or append the buffered glob (the glob editor stays open for more adds). +func (s *FormState) Commit() { + if !s.editing { + return + } + switch s.focus { + case FieldLicense: + if choices := s.filteredLicenses(); len(choices) > 0 { + s.answers.License.SPDXID = choices[clamp(s.licenseCursor, 0, len(choices)-1)] + } + s.editing = false + case FieldStyle: + s.answers.HeaderStyle.Style = styleOptions[clamp(s.styleCursor, 0, len(styleOptions)-1)] + s.editing = false + case FieldHolder: + s.answers.Identity.Holder = strings.TrimSpace(s.textBuffer) + s.editing = false + case FieldYear: + s.answers.Identity.Year = strings.TrimSpace(s.textBuffer) + s.editing = false + case FieldInclude: + if g := strings.TrimSpace(s.globBuffer); g != "" { + s.answers.Coverage.Include = append(s.answers.Coverage.Include, g) + s.globBuffer = "" + } + case FieldExclude: + if g := strings.TrimSpace(s.globBuffer); g != "" { + s.answers.Coverage.Exclude = append(s.answers.Coverage.Exclude, g) + s.globBuffer = "" + } + } +} + +// Remove deletes the selected entry from the focused glob list editor. +func (s *FormState) Remove() { + if !s.editing { + return + } + switch s.focus { + case FieldInclude: + s.answers.Coverage.Include = removeAt(s.answers.Coverage.Include, s.globCursor) + s.clampGlobCursor() + case FieldExclude: + s.answers.Coverage.Exclude = removeAt(s.answers.Coverage.Exclude, s.globCursor) + s.clampGlobCursor() + } +} + +// Validate returns every failing field-level rule. An empty result means the answers +// can be written. +func (s FormState) Validate() []FieldError { + var errs []FieldError + if _, ok := spdx.Lookup(strings.TrimSpace(s.answers.License.SPDXID)); !ok { + errs = append(errs, FieldError{FieldLicense, "choose a supported license"}) + } + if strings.TrimSpace(s.answers.Identity.Holder) == "" { + errs = append(errs, FieldError{FieldHolder, "holder is required"}) + } + if y := strings.TrimSpace(s.answers.Identity.Year); y != "" { + if _, err := config.ParseYearSpec(y); err != nil { + errs = append(errs, FieldError{FieldYear, "use current, git, YYYY, or YYYY-YYYY"}) + } + } + for _, g := range s.answers.Coverage.Include { + if !validGlob(g) { + errs = append(errs, FieldError{FieldInclude, "glob entries cannot be blank"}) + break + } + } + for _, g := range s.answers.Coverage.Exclude { + if !validGlob(g) { + errs = append(errs, FieldError{FieldExclude, "glob entries cannot be blank"}) + break + } + } + return errs +} + +// CanWrite reports whether the answers pass every validation rule. +func (s FormState) CanWrite() bool { + return len(s.Validate()) == 0 +} + +// BlockingReason returns the first validation message, or "" when writable. The +// footer shows this to explain why the write action is disabled. +func (s FormState) BlockingReason() string { + if errs := s.Validate(); len(errs) > 0 { + return errs[0].Msg + } + return "" +} + +func (s FormState) filteredLicenses() []string { + f := strings.ToLower(strings.TrimSpace(s.licenseFilter)) + if f == "" { + return s.licenseOptions + } + out := make([]string, 0, len(s.licenseOptions)) + for _, id := range s.licenseOptions { + if strings.Contains(strings.ToLower(id), f) { + out = append(out, id) + } + } + return out +} + +func (s FormState) licenseIndexOf(id string) int { + return optionIndex(s.filteredLicenses(), id) +} + +func (s *FormState) clampLicenseCursor() { + n := len(s.filteredLicenses()) + if n == 0 { + s.licenseCursor = 0 + return + } + s.licenseCursor = clamp(s.licenseCursor, 0, n-1) +} + +func (s FormState) globEntries() []string { + if s.focus == FieldExclude { + return s.answers.Coverage.Exclude + } + return s.answers.Coverage.Include +} + +func (s *FormState) clampGlobCursor() { + n := len(s.globEntries()) + if n == 0 { + s.globCursor = 0 + return + } + s.globCursor = clamp(s.globCursor, 0, n-1) +} + +func validGlob(g string) bool { + return strings.TrimSpace(g) != "" +} + +func optionIndex(values []string, value string) int { + for i, v := range values { + if v == value { + return i + } + } + return 0 +} + +func clamp(v, lo, hi int) int { + if v < lo { + return lo + } + if v > hi { + return hi + } + return v +} + +func dropLastRune(s string) string { + if s == "" { + return s + } + r := []rune(s) + return string(r[:len(r)-1]) +} + +func removeAt(values []string, i int) []string { + if i < 0 || i >= len(values) { + return values + } + return append(values[:i], values[i+1:]...) +} diff --git a/internal/initwizard/form_test.go b/internal/initwizard/form_test.go new file mode 100644 index 0000000..cb52540 --- /dev/null +++ b/internal/initwizard/form_test.go @@ -0,0 +1,307 @@ +package initwizard + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func validForm() FormState { + return NewForm(Answers{ + License: LicenseAnswer{SPDXID: "MIT"}, + Identity: IdentityAnswer{Holder: "Acme, LLC", Year: "git"}, + }, Detected{}) +} + +func TestFieldLabel(t *testing.T) { + for f, want := range map[Field]string{ + FieldLicense: "License", + FieldHolder: "Holder", + FieldYear: "Year", + FieldStyle: "Header style", + FieldManageFiles: "Manage license files", + FieldInclude: "Include globs", + FieldExclude: "Exclude globs", + FieldWrite: "Write .license-tool.yaml", + } { + assert.Equal(t, want, f.Label()) + } +} + +func TestNewFormDefaults(t *testing.T) { + s := NewForm(Answers{}, Detected{}) + require.NotEmpty(t, s.licenseOptions) + assert.Equal(t, s.licenseOptions[0], s.answers.License.SPDXID) + assert.Equal(t, "git", s.answers.Identity.Year) + assert.Equal(t, "reuse+notice", s.answers.HeaderStyle.Style) + assert.Equal(t, FieldLicense, s.Focused()) + assert.False(t, s.Editing()) +} + +func TestNewFormPreservesPresets(t *testing.T) { + s := NewForm(Answers{ + License: LicenseAnswer{SPDXID: "Apache-2.0"}, + Identity: IdentityAnswer{Year: "2024"}, + HeaderStyle: HeaderStyleAnswer{Style: "reuse"}, + }, Detected{License: true}) + assert.Equal(t, "Apache-2.0", s.answers.License.SPDXID) + assert.Equal(t, "2024", s.answers.Identity.Year) + assert.Equal(t, "reuse", s.answers.HeaderStyle.Style) +} + +func TestMoveFocusWraps(t *testing.T) { + s := validForm() + s.MoveFocus(-1) + assert.Equal(t, FieldWrite, s.Focused()) + s.MoveFocus(1) + assert.Equal(t, FieldLicense, s.Focused()) + + s.editing = true + s.MoveFocus(1) // no-op while editing + assert.Equal(t, FieldLicense, s.Focused()) +} + +func TestActivateManageToggles(t *testing.T) { + s := validForm() + s.focus = FieldManageFiles + assert.False(t, s.answers.LicenseFiles.Manage) + assert.Equal(t, ActionNone, s.Activate()) + assert.True(t, s.answers.LicenseFiles.Manage) + assert.False(t, s.Editing()) +} + +func TestActivateWrite(t *testing.T) { + t.Run("valid form requests write", func(t *testing.T) { + s := validForm() + s.focus = FieldWrite + assert.Equal(t, ActionWrite, s.Activate()) + }) + t.Run("invalid form does not write", func(t *testing.T) { + s := NewForm(Answers{License: LicenseAnswer{SPDXID: "MIT"}}, Detected{}) // empty holder + s.focus = FieldWrite + assert.Equal(t, ActionNone, s.Activate()) + }) +} + +func TestActivateOpensEditors(t *testing.T) { + for _, f := range []Field{FieldLicense, FieldHolder, FieldYear, FieldStyle, FieldInclude, FieldExclude} { + s := validForm() + s.focus = f + assert.Equal(t, ActionNone, s.Activate()) + assert.True(t, s.Editing(), "field %v should open an editor", f) + } +} + +func TestCancel(t *testing.T) { + s := validForm() + s.focus = FieldHolder + s.Activate() + require.True(t, s.Editing()) + assert.Equal(t, ActionNone, s.Cancel()) + assert.False(t, s.Editing()) + + assert.Equal(t, ActionQuit, s.Cancel()) +} + +func TestLicenseFilterAndCommit(t *testing.T) { + s := validForm() + s.focus = FieldLicense + s.Activate() + for _, r := range "apache" { + s.Input(r) + } + choices := s.filteredLicenses() + require.NotEmpty(t, choices) + assert.Contains(t, choices[0], "Apache") + s.MoveCursor(1) // exercise the license-cursor move with a non-empty result set + s.Commit() + assert.False(t, s.Editing()) + assert.Equal(t, "Apache-2.0", s.answers.License.SPDXID) +} + +func TestLicenseBackspaceAndEmptyFilter(t *testing.T) { + s := validForm() + s.focus = FieldLicense + s.Activate() + for _, r := range "zzz" { + s.Input(r) + } + assert.Empty(t, s.filteredLicenses()) + s.MoveCursor(1) // n==0 path + s.Commit() // choices==0 path: license unchanged, editor closes + assert.Equal(t, "MIT", s.answers.License.SPDXID) + assert.False(t, s.Editing()) + + s.Activate() + s.Input('m') + s.Backspace() + assert.Equal(t, s.licenseOptions, s.filteredLicenses()) +} + +func TestStyleEditor(t *testing.T) { + s := validForm() + s.focus = FieldStyle + s.Activate() + s.MoveCursor(-100) // clamps to first + s.Commit() + assert.Equal(t, "reuse", s.answers.HeaderStyle.Style) + + s.Activate() + s.MoveCursor(100) // clamps to last + s.Commit() + assert.Equal(t, "reuse+notice", s.answers.HeaderStyle.Style) +} + +func TestTextEditors(t *testing.T) { + s := validForm() + s.focus = FieldHolder + s.Activate() + s.Backspace() // trim a char from "Acme, LLC" + for _, r := range " Inc" { + s.Input(r) + } + s.Commit() + assert.Equal(t, "Acme, LL Inc", s.answers.Identity.Holder) + assert.False(t, s.Editing()) + + s.focus = FieldYear + s.Activate() + s.textBuffer = "2020-2025" + s.Commit() + assert.Equal(t, "2020-2025", s.answers.Identity.Year) +} + +func TestGlobEditorAddRemove(t *testing.T) { + s := validForm() + s.focus = FieldInclude + s.Activate() + for _, r := range "src/**" { + s.Input(r) + } + s.Commit() // adds, stays open + assert.True(t, s.Editing()) + assert.Equal(t, []string{"src/**"}, s.answers.Coverage.Include) + + s.globBuffer = " " // blank add is a no-op + s.Commit() + assert.Equal(t, []string{"src/**"}, s.answers.Coverage.Include) + + for _, r := range "docs/**" { + s.Input(r) + } + s.Commit() + assert.Equal(t, []string{"src/**", "docs/**"}, s.answers.Coverage.Include) + + s.MoveCursor(1) // select second + s.Remove() + assert.Equal(t, []string{"src/**"}, s.answers.Coverage.Include) + + // Exclude path mirrors include. + s.focus = FieldExclude + s.Activate() + for _, r := range "**/vendor/**" { + s.Input(r) + } + s.Commit() + assert.Equal(t, []string{"**/vendor/**"}, s.answers.Coverage.Exclude) + s.Remove() + assert.Empty(t, s.answers.Coverage.Exclude) +} + +func TestTransitionsNoopWhenNotEditing(t *testing.T) { + s := validForm() + // None of these should panic or mutate when no editor is open. + s.Input('x') + s.Backspace() + s.MoveCursor(1) + s.Commit() + s.Remove() + assert.False(t, s.Editing()) + assert.Equal(t, "MIT", s.answers.License.SPDXID) +} + +func TestValidate(t *testing.T) { + t.Run("valid form has no errors", func(t *testing.T) { + assert.Empty(t, validForm().Validate()) + assert.True(t, validForm().CanWrite()) + assert.Empty(t, validForm().BlockingReason()) + }) + + t.Run("each rule reports", func(t *testing.T) { + s := NewForm(Answers{ + License: LicenseAnswer{SPDXID: "NOPE"}, + Identity: IdentityAnswer{Year: "bad"}, + Coverage: CoverageAnswer{Include: []string{" "}, Exclude: []string{"\t"}}, + }, Detected{}) + errs := s.Validate() + fields := map[Field]string{} + for _, e := range errs { + fields[e.Field] = e.Msg + } + assert.Contains(t, fields, FieldLicense) + assert.Contains(t, fields, FieldHolder) + assert.Contains(t, fields, FieldYear) + assert.Contains(t, fields, FieldInclude) + assert.Contains(t, fields, FieldExclude) + assert.False(t, s.CanWrite()) + assert.NotEmpty(t, s.BlockingReason()) + }) +} + +func TestWriteConfig(t *testing.T) { + cfg, err := validForm().WriteConfig() + require.NoError(t, err) + assert.Equal(t, "MIT", cfg.License) + + _, err = NewForm(Answers{License: LicenseAnswer{SPDXID: "MIT"}}, Detected{}).WriteConfig() + assert.Error(t, err) // empty holder +} + +func TestSmallHelpers(t *testing.T) { + assert.Equal(t, 0, optionIndex([]string{"a", "b"}, "missing")) + assert.Equal(t, 1, optionIndex([]string{"a", "b"}, "b")) + assert.Equal(t, 5, clamp(10, 0, 5)) + assert.Equal(t, 0, clamp(-2, 0, 5)) + assert.Equal(t, 3, clamp(3, 0, 5)) + assert.Equal(t, "", dropLastRune("")) + assert.Equal(t, "ab", dropLastRune("abc")) + assert.False(t, validGlob(" ")) + assert.True(t, validGlob("src/**")) + assert.Equal(t, []string{"a"}, removeAt([]string{"a"}, 5)) // out of range + assert.Equal(t, []string{"a"}, removeAt([]string{"a"}, -1)) +} + +func TestGlobCursorClampOnEmpty(t *testing.T) { + s := validForm() + s.focus = FieldInclude + s.Activate() + s.globCursor = 4 + s.clampGlobCursor() // no entries -> resets to 0 + assert.Equal(t, 0, s.globCursor) +} + +func TestAnswersAccessor(t *testing.T) { + s := validForm() + assert.Equal(t, "MIT", s.Answers().License.SPDXID) +} + +func TestGlobEditorBackspaceAndEmptyCursor(t *testing.T) { + s := validForm() + s.focus = FieldExclude + s.Activate() + for _, r := range "vend" { + s.Input(r) + } + s.Backspace() // glob-buffer backspace path + s.MoveCursor(1) // no entries yet -> n==0 path + s.Commit() + assert.Equal(t, []string{"ven"}, s.answers.Coverage.Exclude) +} + +func TestSelectOptionsDedupAndAppend(t *testing.T) { + // renderable carries an id absent from common, exercising the append branch the + // vendored snapshot cannot (its common set covers every renderable id). + got := selectOptions([]string{"MIT", "Apache-2.0"}, []string{"Apache-2.0", "MIT", "ZZ-Extra"}) + assert.Equal(t, []string{"MIT", "Apache-2.0", "ZZ-Extra"}, got) +} -- 2.54.0 From a6cc331fea6d5f32985d1be9591c1b7ce3672aa7 Mon Sep 17 00:00:00 2001 From: James Maes Date: Mon, 8 Jun 2026 12:14:31 -0500 Subject: [PATCH 11/14] feat(#29): adaptive panel layout planner --- internal/initwizard/layout.go | 92 ++++++++++++++++++++++++++++++ internal/initwizard/layout_test.go | 64 +++++++++++++++++++++ 2 files changed, 156 insertions(+) create mode 100644 internal/initwizard/layout.go create mode 100644 internal/initwizard/layout_test.go diff --git a/internal/initwizard/layout.go b/internal/initwizard/layout.go new file mode 100644 index 0000000..67ae23d --- /dev/null +++ b/internal/initwizard/layout.go @@ -0,0 +1,92 @@ +package initwizard + +// PanelKind identifies a renderable panel in the layout plan. +type PanelKind int + +const ( + // PanelForm is the editable field column. + PanelForm PanelKind = iota + // PanelSourcePreview is the rendered example source file. + PanelSourcePreview + // PanelYAMLPreview is the .license-tool.yaml preview. + PanelYAMLPreview +) + +// Orientation is how the panels are arranged. +type Orientation int + +const ( + // LayoutHorizontal places panels side by side. + LayoutHorizontal Orientation = iota + // LayoutStacked places panels top to bottom. + LayoutStacked +) + +// Panel is one panel's kind and its allotted interior dimensions. +type Panel struct { + Kind PanelKind + Width int + Height int +} + +// PanelPlan is the adaptive layout decision for a given terminal body size. When +// TooSmall is set the caller should refuse the TUI and fall back to flag-only init. +type PanelPlan struct { + TooSmall bool + Orientation Orientation + Panels []Panel +} + +// Layout breakpoints. WHY adaptive panel count: a teaching tool wants the source AND +// yaml previews beside the form when there is room, two panels at medium width, and a +// stacked single column when narrow; below the floor the previews cannot render +// usefully so the TUI is refused. +const ( + layoutMinWidth = 60 + layoutMinHeight = 20 + layoutFormWidth = 40 + layoutWideBreakpoint = 110 + layoutMediumBreakpoint = 80 + layoutGutter = 1 +) + +// Layout chooses the panel arrangement for the given body width and height. +func Layout(width, height int) PanelPlan { + if width < layoutMinWidth || height < layoutMinHeight { + return PanelPlan{TooSmall: true} + } + + switch { + case width >= layoutWideBreakpoint: + rest := width - layoutFormWidth - 2*layoutGutter + src := rest / 2 + yaml := rest - src + return PanelPlan{ + Orientation: LayoutHorizontal, + Panels: []Panel{ + {PanelForm, layoutFormWidth, height}, + {PanelSourcePreview, src, height}, + {PanelYAMLPreview, yaml, height}, + }, + } + case width >= layoutMediumBreakpoint: + src := width - layoutFormWidth - layoutGutter + return PanelPlan{ + Orientation: LayoutHorizontal, + Panels: []Panel{ + {PanelForm, layoutFormWidth, height}, + {PanelSourcePreview, src, height}, + }, + } + default: + formHeight := height / 2 + srcHeight := height - formHeight - layoutGutter + return PanelPlan{ + Orientation: LayoutStacked, + Panels: []Panel{ + {PanelForm, width, formHeight}, + {PanelSourcePreview, width, srcHeight}, + }, + } + } +} diff --git a/internal/initwizard/layout_test.go b/internal/initwizard/layout_test.go new file mode 100644 index 0000000..6084496 --- /dev/null +++ b/internal/initwizard/layout_test.go @@ -0,0 +1,64 @@ +package initwizard + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func panelKinds(plan PanelPlan) []PanelKind { + kinds := make([]PanelKind, 0, len(plan.Panels)) + for _, p := range plan.Panels { + kinds = append(kinds, p.Kind) + } + return kinds +} + +func TestLayoutTooSmall(t *testing.T) { + for _, dim := range [][2]int{{50, 30}, {120, 10}, {59, 19}} { + plan := Layout(dim[0], dim[1]) + assert.True(t, plan.TooSmall, "%dx%d should be too small", dim[0], dim[1]) + assert.Empty(t, plan.Panels) + } +} + +func TestLayoutWideHasThreePanels(t *testing.T) { + plan := Layout(120, 40) + require.False(t, plan.TooSmall) + assert.Equal(t, LayoutHorizontal, plan.Orientation) + assert.Equal(t, []PanelKind{PanelForm, PanelSourcePreview, PanelYAMLPreview}, panelKinds(plan)) + + total := 2 * layoutGutter + for _, p := range plan.Panels { + total += p.Width + assert.Equal(t, 40, p.Height) + } + assert.Equal(t, 120, total) + assert.Equal(t, layoutFormWidth, plan.Panels[0].Width) +} + +func TestLayoutMediumHasTwoPanels(t *testing.T) { + plan := Layout(90, 30) + require.False(t, plan.TooSmall) + assert.Equal(t, LayoutHorizontal, plan.Orientation) + assert.Equal(t, []PanelKind{PanelForm, PanelSourcePreview}, panelKinds(plan)) + assert.Equal(t, 90, plan.Panels[0].Width+plan.Panels[1].Width+layoutGutter) +} + +func TestLayoutNarrowStacks(t *testing.T) { + plan := Layout(70, 24) + require.False(t, plan.TooSmall) + assert.Equal(t, LayoutStacked, plan.Orientation) + assert.Equal(t, []PanelKind{PanelForm, PanelSourcePreview}, panelKinds(plan)) + for _, p := range plan.Panels { + assert.Equal(t, 70, p.Width) + } + assert.Equal(t, 24, plan.Panels[0].Height+plan.Panels[1].Height+layoutGutter) +} + +func TestLayoutBreakpointBoundaries(t *testing.T) { + assert.Len(t, Layout(layoutWideBreakpoint, 40).Panels, 3) + assert.Len(t, Layout(layoutMediumBreakpoint, 40).Panels, 2) + assert.Equal(t, LayoutStacked, Layout(layoutMinWidth, layoutMinHeight).Orientation) +} -- 2.54.0 From 09c8174841c72ec42c001ef06a74318cadce5956 Mon Sep 17 00:00:00 2001 From: James Maes Date: Mon, 8 Jun 2026 12:21:24 -0500 Subject: [PATCH 12/14] feat(#29): pure adaptive view rendering for init form --- internal/initwizard/layout.go | 2 +- internal/initwizard/view.go | 338 +++++++++++++++++++++++++++++++ internal/initwizard/view_test.go | 151 ++++++++++++++ 3 files changed, 490 insertions(+), 1 deletion(-) create mode 100644 internal/initwizard/view.go create mode 100644 internal/initwizard/view_test.go diff --git a/internal/initwizard/layout.go b/internal/initwizard/layout.go index 67ae23d..7f1f8b4 100644 --- a/internal/initwizard/layout.go +++ b/internal/initwizard/layout.go @@ -44,7 +44,7 @@ type PanelPlan struct { const ( layoutMinWidth = 60 layoutMinHeight = 20 - layoutFormWidth = 40 + layoutFormWidth = 46 layoutWideBreakpoint = 110 layoutMediumBreakpoint = 80 layoutGutter = 1 diff --git a/internal/initwizard/view.go b/internal/initwizard/view.go new file mode 100644 index 0000000..e06af33 --- /dev/null +++ b/internal/initwizard/view.go @@ -0,0 +1,338 @@ +package initwizard + +import ( + "fmt" + "strings" + + "github.com/charmbracelet/lipgloss" + + "github.com/KofTwentyTwo/license-tool/internal/model" +) + +var ( + paneStyle = lipgloss.NewStyle(). + Border(lipgloss.RoundedBorder()). + BorderForeground(lipgloss.Color("240")) + titleStyle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("15")) + mutedStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("245")) +) + +const footerHints = "tab move | enter edit/commit | esc cancel/back | ctrl+s write | ctrl+c quit" + +// Render produces the full init view for the form, layout plan, chosen preview +// sample, and a now-year for preview year resolution. WHY a pure function: the +// Bubble Tea adapter only forwards window size and keys; everything visible is built +// here and unit-tested, so the adapter shell stays trivial. +func Render(s FormState, plan PanelPlan, sample Sample, nowYear int) string { + if plan.TooSmall { + return tooSmallView() + } + + cfg, _ := Translate(s.answers, TranslateOptions{AllowPlaceholders: true}) + + boxes := make([]string, 0, len(plan.Panels)) + for _, p := range plan.Panels { + var title, content string + switch p.Kind { + case PanelForm: + title, content = "license-tool init", renderForm(s) + case PanelSourcePreview: + title, content = "Source preview", renderSource(cfg, sample, nowYear) + case PanelYAMLPreview: + title, content = ".license-tool.yaml", renderYAML(cfg) + } + boxes = append(boxes, panelBox(p, title, content)) + } + + return joinPanels(plan.Orientation, boxes) + "\n" + footer(s) +} + +func tooSmallView() string { + return "Terminal too small for the init wizard.\n" + + "Widen to at least 60x20, or run non-interactively:\n" + + " license-tool init --license --holder \"\"" +} + +func renderForm(s FormState) string { + invalid := map[Field]bool{} + for _, e := range s.Validate() { + invalid[e.Field] = true + } + + var b strings.Builder + for f := FieldLicense; f <= FieldWrite; f++ { + b.WriteString(renderRow(s, f, invalid[f])) + b.WriteByte('\n') + if s.editing && s.focus == f { + b.WriteString(indentBlock(renderEditor(s))) + b.WriteByte('\n') + } + } + return strings.TrimRight(b.String(), "\n") +} + +func renderRow(s FormState, f Field, invalid bool) string { + marker := " " + if f == s.focus { + marker = "> " + } + if f == FieldWrite { + label := f.Label() + if !s.CanWrite() { + label += " (blocked)" + } + return marker + label + } + + row := marker + f.Label() + ": " + rowValue(s, f) + if detectedBadge(s, f) { + row += " (detected)" + } + if invalid { + row += " !" + } + return row +} + +func rowValue(s FormState, f Field) string { + switch f { + case FieldLicense: + return s.answers.License.SPDXID + case FieldHolder: + return orPlaceholder(s.answers.Identity.Holder, "(required)") + case FieldYear: + return s.answers.Identity.Year + case FieldStyle: + return s.answers.HeaderStyle.Style + case FieldManageFiles: + return yesNo(s.answers.LicenseFiles.Manage) + case FieldInclude: + return listOrAll(s.answers.Coverage.Include) + default: + return listOrNone(s.answers.Coverage.Exclude) + } +} + +func detectedBadge(s FormState, f Field) bool { + switch f { + case FieldLicense: + return s.detected.License + case FieldHolder: + return s.detected.Holder + case FieldManageFiles: + return s.detected.Manage + default: + return false + } +} + +func renderEditor(s FormState) string { + switch s.focus { + case FieldLicense: + return renderLicenseEditor(s) + case FieldStyle: + return renderChoiceEditor(styleOptions, s.styleCursor) + case FieldHolder, FieldYear: + return "> " + s.textBuffer + "_" + default: // FieldInclude, FieldExclude + return renderGlobEditor(s) + } +} + +func renderLicenseEditor(s FormState) string { + choices := s.filteredLicenses() + var b strings.Builder + fmt.Fprintf(&b, "filter: %s\n", orPlaceholder(s.licenseFilter, "(type to filter)")) + if len(choices) == 0 { + b.WriteString("(no matching licenses)") + return b.String() + } + start, end := window(s.licenseCursor, len(choices), 6) + for i := start; i < end; i++ { + b.WriteString(cursorMark(i == s.licenseCursor) + choices[i] + "\n") + } + fmt.Fprintf(&b, "%d/%d", s.licenseCursor+1, len(choices)) + return b.String() +} + +func renderChoiceEditor(options []string, cursor int) string { + var b strings.Builder + for i, opt := range options { + b.WriteString(cursorMark(i == cursor) + opt + "\n") + } + return strings.TrimRight(b.String(), "\n") +} + +func renderGlobEditor(s FormState) string { + entries := s.globEntries() + var b strings.Builder + if len(entries) == 0 { + b.WriteString("(no entries yet)\n") + } + for i, e := range entries { + b.WriteString(cursorMark(i == s.globCursor) + e + "\n") + } + fmt.Fprintf(&b, "add: %s_ (enter to add, d to remove)", s.globBuffer) + return b.String() +} + +func renderSource(cfg model.Config, sample Sample, nowYear int) string { + sp, err := BuildSourcePreview(SourcePreviewInput{ + Config: cfg, + Sample: sample, + ResolvedYear: previewYear(cfg.Year, nowYear), + }) + if err != nil { + return "source preview unavailable: " + err.Error() + } + return fmt.Sprintf("%s %s\n\n%s", sp.Language, sp.Path, sp.Content) +} + +func renderYAML(cfg model.Config) string { + // BuildYAMLPreview wraps config.RenderFile, which is documented total (yaml.Marshal + // of the fixed schema cannot fail for a real Config), so the error is unreachable + // for any cfg this view can produce and is intentionally not branched on. + y, _ := BuildYAMLPreview(cfg) + return strings.TrimRight(string(y), "\n") +} + +func previewYear(y model.YearSpec, nowYear int) string { + switch y.Kind { + case model.YearCurrent: + return fmt.Sprintf("%d", nowYear) + case model.YearExplicit: + if y.Start > 0 { + return fmt.Sprintf("%d", y.Start) + } + case model.YearRange: + if y.Start > 0 && y.End > 0 { + return fmt.Sprintf("%d-%d", y.Start, y.End) + } + } + return fmt.Sprintf("2021-%d", nowYear) +} + +func footer(s FormState) string { + status := "ready to write" + if r := s.BlockingReason(); r != "" { + status = "cannot write: " + r + } + return mutedStyle.Render(footerHints) + "\n" + mutedStyle.Render(status) +} + +func panelBox(p Panel, title, content string) string { + // The rounded border adds one column/row on each side, so the text area is + // p.Width-2 by p.Height-2. Content is pre-fit to exactly that width so lipgloss + // never re-wraps an already-truncated line. + w := maxInt(1, p.Width-2) + h := maxInt(1, p.Height-2) + body := titleStyle.Render(title) + "\n" + fitBlock(content, w, maxInt(1, h-1)) + return paneStyle.Width(w).Height(h).Render(body) +} + +func joinPanels(orientation Orientation, boxes []string) string { + if orientation == LayoutStacked { + return lipgloss.JoinVertical(lipgloss.Left, boxes...) + } + spaced := make([]string, 0, len(boxes)*2) + for i, b := range boxes { + if i > 0 { + spaced = append(spaced, " ") + } + spaced = append(spaced, b) + } + return lipgloss.JoinHorizontal(lipgloss.Top, spaced...) +} + +func cursorMark(selected bool) string { + if selected { + return "> " + } + return " " +} + +func orPlaceholder(value, placeholder string) string { + if strings.TrimSpace(value) == "" { + return placeholder + } + return value +} + +func yesNo(v bool) string { + if v { + return "yes" + } + return "no" +} + +func listOrAll(values []string) string { + if len(values) == 0 { + return "all supported files" + } + return strings.Join(values, ", ") +} + +func listOrNone(values []string) string { + if len(values) == 0 { + return "none" + } + return strings.Join(values, ", ") +} + +func indentBlock(text string) string { + lines := strings.Split(text, "\n") + for i, l := range lines { + lines[i] = " " + l + } + return strings.Join(lines, "\n") +} + +func window(cursor, total, rows int) (start, end int) { + if total <= rows { + return 0, total + } + start = cursor - rows/2 + if start < 0 { + start = 0 + } + if start+rows > total { + start = total - rows + } + return start, start + rows +} + +func fitBlock(text string, width, height int) string { + if width <= 0 || height <= 0 { + return "" + } + raw := strings.Split(text, "\n") + lines := make([]string, 0, height) + for _, line := range raw { + lines = append(lines, truncateLine(line, width)) + if len(lines) == height { + break + } + } + if len(raw) > height { + lines[height-1] = truncateLine("...", width) + } + return strings.Join(lines, "\n") +} + +func truncateLine(line string, width int) string { + r := []rune(line) + if len(r) <= width { + return line + } + if width <= 3 { + return string(r[:width]) + } + return string(r[:width-3]) + "..." +} + +func maxInt(a, b int) int { + if a > b { + return a + } + return b +} diff --git a/internal/initwizard/view_test.go b/internal/initwizard/view_test.go new file mode 100644 index 0000000..2bedc40 --- /dev/null +++ b/internal/initwizard/view_test.go @@ -0,0 +1,151 @@ +package initwizard + +import ( + "strings" + "testing" + + "github.com/KofTwentyTwo/license-tool/internal/model" + "github.com/stretchr/testify/assert" +) + +func cSample() Sample { return SelectSample(nil) } + +func TestRenderTooSmall(t *testing.T) { + out := Render(validForm(), PanelPlan{TooSmall: true}, cSample(), 2026) + assert.Contains(t, out, "Terminal too small") + assert.Contains(t, out, "--license") +} + +func TestRenderWideShowsAllPanels(t *testing.T) { + s := NewForm(Answers{ + License: LicenseAnswer{SPDXID: "MIT"}, + Identity: IdentityAnswer{Holder: "Acme, LLC", Year: "git"}, + Coverage: CoverageAnswer{Include: []string{"src/**"}, Exclude: []string{"**/vendor/**"}}, + }, Detected{}) + out := Render(s, Layout(140, 40), cSample(), 2026) + + assert.Contains(t, out, "license-tool init") + assert.Contains(t, out, "License") + assert.Contains(t, out, "MIT") + assert.Contains(t, out, "Acme, LLC") + assert.Contains(t, out, "src/**") // include row (listOrAll non-empty) + assert.Contains(t, out, "**/vendor/**") // exclude row (listOrNone non-empty) + assert.Contains(t, out, "Source preview") + assert.Contains(t, out, "stdio") // C sample body + assert.Contains(t, out, "license: MIT") // YAML preview + assert.Contains(t, out, "ready to write") // footer, valid form +} + +func TestRenderListPlaceholders(t *testing.T) { + out := Render(validForm(), Layout(140, 40), cSample(), 2026) + assert.Contains(t, out, "all supported files") // empty include + assert.Contains(t, out, "Manage license files: no") +} + +func TestRenderInvalidFormDisablesWrite(t *testing.T) { + s := NewForm(Answers{License: LicenseAnswer{SPDXID: "MIT"}}, Detected{}) // empty holder + out := Render(s, Layout(140, 40), cSample(), 2026) + assert.Contains(t, out, "(required)") // holder placeholder + assert.Contains(t, out, "(blocked)") // write row disabled + assert.Contains(t, out, "cannot write:") // footer reason +} + +func TestRenderDetectedBadges(t *testing.T) { + s := NewForm(Answers{ + License: LicenseAnswer{SPDXID: "MIT"}, + Identity: IdentityAnswer{Holder: "Acme"}, + }, Detected{License: true, Holder: true, Manage: true}) + out := Render(s, Layout(140, 40), cSample(), 2026) + assert.GreaterOrEqual(t, strings.Count(out, "(detected)"), 3) +} + +func TestRenderEditors(t *testing.T) { + open := func(f Field, mutate func(*FormState)) string { + s := validForm() + s.focus = f + s.Activate() + if mutate != nil { + mutate(&s) + } + return Render(s, Layout(140, 40), cSample(), 2026) + } + + assert.Contains(t, open(FieldLicense, nil), "filter:") + assert.Contains(t, open(FieldStyle, nil), "reuse+notice") + assert.Contains(t, open(FieldHolder, nil), "Acme, LLC_") + assert.Contains(t, open(FieldInclude, nil), "(no entries yet)") + assert.Contains(t, open(FieldInclude, func(s *FormState) { + s.globBuffer = "src/**" + s.Commit() + }), "add:") + + noMatch := open(FieldLicense, func(s *FormState) { + for _, r := range "zzzz" { + s.Input(r) + } + }) + assert.Contains(t, noMatch, "no matching licenses") +} + +func TestRenderSourceUnavailable(t *testing.T) { + s := NewForm(Answers{ + License: LicenseAnswer{SPDXID: "Glide"}, // valid SPDX id, not renderable + Identity: IdentityAnswer{Holder: "Acme"}, + }, Detected{}) + out := Render(s, Layout(140, 40), cSample(), 2026) + assert.Contains(t, out, "source preview unavailable") +} + +func TestRenderStacked(t *testing.T) { + out := Render(validForm(), Layout(70, 24), cSample(), 2026) + assert.Contains(t, out, "license-tool init") + assert.Contains(t, out, "Source preview") +} + +func TestPreviewYear(t *testing.T) { + assert.Equal(t, "2026", previewYear(model.YearSpec{Kind: model.YearCurrent}, 2026)) + assert.Equal(t, "2030", previewYear(model.YearSpec{Kind: model.YearExplicit, Start: 2030}, 2026)) + assert.Equal(t, "2021-2026", previewYear(model.YearSpec{Kind: model.YearExplicit}, 2026)) // Start==0 fallback + assert.Equal(t, "2020-2025", previewYear(model.YearSpec{Kind: model.YearRange, Start: 2020, End: 2025}, 2026)) + assert.Equal(t, "2021-2026", previewYear(model.YearSpec{Kind: model.YearRange}, 2026)) // incomplete fallback + assert.Equal(t, "2021-2026", previewYear(model.YearSpec{Kind: model.YearGit}, 2026)) // git/default +} + +func TestSmallViewHelpers(t *testing.T) { + assert.Equal(t, "> ", cursorMark(true)) + assert.Equal(t, " ", cursorMark(false)) + assert.Equal(t, "fallback", orPlaceholder(" ", "fallback")) + assert.Equal(t, "value", orPlaceholder("value", "fallback")) + assert.Equal(t, "yes", yesNo(true)) + assert.Equal(t, "no", yesNo(false)) + assert.Equal(t, "all supported files", listOrAll(nil)) + assert.Equal(t, "a, b", listOrAll([]string{"a", "b"})) + assert.Equal(t, "none", listOrNone(nil)) + assert.Equal(t, "x", listOrNone([]string{"x"})) + assert.Equal(t, " a\n b", indentBlock("a\nb")) + assert.Equal(t, 5, maxInt(5, 1)) + assert.Equal(t, 5, maxInt(1, 5)) +} + +func TestWindow(t *testing.T) { + s, e := window(0, 3, 6) + assert.Equal(t, [2]int{0, 3}, [2]int{s, e}) // total <= rows + + s, e = window(0, 20, 6) + assert.Equal(t, [2]int{0, 6}, [2]int{s, e}) // start clamped to 0 + + s, e = window(19, 20, 6) + assert.Equal(t, [2]int{14, 20}, [2]int{s, e}) // start+rows > total +} + +func TestFitBlockAndTruncate(t *testing.T) { + assert.Equal(t, "", fitBlock("x", 0, 5)) + assert.Equal(t, "", fitBlock("x", 5, 0)) + + got := fitBlock("a\nb\nc\nd", 10, 2) + assert.Equal(t, "a\n...", got) // overflow replaces last visible line + + assert.Equal(t, "ab", truncateLine("ab", 10)) // fits + assert.Equal(t, "ab", truncateLine("abcdef", 2)) // width <= 3 + assert.Equal(t, "a...", truncateLine("abcdef", 4)) +} -- 2.54.0 From 0031b00eb39a2c03fa8f552f39400cc29bdc7c6e Mon Sep 17 00:00:00 2001 From: James Maes Date: Mon, 8 Jun 2026 12:33:49 -0500 Subject: [PATCH 13/14] feat(#29): single-form init wizard with adaptive live preview Replaces the 7-step 3-pane wizard with a single repo-seeded form and a persistent adaptive preview. wizard.go is now a thin Bubble Tea adapter; all logic lives in internal/initwizard at 100% coverage. Closes #29 --- .testcoverage.yml | 13 +- DEVELOPERS.md | 2 +- README.md | 15 +- cmd/license-tool/commands.go | 1 - cmd/license-tool/commands_test.go | 11 - cmd/license-tool/wizard.go | 939 +++--------------------------- docs/SESSION-STATE.md | 13 +- internal/initwizard/form.go | 8 + internal/initwizard/model.go | 57 +- internal/initwizard/view.go | 2 +- 10 files changed, 123 insertions(+), 938 deletions(-) diff --git a/.testcoverage.yml b/.testcoverage.yml index 29ca3b6..4918937 100644 --- a/.testcoverage.yml +++ b/.testcoverage.yml @@ -34,12 +34,13 @@ threshold: # and defense-in-depth. It is not part of the shipped binary. # # 3. cmd/license-tool/wizard.go -# The interactive init wizard is a Bubble Tea terminal shell: it renders panels, -# binds answers, and runs the terminal event loop. Like the main() shim, it has -# no write-path validation of its own; answersToConfig, config, spdx, and -# internal/initwizard carry the covered behavior. Driving a real TUI requires an -# interactive PTY that an in-process unit test cannot provide, so it is excluded -# for the same reason as main.go. +# The interactive init wizard is a thin Bubble Tea adapter: it forwards window +# sizes and keystrokes to internal/initwizard FormState transitions and renders +# via initwizard.Render. It holds no logic of its own; the state machine, +# validation, layout, rendering, repo-seeding, and the single Answers->Config +# translation all live in internal/initwizard and are unit-tested to 100%. +# Driving a real TUI requires an interactive PTY that an in-process unit test +# cannot provide, so the adapter shell is excluded for the same reason as main.go. exclude: paths: - ^cmd/license-tool/main\.go$ diff --git a/DEVELOPERS.md b/DEVELOPERS.md index 5aa7011..e734939 100644 --- a/DEVELOPERS.md +++ b/DEVELOPERS.md @@ -2,6 +2,6 @@ Use feature branches for normal work, merge through `develop`, and promote only green, release-ready commits to `main`. The required local quality gate is the same shape as CI: `gofmt -l .`, `go vet ./...`, `golangci-lint run`, race-enabled tests with `cover.out`, the configured 100% coverage checker, and `go build ./...`. -The interactive `init` wizard keeps terminal rendering in `cmd/license-tool/wizard.go`. Covered behavior belongs in `answersToConfig`, `internal/config`, and `internal/initwizard`; the TUI shell should stay thin and delegate preview rendering to the pure initwizard helpers. +The interactive `init` wizard is a thin Bubble Tea adapter in `cmd/license-tool/wizard.go` (excluded from coverage). All behavior — the form state machine, live validation, adaptive layout, view rendering, repo detection (`Seed`), and the single `Translate` from answers to config — lives in `internal/initwizard` and is unit-tested to 100%. Keep the adapter logic-free: forward keystrokes to `FormState` transitions and render via `initwizard.Render`. There is exactly one `Answers`->`Config` translator (`initwizard.Translate`); do not reintroduce a second one for the preview. Releases are documented in [RELEASING.md](RELEASING.md). In short: update [CHANGELOG.md](CHANGELOG.md), run `./scripts/verify-release.sh`, commit the release notes with a conventional commit, push `main`, wait for CI and CodeQL, then push a signed semver tag such as `v0.3.0`. The tag triggers GoReleaser, which creates the GitHub Release and publishes the Homebrew cask. diff --git a/README.md b/README.md index de5ceda..800d381 100644 --- a/README.md +++ b/README.md @@ -115,11 +115,16 @@ license-tool license --license AGPL-3.0-or-later --holder "Kingsrook, LLC" --wri ### init Scaffold a `.license-tool.yaml` for the repo. On a TTY, `init` opens a -full-screen wizard with a progress rail, active controls, and a live preview -panel. The preview renders the current answers onto an example source file, -shows the YAML that will be written, summarizes license-file behavior, and shows -include/exclude scope. The example source is chosen from supported language -families detected in the repo, with C as the fallback. +single-screen form pre-filled from repo detection (existing headers, a top-level +`LICENSE`, and the git author seed the license, holder, and manage choices, each +badged `(detected)` and fully editable). Every field is visible and editable in +any order; complex fields (the searchable license picker and the include/exclude +glob lists) expand inline. A persistent live preview re-renders on every edit and +adapts to terminal width: the example source file with the generated header, the +YAML to be written, both side by side when wide, stacked when narrow. The example +source is chosen from supported language families detected in the repo, with C as +the fallback. Validation is live; the write action stays disabled until every +field is valid. Writing over an existing `.license-tool.yaml` asks first. ```bash license-tool init diff --git a/cmd/license-tool/commands.go b/cmd/license-tool/commands.go index 7ad02e3..995b1c4 100644 --- a/cmd/license-tool/commands.go +++ b/cmd/license-tool/commands.go @@ -404,7 +404,6 @@ func newInitCmd(shared *sharedFlags) *cobra.Command { path := argPath(args) out := cmd.OutOrStdout() a := initwizard.Answers{ - Project: initwizard.ProjectAnswer{Model: initwizard.ProjectModelAdvancedManual}, License: initwizard.LicenseAnswer{SPDXID: f.license}, Identity: initwizard.IdentityAnswer{Holder: f.holder, Year: f.year}, HeaderStyle: initwizard.HeaderStyleAnswer{Style: f.style}, diff --git a/cmd/license-tool/commands_test.go b/cmd/license-tool/commands_test.go index a1e628a..8c9f3c4 100644 --- a/cmd/license-tool/commands_test.go +++ b/cmd/license-tool/commands_test.go @@ -1018,14 +1018,6 @@ func TestWriteOrInternalErrorClassifiesUnexpectedErrors(t *testing.T) { assert.Equal(t, exitInternal, exitCode(err)) } -func TestLicenseSelectOptions(t *testing.T) { - opts := licenseSelectOptions() - require.NotEmpty(t, opts, "license picker should offer renderable licenses") - - assert.Contains(t, opts, "MIT") - assert.NotContains(t, opts, "Zlib", "picker must not offer a license the tool cannot render") -} - // TestInitCommandInteractiveCollectError covers the init RunE branch where the // interactiveCollect seam returns an error: the command must propagate it verbatim // and write nothing. The seam is overridden so the failure is deterministic without @@ -1059,7 +1051,6 @@ func TestInitCommandConsumesCollectorAnswers(t *testing.T) { interactiveCollect = func(path string, initial initwizard.Answers, interactive bool) (initwizard.Answers, error) { assert.Equal(t, dir, path) assert.False(t, interactive) - assert.Equal(t, initwizard.ProjectModelAdvancedManual, initial.Project.Model) assert.Equal(t, "MIT", initial.License.SPDXID) assert.Equal(t, "Flag Holder", initial.Identity.Holder) assert.Equal(t, "2026", initial.Identity.Year) @@ -1068,7 +1059,6 @@ func TestInitCommandConsumesCollectorAnswers(t *testing.T) { assert.Equal(t, []string{"vendor/**"}, initial.Coverage.Exclude) return initwizard.Answers{ - Project: initwizard.ProjectAnswer{Model: initwizard.ProjectModelPrivateInternal}, License: initwizard.LicenseAnswer{ SPDXID: "Apache-2.0", }, @@ -1082,7 +1072,6 @@ func TestInitCommandConsumesCollectorAnswers(t *testing.T) { Include: []string{"cmd/**"}, Exclude: []string{"generated/**"}, }, - Review: initwizard.ReviewAnswer{Confirmed: true}, }, nil } diff --git a/cmd/license-tool/wizard.go b/cmd/license-tool/wizard.go index 7af6c96..6f3ccdc 100644 --- a/cmd/license-tool/wizard.go +++ b/cmd/license-tool/wizard.go @@ -6,783 +6,126 @@ import ( "os" "path/filepath" "sort" - "strings" "time" - "github.com/charmbracelet/bubbles/textinput" tea "github.com/charmbracelet/bubbletea" - "github.com/charmbracelet/lipgloss" "github.com/KofTwentyTwo/license-tool/internal/initwizard" - "github.com/KofTwentyTwo/license-tool/internal/model" - "github.com/KofTwentyTwo/license-tool/internal/spdx" ) -var ( - projectModelOptions = []initwizard.ProjectModel{ - initwizard.ProjectModelOpenSource, - initwizard.ProjectModelPrivateInternal, - initwizard.ProjectModelExistingProject, - initwizard.ProjectModelAdvancedManual, - } - headerStyleOptions = []string{"reuse", "notice", "reuse+notice"} - - appTitleStyle = lipgloss.NewStyle(). - Bold(true). - Foreground(lipgloss.Color("15")). - Background(lipgloss.Color("62")). - Padding(0, 1) - paneStyle = lipgloss.NewStyle(). - Border(lipgloss.RoundedBorder()). - BorderForeground(lipgloss.Color("240")). - Padding(0, 1) - activePaneStyle = paneStyle. - BorderForeground(lipgloss.Color("62")) - paneTitleStyle = lipgloss.NewStyle(). - Bold(true). - Foreground(lipgloss.Color("15")) - mutedStyle = lipgloss.NewStyle(). - Foreground(lipgloss.Color("245")) -) - -// licenseSelectOptions builds the license picker values: common renderable SPDX ids -// first, then the remaining renderable ids in sorted order without duplicates. -func licenseSelectOptions() []string { - common := spdx.CommonIDs() - seen := make(map[string]bool, len(common)) - opts := make([]string, 0, len(common)) - for _, id := range common { - seen[id] = true - opts = append(opts, id) - } - for _, id := range spdx.RenderableIDs() { - if seen[id] { - continue - } - opts = append(opts, id) - } - return opts -} - +// initWizardModel is a thin Bubble Tea adapter. WHY it carries no logic: every +// decision (field state, validation, layout, rendering, the single Answers->Config +// translation) lives in the pure, fully-tested internal/initwizard package; this +// shell only forwards window sizes and keystrokes to FormState transitions and +// renders via initwizard.Render. It is excluded from the coverage gate precisely +// because it is this trivial. type initWizardModel struct { - root string - answers initwizard.Answers - step initwizard.Step - input textinput.Model - licenseOptions []string - licenseFilter string - previewPaths []string - projectIndex int - licenseIndex int - styleIndex int - width int - height int + form initwizard.FormState + sample initwizard.Sample + nowYear int + width int + height int + confirmed bool } -func newInitWizardModel(root string, answers initwizard.Answers) initWizardModel { - m := initWizardModel{ - root: root, - answers: answers, - step: initwizard.StepProjectModel, - licenseOptions: licenseSelectOptions(), - previewPaths: previewCandidatePaths(root), +func newInitWizardModel(root string, a initwizard.Answers) initWizardModel { + seeded, detected := initwizard.Seed(root, a, initwizard.SeedDeps{}) + return initWizardModel{ + form: initwizard.NewForm(seeded, detected), + sample: initwizard.SelectSample(previewCandidatePaths(root)), + nowYear: time.Now().Year(), } - if m.answers.Project.Model == "" { - m.answers.Project.Model = initwizard.ProjectModelOpenSource - } - if m.answers.License.SPDXID == "" && len(m.licenseOptions) > 0 { - m.answers.License.SPDXID = m.licenseOptions[0] - } - if m.answers.Identity.Year == "" { - m.answers.Identity.Year = "git" - } - if m.answers.HeaderStyle.Style == "" { - m.answers.HeaderStyle.Style = "reuse+notice" - } - m.projectIndex = indexProjectModel(projectModelOptions, m.answers.Project.Model) - m.licenseIndex = indexString(m.licenseOptions, m.answers.License.SPDXID) - if len(m.licenseOptions) > 0 && m.answers.License.SPDXID != m.licenseOptions[m.licenseIndex] { - m.answers.License.SPDXID = m.licenseOptions[m.licenseIndex] - } - m.styleIndex = indexString(headerStyleOptions, m.answers.HeaderStyle.Style) - m.setInput() - return m } -func indexProjectModel(values []initwizard.ProjectModel, value initwizard.ProjectModel) int { - for i, item := range values { - if item == value { - return i - } - } - return 0 -} - -func indexString(values []string, value string) int { - for i, item := range values { - if item == value { - return i - } - } - return 0 -} - -func (m initWizardModel) Init() tea.Cmd { - return textinput.Blink -} +func (m initWizardModel) Init() tea.Cmd { return nil } func (m initWizardModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case tea.WindowSizeMsg: - m.width = msg.Width - m.height = msg.Height - m.input.Width = m.inputWidth() + m.width, m.height = msg.Width, msg.Height return m, nil case tea.KeyMsg: - if m.step == initwizard.StepLicense { - if m.handleLicenseKey(msg) { - return m, nil - } - } - switch msg.String() { - case "ctrl+c", "esc": - m.answers.Review.Confirmed = false + return m.handleKey(msg) + } + return m, nil +} + +func (m initWizardModel) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + switch msg.Type { + case tea.KeyCtrlC: + return m, tea.Quit + case tea.KeyCtrlS: + if m.form.CanWrite() { + m.confirmed = true return m, tea.Quit - case "up", "k": - m.moveSelection(-1) - return m, nil - case "down", "j": - m.moveSelection(1) - return m, nil - case "pgup": - m.moveSelection(-10) - return m, nil - case "pgdown": - m.moveSelection(10) - return m, nil - case "home": - m.moveSelectionToStart() - return m, nil - case "end": - m.moveSelectionToEnd() - return m, nil - case " ", "y", "n": - if m.step == initwizard.StepLicenseFiles { - m.toggleBool(msg.String()) - return m, nil - } - case "backspace": - if !m.usesTextInput() && m.step > initwizard.StepProjectModel { - m.step-- - m.setInput() - return m, nil - } - case "enter": - if m.step == initwizard.StepLicense && len(m.filteredLicenseChoices()) == 0 { - return m, nil - } - m.commitInput() - if m.step == initwizard.StepReview { - m.answers.Review.Confirmed = true - return m, tea.Quit - } - m.step++ - m.setInput() - return m, nil + } + return m, nil + } + + if m.form.Editing() { + return m.handleEditingKey(msg) + } + return m.handleNavKey(msg) +} + +func (m initWizardModel) handleEditingKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + switch msg.Type { + case tea.KeyEsc: + m.form.Cancel() + case tea.KeyEnter: + m.form.Commit() + case tea.KeyUp: + m.form.MoveCursor(-1) + case tea.KeyDown: + m.form.MoveCursor(1) + case tea.KeyDelete: + m.form.Remove() + case tea.KeyBackspace: + m.form.Backspace() + case tea.KeyRunes, tea.KeySpace: + for _, r := range msg.Runes { + m.form.Input(r) } } - if m.usesTextInput() { - var cmd tea.Cmd - m.input, cmd = m.input.Update(msg) - return m, cmd + return m, nil +} + +func (m initWizardModel) handleNavKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + switch msg.Type { + case tea.KeyEsc: + if m.form.Cancel() == initwizard.ActionQuit { + return m, tea.Quit + } + case tea.KeyEnter, tea.KeySpace: + if m.form.Activate() == initwizard.ActionWrite { + m.confirmed = true + return m, tea.Quit + } + case tea.KeyUp: + m.form.MoveFocus(-1) + case tea.KeyDown, tea.KeyTab: + m.form.MoveFocus(1) + case tea.KeyShiftTab: + m.form.MoveFocus(-1) } return m, nil } func (m initWizardModel) View() string { - width := m.width + width, height := m.width, m.height if width <= 0 { width = 120 } - height := m.height if height <= 0 { height = 34 } - - header := m.headerView(width) - footer := m.footerView(width) - bodyHeight := height - lipgloss.Height(header) - lipgloss.Height(footer) - 2 - if bodyHeight < 14 { - bodyHeight = 14 - } - - return strings.TrimRight(lipgloss.JoinVertical( - lipgloss.Left, - header, - m.bodyView(width, bodyHeight), - footer, - ), "\n") -} - -func (m initWizardModel) stepTitle() string { - return stepTitle(m.step) -} - -func stepTitle(step initwizard.Step) string { - switch step { - case initwizard.StepProjectModel: - return "Project model" - case initwizard.StepLicense: - return "License" - case initwizard.StepIdentity: - return "Identity" - case initwizard.StepHeaderStyle: - return "Header style" - case initwizard.StepLicenseFiles: - return "License files" - case initwizard.StepCoverage: - return "Coverage" - default: - return "Review" - } -} - -func (m initWizardModel) headerView(width int) string { - title := "license-tool init" - if m.root != "" { - title += " " + m.root - } - return appTitleStyle.Width(maxInt(1, width-2)).Render(title) -} - -func (m initWizardModel) footerView(width int) string { - keys := "enter next" - if m.step == initwizard.StepReview { - keys = "enter write" - } - keys += " | back back | esc cancel | arrows/pg move" - if m.step == initwizard.StepLicense { - keys += " | type filter | ctrl+u clear" - } - return mutedStyle.Width(width).Render(keys) -} - -func (m initWizardModel) bodyView(width int, height int) string { - if width < 100 { - topHeight := height / 2 - if height >= 18 && topHeight < 11 { - topHeight = 11 - } - if height < 18 && topHeight < 7 { - topHeight = 7 - } - if topHeight > height-7 { - topHeight = height - 7 - } - if topHeight < 6 { - topHeight = 6 - } - previewHeight := height - topHeight - 1 - if previewHeight < 6 { - previewHeight = 6 - topHeight = maxInt(6, height-previewHeight-1) - } - navWidth := 22 - if width < 70 { - navWidth = 18 - } - controlWidth := maxInt(24, width-navWidth-1) - top := lipgloss.JoinHorizontal( - lipgloss.Top, - m.renderPane("Steps", m.navigationBody(), navWidth, topHeight, false), - " ", - m.renderPane(m.stepTitle(), m.stepBody(topHeight-3), controlWidth, topHeight, true), - ) - return lipgloss.JoinVertical( - lipgloss.Left, - top, - m.renderPane("Live preview", m.previewSummary(), width, previewHeight, false), - ) - } - - gutter := 1 - navWidth := 24 - previewWidth := width / 2 - if previewWidth < 46 { - previewWidth = 46 - } - if previewWidth > 72 { - previewWidth = 72 - } - controlWidth := width - navWidth - previewWidth - gutter*2 - if controlWidth < 34 { - controlWidth = 34 - previewWidth = width - navWidth - controlWidth - gutter*2 - } - - return lipgloss.JoinHorizontal( - lipgloss.Top, - m.renderPane("Steps", m.navigationBody(), navWidth, height, false), - strings.Repeat(" ", gutter), - m.renderPane(m.stepTitle(), m.stepBody(height-3), controlWidth, height, true), - strings.Repeat(" ", gutter), - m.renderPane("Live preview", m.previewSummary(), previewWidth, height, false), - ) -} - -func (m initWizardModel) renderPane(title string, content string, width int, height int, active bool) string { - if width < 12 { - width = 12 - } - if height < 6 { - height = 6 - } - innerWidth := maxInt(1, width-4) - innerHeight := maxInt(1, height-2) - body := paneTitleStyle.Render(title) + "\n" + fitText(content, innerWidth, innerHeight-1) - style := paneStyle - if active { - style = activePaneStyle - } - return style.Width(innerWidth).Height(innerHeight).Render(body) -} - -func (m initWizardModel) stepBody(rows int) string { - switch m.step { - case initwizard.StepProjectModel: - return selectionList(projectModelsToStrings(projectModelOptions), m.projectIndex, rows) - case initwizard.StepLicense: - return m.licenseBody(rows) - case initwizard.StepIdentity: - return strings.Join([]string{ - "Copyright holder and year policy", - "", - m.input.View(), - "", - "Format: holder | year", - "Year accepts current, git, YYYY, or YYYY-YYYY.", - }, "\n") - case initwizard.StepHeaderStyle: - return selectionList(headerStyleOptions, m.styleIndex, rows) - case initwizard.StepLicenseFiles: - if m.answers.LicenseFiles.Manage { - return "Manage LICENSE and LICENSES/.txt\n\nCurrent value: yes\n\nPress space, y, or n to change." - } - return "Manage LICENSE and LICENSES/.txt\n\nCurrent value: no\n\nPress space, y, or n to change." - case initwizard.StepCoverage: - return strings.Join([]string{ - "Default file scope", - "", - m.input.View(), - "", - "Format: include globs | exclude globs", - "Examples: src/** | **/generated/**, vendor/**", - "Leave include empty to scan all supported files.", - }, "\n") - default: - return m.reviewBody() - } -} - -func (m initWizardModel) navigationBody() string { - steps := []initwizard.Step{ - initwizard.StepProjectModel, - initwizard.StepLicense, - initwizard.StepIdentity, - initwizard.StepHeaderStyle, - initwizard.StepLicenseFiles, - initwizard.StepCoverage, - initwizard.StepReview, - } - var b strings.Builder - fmt.Fprintf(&b, "Step %d/%d\n", int(m.step)+1, len(steps)) - for _, step := range steps { - mark := " " - if step < m.step { - mark = "x " - } - if step == m.step { - mark = "> " - } - fmt.Fprintf(&b, "%s%s\n", mark, stepTitle(step)) - } - return strings.TrimRight(b.String(), "\n") -} - -func projectModelsToStrings(values []initwizard.ProjectModel) []string { - out := make([]string, 0, len(values)) - for _, value := range values { - out = append(out, string(value)) - } - return out -} - -func selectionList(values []string, selected int, rows int) string { - if rows < 4 { - rows = 4 - } - visibleRows := rows - 2 - start := windowStart(selected, len(values), visibleRows) - var b strings.Builder - fmt.Fprintf(&b, "%-4s %s\n", "Sel", "Value") - fmt.Fprintf(&b, "%-4s %s\n", "---", "-----") - for i := start; i < len(values) && i < start+visibleRows; i++ { - prefix := " " - if i == selected { - prefix = "> " - } - fmt.Fprintf(&b, "%-4s %s\n", prefix, values[i]) - } - if len(values) > visibleRows { - fmt.Fprintf(&b, "\n%d/%d", selected+1, len(values)) - } - return strings.TrimRight(b.String(), "\n") -} - -func (m initWizardModel) licenseBody(rows int) string { - choices := m.filteredLicenseChoices() - filter := m.licenseFilter - if filter == "" { - filter = "(none)" - } - var b strings.Builder - fmt.Fprintf(&b, "Filter: %s Selected: %s\n", filter, m.answers.License.SPDXID) - if len(choices) == 0 { - b.WriteString("No matching renderable licenses.\n\nBackspace or ctrl+u to change the filter.") - return b.String() - } - - selectedPos := m.licenseChoicePosition(choices) - visibleRows := rows - 4 - if visibleRows < 4 { - visibleRows = 4 - } - start := windowStart(selectedPos, len(choices), visibleRows) - fmt.Fprintf(&b, "%-4s %-24s %s\n", "Sel", "SPDX id", "Group") - fmt.Fprintf(&b, "%-4s %-24s %s\n", "---", "-------", "-----") - for pos := start; pos < len(choices) && pos < start+visibleRows; pos++ { - choice := choices[pos] - mark := " " - if choice.index == m.licenseIndex { - mark = "> " - } - group := "other" - if isCommonLicense(choice.id) { - group = "common" - } - fmt.Fprintf(&b, "%-4s %-24s %s\n", mark, choice.id, group) - } - fmt.Fprintf(&b, "\n%d/%d matches, %d renderable total", selectedPos+1, len(choices), len(m.licenseOptions)) - return strings.TrimRight(b.String(), "\n") -} - -func (m initWizardModel) reviewBody() string { - rows := [][2]string{ - {"Project model", string(m.answers.Project.Model)}, - {"License", m.answers.License.SPDXID}, - {"Holder", valueOrPlaceholder(m.answers.Identity.Holder, "(required)")}, - {"Year", valueOrPlaceholder(m.answers.Identity.Year, "git")}, - {"Header style", m.answers.HeaderStyle.Style}, - {"Manage license files", yesNo(m.answers.LicenseFiles.Manage)}, - {"Include", listOrAll(m.answers.Coverage.Include)}, - {"Exclude", listOrNone(m.answers.Coverage.Exclude)}, - } - var b strings.Builder - fmt.Fprintf(&b, "%-22s %s\n", "Field", "Value") - fmt.Fprintf(&b, "%-22s %s\n", "-----", "-----") - for _, row := range rows { - fmt.Fprintf(&b, "%-22s %s\n", row[0], row[1]) - } - b.WriteString("\nPress enter to write .license-tool.yaml.") - return strings.TrimRight(b.String(), "\n") -} - -func (m initWizardModel) previewSummary() string { - cfg, _ := initwizard.Translate(m.answers, initwizard.TranslateOptions{AllowPlaceholders: true}) - sample := initwizard.SelectSample(m.previewPaths) - sourcePreview, sourceErr := initwizard.BuildSourcePreview(initwizard.SourcePreviewInput{ - Config: cfg, - Sample: sample, - ResolvedYear: previewResolvedYear(cfg.Year), - }) - yamlPreview, yamlErr := initwizard.BuildYAMLPreview(cfg) - - var b strings.Builder - if sourceErr == nil { - fmt.Fprintf(&b, "%s %s\n\n", sourcePreview.Language, sourcePreview.Path) - b.WriteString(sourcePreview.Content) - } else { - fmt.Fprintf(&b, "Source preview unavailable: %s\n", sourceErr) - } - if yamlErr == nil { - fmt.Fprintf(&b, "\n\n.license-tool.yaml\n\n%s", strings.TrimRight(string(yamlPreview), "\n")) - } else { - fmt.Fprintf(&b, "\n\nYAML preview unavailable: %s", yamlErr) - } - fmt.Fprintf(&b, "\n\nLicense files: %s", yesNo(cfg.ManageLicenseFile)) - fmt.Fprintf(&b, "\nCoverage include: %s", listOrAll(cfg.Includes)) - fmt.Fprintf(&b, "\nCoverage exclude: %s", listOrNone(cfg.Excludes)) - return strings.TrimRight(b.String(), "\n") -} - -func yesNo(v bool) string { - if v { - return "yes" - } - return "no" -} - -func (m *initWizardModel) handleLicenseKey(msg tea.KeyMsg) bool { - switch msg.Type { - case tea.KeyRunes: - m.licenseFilter += string(msg.Runes) - m.alignLicenseSelection() - return true - case tea.KeyBackspace: - if m.licenseFilter == "" { - return false - } - runes := []rune(m.licenseFilter) - m.licenseFilter = string(runes[:len(runes)-1]) - m.alignLicenseSelection() - return true - } - switch msg.String() { - case "ctrl+u": - m.licenseFilter = "" - m.alignLicenseSelection() - return true - case "up", "k": - m.moveSelection(-1) - return true - case "down", "j": - m.moveSelection(1) - return true - case "pgup": - m.moveSelection(-10) - return true - case "pgdown": - m.moveSelection(10) - return true - case "home": - m.moveSelectionToStart() - return true - case "end": - m.moveSelectionToEnd() - return true - } - return false -} - -func (m *initWizardModel) moveSelection(delta int) { - switch m.step { - case initwizard.StepProjectModel: - m.projectIndex = wrapIndex(m.projectIndex+delta, len(projectModelOptions)) - m.answers.Project.Model = projectModelOptions[m.projectIndex] - case initwizard.StepLicense: - choices := m.filteredLicenseChoices() - if len(choices) == 0 { - return - } - pos := clampInt(m.licenseChoicePosition(choices)+delta, 0, len(choices)-1) - m.licenseIndex = choices[pos].index - m.answers.License.SPDXID = choices[pos].id - case initwizard.StepHeaderStyle: - m.styleIndex = wrapIndex(m.styleIndex+delta, len(headerStyleOptions)) - m.answers.HeaderStyle.Style = headerStyleOptions[m.styleIndex] - } -} - -func (m *initWizardModel) moveSelectionToStart() { - switch m.step { - case initwizard.StepProjectModel: - m.projectIndex = 0 - m.answers.Project.Model = projectModelOptions[m.projectIndex] - case initwizard.StepLicense: - choices := m.filteredLicenseChoices() - if len(choices) == 0 { - return - } - m.licenseIndex = choices[0].index - m.answers.License.SPDXID = choices[0].id - case initwizard.StepHeaderStyle: - m.styleIndex = 0 - m.answers.HeaderStyle.Style = headerStyleOptions[m.styleIndex] - } -} - -func (m *initWizardModel) moveSelectionToEnd() { - switch m.step { - case initwizard.StepProjectModel: - m.projectIndex = len(projectModelOptions) - 1 - m.answers.Project.Model = projectModelOptions[m.projectIndex] - case initwizard.StepLicense: - choices := m.filteredLicenseChoices() - if len(choices) == 0 { - return - } - last := choices[len(choices)-1] - m.licenseIndex = last.index - m.answers.License.SPDXID = last.id - case initwizard.StepHeaderStyle: - m.styleIndex = len(headerStyleOptions) - 1 - m.answers.HeaderStyle.Style = headerStyleOptions[m.styleIndex] - } -} - -type licenseChoice struct { - index int - id string -} - -func (m initWizardModel) filteredLicenseChoices() []licenseChoice { - filter := strings.ToLower(strings.TrimSpace(m.licenseFilter)) - choices := make([]licenseChoice, 0, len(m.licenseOptions)) - for i, id := range m.licenseOptions { - if filter != "" && !strings.Contains(strings.ToLower(id), filter) { - continue - } - choices = append(choices, licenseChoice{index: i, id: id}) - } - return choices -} - -func (m initWizardModel) licenseChoicePosition(choices []licenseChoice) int { - for i, choice := range choices { - if choice.index == m.licenseIndex { - return i - } - } - return 0 -} - -func (m *initWizardModel) alignLicenseSelection() { - choices := m.filteredLicenseChoices() - if len(choices) == 0 { - return - } - for _, choice := range choices { - if choice.index == m.licenseIndex { - m.answers.License.SPDXID = choice.id - return - } - } - m.licenseIndex = choices[0].index - m.answers.License.SPDXID = choices[0].id -} - -func isCommonLicense(id string) bool { - for _, common := range spdx.CommonIDs() { - if common == id { - return true - } - } - return false -} - -func wrapIndex(value, size int) int { - if size == 0 { - return 0 - } - for value < 0 { - value += size - } - return value % size -} - -func (m *initWizardModel) toggleBool(key string) { - if m.step != initwizard.StepLicenseFiles { - return - } - switch key { - case "y": - m.answers.LicenseFiles.Manage = true - case "n": - m.answers.LicenseFiles.Manage = false - default: - m.answers.LicenseFiles.Manage = !m.answers.LicenseFiles.Manage - } -} - -func (m initWizardModel) usesTextInput() bool { - return m.step == initwizard.StepIdentity || m.step == initwizard.StepCoverage -} - -func (m *initWizardModel) setInput() { - ti := textinput.New() - ti.Width = m.inputWidth() - switch m.step { - case initwizard.StepIdentity: - ti.Placeholder = "holder | year, for example Acme, LLC | git" - ti.SetValue(strings.TrimSpace(m.answers.Identity.Holder + " | " + m.answers.Identity.Year)) - ti.Focus() - case initwizard.StepCoverage: - ti.Placeholder = "include globs | exclude globs" - ti.SetValue(coverageInputValue(m.answers.Coverage)) - ti.Focus() - } - m.input = ti -} - -func (m *initWizardModel) commitInput() { - switch m.step { - case initwizard.StepIdentity: - holder, year, ok := strings.Cut(m.input.Value(), "|") - if ok { - m.answers.Identity.Holder = strings.TrimSpace(holder) - m.answers.Identity.Year = strings.TrimSpace(year) - return - } - m.answers.Identity.Holder = strings.TrimSpace(m.input.Value()) - case initwizard.StepCoverage: - include, exclude, hasSeparator := strings.Cut(m.input.Value(), "|") - if hasSeparator { - m.answers.Coverage.Include = splitCSV(include) - m.answers.Coverage.Exclude = splitCSV(exclude) - return - } - m.answers.Coverage.Include = splitCSV(m.input.Value()) - m.answers.Coverage.Exclude = nil - } -} - -func coverageInputValue(a initwizard.CoverageAnswer) string { - include := strings.Join(a.Include, ", ") - exclude := strings.Join(a.Exclude, ", ") - if include == "" && exclude == "" { - return "" - } - return include + " | " + exclude -} - -func splitCSV(raw string) []string { - var out []string - for _, item := range strings.Split(raw, ",") { - item = strings.TrimSpace(item) - if item != "" { - out = append(out, item) - } - } - return out -} - -func previewResolvedYear(y model.YearSpec) string { - current := time.Now().Year() - switch y.Kind { - case model.YearCurrent: - return fmt.Sprintf("%d", current) - case model.YearExplicit: - if y.Start > 0 { - return fmt.Sprintf("%d", y.Start) - } - case model.YearRange: - if y.Start > 0 && y.End > 0 { - return fmt.Sprintf("%d-%d", y.Start, y.End) - } - } - return fmt.Sprintf("2021-%d", current) + // Reserve two rows for the footer that Render appends below the panels. + plan := initwizard.Layout(width, height-2) + return initwizard.Render(m.form, plan, m.sample, m.nowYear) } +// previewCandidatePaths walks root for files whose extension maps to a preview +// sample, so SelectSample can pick a language family present in the repo. func previewCandidatePaths(root string) []string { if root == "" { return nil @@ -821,114 +164,6 @@ func ignoredPreviewDir(name string) bool { } } -func listOrAll(values []string) string { - if len(values) == 0 { - return "all supported files" - } - return strings.Join(values, ", ") -} - -func listOrNone(values []string) string { - if len(values) == 0 { - return "none" - } - return strings.Join(values, ", ") -} - -func valueOrPlaceholder(value string, placeholder string) string { - if strings.TrimSpace(value) == "" { - return placeholder - } - return value -} - -func (m initWizardModel) inputWidth() int { - width := m.width - if width <= 0 { - width = 120 - } - if width < 100 { - return maxInt(20, width-8) - } - previewWidth := width / 2 - if previewWidth < 46 { - previewWidth = 46 - } - if previewWidth > 72 { - previewWidth = 72 - } - controlWidth := width - 24 - previewWidth - 2 - return maxInt(20, controlWidth-8) -} - -func fitText(text string, width int, height int) string { - if width <= 0 || height <= 0 { - return "" - } - raw := strings.Split(text, "\n") - lines := make([]string, 0, minInt(len(raw), height)) - for _, line := range raw { - lines = append(lines, ellipsize(line, width)) - if len(lines) == height { - break - } - } - if len(raw) > height && height > 0 { - lines[height-1] = ellipsize("...", width) - } - return strings.Join(lines, "\n") -} - -func ellipsize(line string, width int) string { - runes := []rune(line) - if len(runes) <= width { - return line - } - if width <= 3 { - return string(runes[:width]) - } - return string(runes[:width-3]) + "..." -} - -func windowStart(selected int, total int, rows int) int { - if total <= rows || rows <= 0 { - return 0 - } - selected = clampInt(selected, 0, total-1) - start := selected - rows/2 - if start < 0 { - return 0 - } - if start+rows > total { - return total - rows - } - return start -} - -func clampInt(value int, minValue int, maxValue int) int { - if value < minValue { - return minValue - } - if value > maxValue { - return maxValue - } - return value -} - -func maxInt(a int, b int) int { - if a > b { - return a - } - return b -} - -func minInt(a int, b int) int { - if a < b { - return a - } - return b -} - func runInitWizard(path string, a initwizard.Answers) (initwizard.Answers, error) { program := tea.NewProgram( newInitWizardModel(path, a), @@ -944,10 +179,10 @@ func runInitWizard(path string, a initwizard.Answers) (initwizard.Answers, error if !ok { return a, fmt.Errorf("init wizard returned unexpected model") } - if !m.answers.Review.Confirmed { + if !m.confirmed { return a, initwizard.ErrAborted } - return m.answers, nil + return m.form.Answers(), nil } // collectInteractive runs the wizard when interactive is true, otherwise returning diff --git a/docs/SESSION-STATE.md b/docs/SESSION-STATE.md index 6d0cd5d..dc2491a 100644 --- a/docs/SESSION-STATE.md +++ b/docs/SESSION-STATE.md @@ -4,15 +4,12 @@ `feature/GH-29-init-tui-wizard` ## Current Objective -Implement GitHub issue #29: redesign `license-tool init` as a full-screen configuration TUI with live example source preview, persisted include/exclude defaults, and 100% test coverage. +Redesign `license-tool init` per `docs/DESIGN-init-tui-redesign.md`: single always-visible, repo-seeded form with an adaptive live preview; all logic in a tested `internal/initwizard`; `wizard.go` a thin Bubble Tea adapter. Plan: `docs/PLAN-GH-29-init-tui-redesign.md`. ## Status -- `v0.3.0` is released. -- Feature branch created from `main` at `7e177a9`. -- Plan created in `docs/PLAN-GH-29-init-tui-wizard.md`. -- Feature-definition and worker slices are integrated into the feature branch. -- The init TUI now uses Bubble Tea with a progress rail, active controls, and live source/YAML preview. -- Include patterns persist through config, CLI flags, collector answers, and written init output. +- Full-codebase review complete: `docs/review/01-03`. Bugs filed: #30, #31, #32 (blocker for #29), #33, #34. +- Task 1 done (commit `4e3561e`): include globs honor `**` via shared `enumerate.CompileMatcher` (#32). +- Task 2 done (commit `bafa281`): single `initwizard.Translate` replaces `answersToConfig` + wizard `previewConfig`; tests moved to `internal/initwizard/translate_test.go`. ## Next Step -Manual TUI review with `/private/tmp/license-tool-gh29` or `go run ./cmd/license-tool init ` before promoting the feature branch. +Task 3: trim dead types (`ProjectModel*`, `Step*`, `ReviewAnswer`, `ProjectAnswer`, `LicenseAnswer.Private`) and add `initwizard.Seed(root, deps)` repo detection. Then Tasks 4-7 (form state machine, layout, view, thin adapter + full gate). NOTE: the current `wizard.go` still references the soon-to-be-removed types; Task 7 rewrites it. diff --git a/internal/initwizard/form.go b/internal/initwizard/form.go index c2e5f0e..da04ec5 100644 --- a/internal/initwizard/form.go +++ b/internal/initwizard/form.go @@ -13,13 +13,21 @@ import ( type Field int const ( + // FieldLicense is the target SPDX license row. FieldLicense Field = iota + // FieldHolder is the copyright holder row. FieldHolder + // FieldYear is the year-policy row. FieldYear + // FieldStyle is the header-style row. FieldStyle + // FieldManageFiles is the manage-license-files toggle row. FieldManageFiles + // FieldInclude is the include-globs list row. FieldInclude + // FieldExclude is the exclude-globs list row. FieldExclude + // FieldWrite is the trailing write-config action row. FieldWrite ) diff --git a/internal/initwizard/model.go b/internal/initwizard/model.go index cfdfd4b..885cdd6 100644 --- a/internal/initwizard/model.go +++ b/internal/initwizard/model.go @@ -8,44 +8,11 @@ import "errors" // confirming the review step. var ErrAborted = errors.New("init wizard aborted") -// ProjectModel describes the licensing posture the wizard is collecting for. -type ProjectModel string - -const ( - // ProjectModelOpenSource is for public source distributed under an SPDX license. - ProjectModelOpenSource ProjectModel = "open-source" - // ProjectModelPrivateInternal is for private source with internal policy needs. - ProjectModelPrivateInternal ProjectModel = "private-internal" - // ProjectModelExistingProject is for an existing repo where current files guide defaults. - ProjectModelExistingProject ProjectModel = "existing-project" - // ProjectModelAdvancedManual is for explicit flag or manual wizard choices. - ProjectModelAdvancedManual ProjectModel = "advanced-manual" -) - -// Step is the high-level screen/state currently active in the collector. -type Step int - -const ( - // StepProjectModel collects the project licensing model. - StepProjectModel Step = iota - // StepLicense collects the SPDX or future private license choice. - StepLicense - // StepIdentity collects holder and year policy values. - StepIdentity - // StepHeaderStyle collects the source header style. - StepHeaderStyle - // StepLicenseFiles collects top-level license file management intent. - StepLicenseFiles - // StepCoverage collects include and exclude coverage choices. - StepCoverage - // StepReview presents the final review before writing config. - StepReview -) - -// Answers is the structured payload returned by the interactive collector. +// Answers is the structured payload the init form edits and returns. WHY no project +// model or review step: the redesign detects defaults from the repo (see Seed) rather +// than asking a project-model question, and the single-screen form is itself the +// review, so the former Project/Review/Step machinery was removed. type Answers struct { - // Project records the project model choice. - Project ProjectAnswer // License records the target license choice. License LicenseAnswer // Identity records copyright holder and year policy. @@ -56,22 +23,12 @@ type Answers struct { LicenseFiles LicenseFilesAnswer // Coverage records include and exclude file scope answers. Coverage CoverageAnswer - // Review records the final confirmation state. - Review ReviewAnswer -} - -// ProjectAnswer holds the project model selection. -type ProjectAnswer struct { - // Model is the selected project model. - Model ProjectModel } // LicenseAnswer holds the target license selection. type LicenseAnswer struct { // SPDXID is the SPDX identifier selected for generated config. SPDXID string - // Private marks a future private/internal license path without SPDX rendering. - Private bool } // IdentityAnswer holds copyright identity answers. @@ -101,9 +58,3 @@ type CoverageAnswer struct { // Exclude is the selected exclude glob list. Exclude []string } - -// ReviewAnswer records whether the final review was confirmed. -type ReviewAnswer struct { - // Confirmed is true when the operator accepted the review screen. - Confirmed bool -} diff --git a/internal/initwizard/view.go b/internal/initwizard/view.go index e06af33..0931c7b 100644 --- a/internal/initwizard/view.go +++ b/internal/initwizard/view.go @@ -172,7 +172,7 @@ func renderGlobEditor(s FormState) string { for i, e := range entries { b.WriteString(cursorMark(i == s.globCursor) + e + "\n") } - fmt.Fprintf(&b, "add: %s_ (enter to add, d to remove)", s.globBuffer) + fmt.Fprintf(&b, "add: %s_ (enter to add, del to remove)", s.globBuffer) return b.String() } -- 2.54.0 From 32b44e51439765dfa9fc0983107dc496a325f333 Mon Sep 17 00:00:00 2001 From: James Maes Date: Mon, 8 Jun 2026 12:34:30 -0500 Subject: [PATCH 14/14] docs(#29): record init redesign completion in session state --- docs/SESSION-STATE.md | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/docs/SESSION-STATE.md b/docs/SESSION-STATE.md index dc2491a..52e8991 100644 --- a/docs/SESSION-STATE.md +++ b/docs/SESSION-STATE.md @@ -6,10 +6,19 @@ ## Current Objective Redesign `license-tool init` per `docs/DESIGN-init-tui-redesign.md`: single always-visible, repo-seeded form with an adaptive live preview; all logic in a tested `internal/initwizard`; `wizard.go` a thin Bubble Tea adapter. Plan: `docs/PLAN-GH-29-init-tui-redesign.md`. -## Status -- Full-codebase review complete: `docs/review/01-03`. Bugs filed: #30, #31, #32 (blocker for #29), #33, #34. -- Task 1 done (commit `4e3561e`): include globs honor `**` via shared `enumerate.CompileMatcher` (#32). -- Task 2 done (commit `bafa281`): single `initwizard.Translate` replaces `answersToConfig` + wizard `previewConfig`; tests moved to `internal/initwizard/translate_test.go`. +## Status: implementation COMPLETE (all gates green) +Full-codebase review: `docs/review/01-03`. Bugs filed: #30, #31, #32 (fixed here), #33, #34. + +Tasks 1-7 done on this branch: +- `4e3561e` fix(#32): include globs honor `**` via shared `enumerate.CompileMatcher`. +- `bafa281` refactor(#29): single `initwizard.Translate` (kills preview/write drift). +- `ddcc51d` feat(#29): `initwizard.Seed` repo detection (retires the dead project-model step). +- `45dcfd9` feat(#29): pure form state machine + live validation. +- `a6cc331` feat(#29): adaptive panel layout planner. +- `09c8174` feat(#29): pure adaptive view rendering. +- `0031b00` feat(#29): thin Bubble Tea adapter + wire-up; dead types removed; docs updated. Closes #29. + +Gates: gofmt clean, `go vet` clean, golangci-lint clean, `go test ./... -race` pass, coverage 100% (2521/2521), build clean. `wizard.go` ~990 -> ~230 lines, still coverage-excluded but now genuinely thin. ## Next Step -Task 3: trim dead types (`ProjectModel*`, `Step*`, `ReviewAnswer`, `ProjectAnswer`, `LicenseAnswer.Private`) and add `initwizard.Seed(root, deps)` repo detection. Then Tasks 4-7 (form state machine, layout, view, thin adapter + full gate). NOTE: the current `wizard.go` still references the soon-to-be-removed types; Task 7 rewrites it. +Not yet pushed / no PR (awaiting explicit permission). Optional before PR: tidy history (the `bafa281` commit bundled CLAUDE.md + design/review/plan docs via `git add -A`). Remaining review bugs #30/#31/#33/#34 are independent of #29 and untouched. Manual TUI spot-check: `go run ./cmd/license-tool init ` on a TTY. -- 2.54.0