init: full TUI configuration wizard with live source preview (#29) #37

Merged
KofTwentyTwo merged 17 commits from feature/GH-29-init-tui-wizard into develop 2026-06-09 15:17:56 +00:00
40 changed files with 4271 additions and 393 deletions

No files matched your search

+7 -6
View File
@@ -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 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 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$
+5
View File
@@ -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
+67
View File
@@ -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/<id>.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`.
+2
View File
@@ -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 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.
+15 -6
View File
@@ -114,15 +114,22 @@ 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
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
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,
@@ -153,7 +160,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 +169,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/<id>.txt
include: # optional globs limiting files considered
- "src/**"
exclude: # gitignore-style, in addition to .gitignore
- "**/generated/**"
- "**/*.pb.go"
+18 -53
View File
@@ -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"
@@ -223,7 +224,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 +262,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,
@@ -389,49 +390,10 @@ 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,
// 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 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)
}
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 a.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)
if err != nil {
return model.Config{}, err
}
cfg.Year = ys
}
if a.Style != "" {
st, err := config.ParseStyle(a.Style)
if err != nil {
return model.Config{}, err
}
cfg.Style = st
}
cfg.ManageLicenseFile = a.ManageLicenseFile
cfg.Excludes = a.Excludes
return cfg, nil
}
func newInitCmd(shared *sharedFlags) *cobra.Command {
f := &applyFlags{}
cmd := &cobra.Command{
@@ -441,18 +403,21 @@ 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{
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)
cfg, err := initwizard.Translate(a, initwizard.TranslateOptions{})
if err != nil {
return usageError(err)
}
@@ -495,7 +460,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)
+109 -76
View File
@@ -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"
@@ -295,6 +296,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 +759,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 +920,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 +931,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) {
@@ -925,66 +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(initAnswers{
License: "MIT",
Holder: "Acme, LLC",
Year: "2021-2026",
Style: "reuse",
ManageLicenseFile: false,
Excludes: []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{"**/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(initAnswers{License: "MIT", Holder: "Acme"})
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"})
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: ""})
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"})
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"})
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)
@@ -1032,28 +1018,18 @@ 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")
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")
}
// 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 +1041,63 @@ 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, "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{
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/**"},
},
}, 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{"cmd/**"}, cfg.Includes)
assert.Equal(t, []string{"generated/**"}, cfg.Excludes)
}
func TestSharedToFlags(t *testing.T) {
s := &sharedFlags{
configPath: "/cfg.yaml",
+175 -94
View File
@@ -1,114 +1,195 @@
package main
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"sort"
"time"
"github.com/charmbracelet/huh"
tea "github.com/charmbracelet/bubbletea"
"github.com/KofTwentyTwo/license-tool/internal/config"
"github.com/KofTwentyTwo/license-tool/internal/spdx"
"github.com/KofTwentyTwo/license-tool/internal/initwizard"
)
// 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")
// 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
// 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 {
form initwizard.FormState
sample initwizard.Sample
nowYear int
width int
height int
confirmed bool
}
// licenseSelectOptions builds the filterable license picker options: the curated
// CommonIDs first (each labeled "<id> (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] {
common := spdx.CommonIDs()
seen := make(map[string]bool, len(common))
opts := make([]huh.Option[string], 0, len(common))
for _, id := range common {
seen[id] = true
opts = append(opts, huh.NewOption(id+" (common)", id))
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(),
}
for _, id := range spdx.RenderableIDs() {
if seen[id] {
continue
}
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, m.height = msg.Width, msg.Height
return m, nil
case tea.KeyMsg:
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
}
opts = append(opts, huh.NewOption(id, id))
return m, nil
}
return opts
if m.form.Editing() {
return m.handleEditingKey(msg)
}
return m.handleNavKey(msg)
}
// 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"
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)
}
}
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()
return m, nil
}
// 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 {
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, height := m.width, m.height
if width <= 0 {
width = 120
}
if height <= 0 {
height = 34
}
// 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
}
return runInitWizard(a)
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 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.confirmed {
return a, initwizard.ErrAborted
}
return m.form.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)
}
+127
View File
@@ -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: <current value>` (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/<id>.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).
+80
View File
@@ -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.
+72
View File
@@ -0,0 +1,72 @@
# 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/<id>.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.
## 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. [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?
+16 -19
View File
@@ -1,27 +1,24 @@
# 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`.
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
- 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`.
## 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
Manual review and testing before any push to GitHub, promotion to `main`, tag, or release.
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 <path>` on a TTY.
+12 -50
View File
@@ -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
- [x] Define full feature specification and MVP boundaries.
- [x] 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 `<!DOCTYPE>` before inserted headers.
## Implementation
- [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.
## 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
## Verification
- [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`.
+287
View File
@@ -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: <id>` 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
`<root>/LICENSE` and `<root>/LICENSES/<id>.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.
+264
View File
@@ -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/<a>/node_modules/<b>`) 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 `<root>/.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<start rejected,
unknown style/year/fail_on tokens are hard errors (no silent CI weakening).
- **Explicit `--config` missing = error; discovered missing = silent** (config.go:137-151). Correct.
- **SPDX two-surface split** (`Validate` permissive over full index, `Lookup` curated) is sound;
`IDs()` correctly excludes deprecated ids from the picker; load is lazy/once/read-only so
concurrent callers are safe. AGPL header override is verbatim-body-preserving.
- **Policy `Passed`** is order-independent and correctly returns true for empty `fail_on`; per-file
and repo violations both feed the verdict via `report.Build`.
- **`EvaluateDependency`** correctly treats `resolved-but-no-id` as unresolved (policy.go:125-132)
rather than passing — a good defensive guard against a resolver lying.
- **Determinism**: every renderer sorts via `sortedCounts`/`sortedFiles`/`sortedDeps`; JSON relies
on encoding/json's sorted map keys plus pre-sorted slices; repo violation tokens are
sorted+deduped. `Build` preserves input file order but counts are order-independent. Verified no
map-iteration order leaks into output.
- **Enumerate skip ladder** (symlink → non-regular → unknown-type → uncommentable → binary) is in a
defensible order; `IsBinary` tolerates a truncated trailing rune at the 8 KiB boundary; staged
deletions (ls-files lists a path absent on disk) are skipped, not fatal.
- **`normalizeSPDX`** correctly rejects npm `SEE LICENSE`/`UNLICENSED` sentinels and compound
expressions (one-id-per-dep invariant).
## Test-quality note
The policy, spdxnorm, and config layering tests are **substantive** (real layering with `**`
globs, stacked-violation ordering assertions, category-sort assertions, alias branch coverage).
The one coverage-padding pattern that masks a real bug is `TestMatchesIncludes`
(enumerate_test.go:51-71): it asserts the broken single-segment behavior as if it were the
contract, so 100% line coverage coexists with finding #1. Recommend adding `**` include cases —
they will fail today and should drive the fix.
+235
View File
@@ -0,0 +1,235 @@
# Review 03 — Command layer, init TUI, and test quality
Scope: `cmd/license-tool/main.go`, `cmd/license-tool/commands.go` (+ `commands_test.go`),
`cmd/license-tool/wizard.go`, `internal/initwizard/{model.go,catalog.go}` (+ `catalog_test.go`).
Reviewed against the repo at branch `feature/GH-29-init-tui-wizard`.
## Summary table
| # | Area | Finding | Severity | Location |
|---|------|---------|----------|----------|
| 1 | Command layer | `--quiet` / `--verbose` persistent flags are bound but never read anywhere — dead UX surface | high | `commands.go:57-58` |
| 2 | Init TUI | Dead "Project model" step: collected, previewed, written to `Answers.Project`, but `answersToConfig` never reads `a.Project` — the whole first wizard screen has no effect on output | high | `commands.go:404-440`, `commands.go:452`, `wizard.go:353-354` |
| 3 | Init TUI | ~990-line `wizard.go` mixes pure logic (selection math, parsing, layout, preview assembly) with the Bubble Tea shell, so genuinely testable logic is parked in a coverage-excluded file | high | `wizard.go` (whole file) |
| 4 | Init TUI | Cram-two-values-into-one-textfield: Identity = `holder \| year`, Coverage = `include \| exclude`. Fragile `strings.Cut`/`splitCSV` parsing with no validation feedback in the field | medium | `wizard.go:728-768` |
| 5 | Model | `LicenseAnswer.Private` field is fully dead (never set, never read) | medium | `model.go:73-74` |
| 6 | Init correctness | `init` ignores `cfg.Year`/`cfg.Style`/etc. from a discovered config file: it scaffolds purely from `Defaults()` + flags, never calling `config.Resolve`. A second `init --force` silently discards prior non-flag settings | medium | `commands.go:419`, `commands.go:466-470` |
| 7 | Init correctness | `init` is the only write command that does NOT validate the target dir as a git tree / honor `--allow-dirty`; `--allow-dirty`/`--commit`/`--commit-message`/`--write` flags are bound on `init` (via `bindApplyFlags`) but meaningless there | medium | `commands.go:481` |
| 8 | Test quality | `internal/initwizard/model.go` has NO test file; the `Answers`/`Step` model and `ErrAborted` reach 100% only incidentally via `commands_test.go`/`wizard.go` usage — no behavioral assertions on the model itself | low | `internal/initwizard/` |
| 9 | Test quality | `TestInitCommandConsumesCollectorAnswers` asserts `initial.Project.Model` is passed in but never asserts the returned `Project`/`Review` affect output (consistent with finding #2 — there is nothing to assert, which masks the dead field) | low | `commands_test.go:1134-1192` |
| 10 | Command layer | `isWriteRefusal` classifies write-refusal vs internal errors by `strings.Contains` on the error message — brittle string coupling to `internal/applier` and `internal/config` wording | medium | `commands.go:290-293` |
| 11 | Command layer | `check --fail-on` only overrides policy when the flag was `Changed`; the bound default `[]string{...}` is therefore inert and exists only as help text. Mild redundancy, not a bug | low | `commands.go:143-149`, `commands.go:189` |
Overall: the command layer is correct on the load-bearing guarantees (dry-run-by-default,
exit-code mapping, `--fail-on` parsing, output-file handling, `isTTY` gating) and is
genuinely well-tested. The init TUI is the weak spot: it is large, carries a dead step and
a dead field, and parks testable logic inside the coverage-excluded shell. Test quality is
high and substantive almost everywhere — the few hollow spots are a direct consequence of
the dead wizard surface, not coverage-padding tricks.
---
## 1. Command layer correctness (focus area 1)
### Dry-run-by-default — CORRECT
`apply` and `license` default `--write=false` (`commands.go:385`) and pass `Write: f.write`
into `applier.Apply`/`applier.License`. `applier.go` guards every mutating branch behind
`opts.Write` (`applier.go:73,134,137,153,165,176`), so absent `--write` the run only
produces diffs. `TestApplyCommand/dry-run reports without writing` (`commands_test.go:646`)
asserts the source file is left untouched, and `dry-run json includes unified diff` /
`write json omits unified diff` pin the diff-presence contract. This guarantee is solid and
well covered.
### Exit-code mapping — CORRECT
`main.go` maps via `commandError`/`withExitCode`/`exitCode`:
- usage = 2 (also the fallback for untyped cobra errors via `exitCode`'s default arm),
- check failure = 1,
- write refusal = 3,
- internal = 4.
`commands_test.go:195-246` covers all four through `executeRoot`, and
`TestCheckFailingExits` (`commands_test.go:564`) uses the subprocess re-exec idiom to prove
the real `os.Exit(1)` path. `TestWithExitCodeNilError` covers the nil short-circuit. This is
thorough and correct.
### `--fail-on` parsing — CORRECT, one redundancy (finding #11)
`parseFailOnFlags` (`commands.go:337`) splits on commas AND across repeated flags via
`splitFlagTokens`, trims, drops empties, and rejects unknown tokens. `TestParseFailOnFlags`
covers the mixed `"a, b"` + repeated-flag + unknown cases.
Redundancy: the override only fires when `cmd.Flags().Changed("fail-on")` is true
(`commands.go:143`). The bound default list at `commands.go:189` is therefore never used to
*set* policy (the config/Defaults layer supplies the effective default); it serves only as
`--help` text. Harmless, but the dead default invites a future reader to assume it is
authoritative. Consider binding `--fail-on` with a nil default and documenting the real
default in the flag usage string.
### Output-file handling — CORRECT
`renderCommandReport` (`commands.go:314`) writes to stdout when `--output` is empty,
otherwise opens via the `createReportFile` seam, renders, and closes — correctly reporting
both render and close errors as internal (exit 4). `TestRenderCommandReportErrors` injects a
close-failing writer through the seam and asserts the close error is surfaced; the
`audit`/`check` "output file create error is internal error" subtests cover the create-fail
path. Good seam design and good coverage.
### `isTTY` gating — CORRECT
`isTTY` (`commands.go:652`) uses `term.IsTerminal` rather than an `os.ModeCharDevice` bit
test; the comment correctly explains that `/dev/null` is a char device but not a terminal.
`TestIsTTY` covers char-device, regular-file, and closed-fd cases. Note the gating reaches
TWO different interactive paths: the Bubble Tea wizard (`init`) and the line-prompt
`fillRequired` in `internal/config/config.go:617` (`apply`/`license`). Both are driven off
`isTTY()`; the test suite forces non-TTY via `forceNonTTYStdin`, so neither prompts in CI.
### Dead flags — finding #1 (high)
`--quiet`/`--verbose` are registered on the root persistent flag set (`commands.go:57-58`)
and stored on `sharedFlags`, but a grep across `cmd/` and `internal/` shows the fields are
read nowhere. They are pure no-ops. Either wire them into report verbosity / output
suppression or remove them; shipping flags that silently do nothing is a correctness/UX
trap. (They are not covered by any assertion either, so removing them is free.)
### `isWriteRefusal` string-matching — finding #10 (medium)
`isWriteRefusal` (`commands.go:290`) decides exit 3 vs exit 4 by
`strings.Contains(msg, "refusing to write")` / `"already exists (use --force)"`. This
couples the command layer to exact error wording in `internal/applier` and
`internal/config`. A reworded error in those packages would silently downgrade a write
refusal to an internal error (3→4) with no compile-time or test signal. Prefer a typed
sentinel (e.g. `errors.Is(err, applier.ErrWriteRefused)`) so the classification is
enforced by the type system.
---
## 2. The init TUI as code (focus area 2)
### Why it is 990 lines and uncoverable
`wizard.go` is excluded from the 100% gate (`.testcoverage.yml`) on the stated grounds that
it is "a Bubble Tea terminal shell ... no write-path validation of its own." That is only
half true. The file contains a large amount of pure, deterministic, trivially-testable
logic that has nothing to do with the terminal event loop:
- selection math: `wrapIndex`, `clampInt`, `windowStart`, `indexString`,
`indexProjectModel`, `moveSelection*` (`wizard.go:578-692,924-961`);
- license filtering: `filteredLicenseChoices`, `licenseChoicePosition`,
`alignLicenseSelection`, `isCommonLicense` (`wizard.go:639-682`);
- input parsing: `commitInput`, `coverageInputValue`, `splitCSV` (`wizard.go:728-768`);
- preview assembly: `previewConfig`, `previewResolvedYear`, `previewCandidatePaths`,
`ignoredPreviewDir`, `previewSummary` (`wizard.go:501-527,770-853`);
- text layout: `fitText`, `ellipsize`, `selectionList`, `licenseBody`, `reviewBody`,
`navigationBody`, `stepTitle` (`wizard.go:228-499,895-922`);
- formatting helpers: `yesNo`, `listOrAll`, `listOrNone`, `valueOrPlaceholder`.
None of these require a PTY. Only `Init`/`Update`/`View`/`runInitWizard`/`newInitWizardModel`
and the layout-width branches are genuinely shell-bound. The coverage exclusion is being
used to hide ~400+ lines of untested-but-testable logic behind the "it's a TUI" rationale.
Recommended extraction (does NOT change UX): move the pure pieces into
`internal/initwizard` (the package already exists and is fully tested) — e.g.
`initwizard.LicenseChoices(opts, filter, selectedIndex)`, `initwizard.PreviewConfig(...)`,
`initwizard.CoverageInput(...)`/`ParseCoverageInput(...)`, and the `wrapIndex`/`windowStart`
math. `wizard.go` then keeps only `tea.Model` glue and remains legitimately excluded. This
would meaningfully raise real (not gamed) coverage and let edge cases (empty license list,
filter-with-no-matches, window scrolling at boundaries) be asserted directly.
### Dead "Project model" step — finding #2 (high)
The wizard's first screen collects `Answers.Project.Model` (`wizard.go:353-354,580-582`),
the review screen displays it (`wizard.go:482`), and `newInitCmd` seeds it to
`ProjectModelAdvancedManual` (`commands.go:452`). But `answersToConfig` (`commands.go:404`)
never reads `a.Project` — it builds the config from License/Identity/HeaderStyle/
LicenseFiles/Coverage only. So the entire Project-model step is a no-op: whatever the user
picks, the generated `.license-tool.yaml` is identical. This is the single most misleading
thing in the init flow. Either (a) make the project model actually drive defaults
(open-source → manage license files + reuse+notice, private-internal → notice-only, etc.),
or (b) remove the step and the `ProjectAnswer` field until it has an effect. The
`projectModelOptions` slice and `ProjectModel*` constants are otherwise only self-referential.
### Cram-two-values-into-one-textfield — finding #4 (medium)
- Identity field packs `holder | year` into one text input (`wizard.go:716-719`), parsed by
`strings.Cut(value, "|")` in `commitInput` (`wizard.go:730-737`). If the holder legitimately
contains a `|`, parsing breaks. If the user omits the separator, the whole string becomes
the holder and year silently stays at its prior value.
- Coverage field packs `include globs | exclude globs` (`wizard.go:720-722,738-747`), split
on `|` then comma via `splitCSV`. Same separator-collision fragility; a glob containing a
literal `|` (rare but legal in some shells/patterns) would be mis-split.
There is no inline validation: a malformed entry is only rejected later in
`answersToConfig` (bad year/style) or accepted silently (bad globs). The instruction says
do not redesign UX — flagging purely as a code-fragility / maintainability concern. If kept,
the parse functions should at minimum be extracted and unit-tested with collision cases.
### Maintainability problems (concrete)
- `bodyView` (`wizard.go:271-332`) hard-codes a thicket of magic layout numbers
(`< 100`, `46`, `72`, `34`, `navWidth 22/18/24`, `topHeight` clamps) with no named
constants and no tests; any change risks silent visual regressions that the excluded-file
status guarantees won't be caught.
- Two parallel ordered lists of steps exist: the `Step` iota in `model.go:28-43` and the
literal slice in `navigationBody` (`wizard.go:389-397`). They must be kept in sync by hand;
adding a step requires editing both plus `stepTitle`'s switch (`wizard.go:232-248`).
- `previewConfig` (`wizard.go:770`) and `answersToConfig` (`commands.go:404`) independently
translate `Answers → model.Config` with subtly different rules (preview substitutes
`"Example, Inc."` for an empty holder and swallows parse errors; the real path rejects
them). Two translators for one concept is a drift hazard — the preview can show a config
the real writer would reject.
---
## 3. Test quality across the repo (focus area 3)
### Command layer tests — substantive, not padding
`commands_test.go` is strong: assertions check real output content (`+ SPDX-License-Identifier`,
unified-diff markers, JSON schema string, `result: PASS/FAIL`), file-system side effects
(header applied vs. not, LICENSE files created vs. absent), git commit scoping
(`--name-only` of HEAD excludes unrelated files), and exit codes via `executeRoot`. Negative
paths are covered with message assertions (bad format, bad fail-on token, unknown resolver
tier, missing `--config`, non-curated `Zlib`). The seams (`createReportFile`,
`interactiveCollect`) are injected to reach error arms deterministically. The subprocess
re-exec for `os.Exit` is the correct idiom. testify usage is idiomatic (`require` for
fatal preconditions, `assert` for soft checks); table tests in `TestArgPath`/`TestParseFailOnFlags`
are sound. This is meaningful coverage.
### `answersToConfig` gate — well-tested
`TestAnswersToConfig` exercises the valid case plus every rejection arm (unknown license,
empty holder, bad year, bad style) and the "empty year/style keep Defaults" branch. This is
exactly the right place to concentrate assertions given the wizard is excluded, and it does
the job.
### `internal/initwizard/catalog_test.go` — substantive
Asserts the catalog's exact membership and stable order (15 families), copy-semantics
(`TestCatalogReturnsACopy` mutates the returned slice and re-reads), extension→family
mapping including the C vs C++ split and C#, and `BuildSourcePreview` edge cases (empty
sample→C fallback, missing year, unknown license, no-file-type, uncommentable override).
`BuildYAMLPreview` is asserted to byte-match `config.RenderFile`. Good golden-style and
edge-case coverage. Minor: `indexOf` is a hand-rolled substring search where
`strings.Index` would do — harmless test-helper verbosity.
### Hollow / missing spots
- **`internal/initwizard/model.go` has no `model_test.go`** (finding #8, low). The
`Answers`/`Step`/`*Answer` types and `ErrAborted` are data/constants, so reaching them via
other packages satisfies the line gate, but there is no test that documents the model's
contract (e.g. step ordering, that `ErrAborted` is the sentinel `runInitWizard` returns).
This is benign for a pure data file, but it means the 100% number is partly incidental
here rather than earned by direct assertions.
- **`TestInitCommandConsumesCollectorAnswers`** (finding #9, low) passes `initial.Project.Model`
in and asserts it, and returns a `Project`/`Review` in the fake answers, but never asserts
those affect the written file — because they can't (finding #2). The test thus *looks* like
it validates the project model round-trips when in fact the field is inert. This is not
coverage-padding in the gaming sense, but it does give a false impression of behavior; a
reader should not trust that the Project field matters from this test.
### testify / table-test soundness — good
`require` vs `assert` discipline is correct throughout. `t.Setenv`/`t.TempDir`/`t.Cleanup`
are used to isolate (`isolateEnv` pins `XDG_CONFIG_HOME` and forces non-TTY stdin). No
obvious flaky-by-clock or order-dependent tests in the reviewed files. The one global-state
mutation (`os.Stdin`, `createReportFile`, `interactiveCollect`) is always paired with a
`t.Cleanup` restore.
---
## Recommended actions (priority order)
1. Resolve the dead Project step (#2): either wire `a.Project` into `answersToConfig`
defaults or remove the step + `ProjectAnswer` + `LicenseAnswer.Private` (#5).
2. Wire or remove `--quiet`/`--verbose` (#1).
3. Extract pure logic from `wizard.go` into `internal/initwizard` and add direct tests (#3);
collapse the two `Answers→Config` translators (preview vs real) into one.
4. Replace `isWriteRefusal` string matching with a typed sentinel error (#10).
5. Reconcile `init`'s flag surface: drop `--allow-dirty`/`--commit`/`--commit-message`
(or honor them) and decide whether `init` should layer an existing config via
`config.Resolve` rather than scaffolding only from Defaults+flags (#6, #7).
+4 -8
View File
@@ -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
-26
View File
@@ -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=
+9
View File
@@ -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
}
+41
View File
@@ -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)
}
+9 -31
View File
@@ -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
+21 -24
View File
@@ -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) {
+40
View File
@@ -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)
}
+45
View File
@@ -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"))
}
+6
View File
@@ -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"},
+1
View File
@@ -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},
+345
View File
@@ -0,0 +1,345 @@
// 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
// Language family labels supported by the source preview catalog.
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 <stdio.h>
void greet(const char *name) {
printf("Hello, %s\n", name);
}
`, "\n"),
},
{
Language: LanguageCPlusPlus,
Path: "example.cpp",
Source: strings.TrimLeft(`
#include <iostream>
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(`
<?php
function greet(string $name): string
{
return "Hello, " . $name;
}
`, "\n"),
},
{
Language: LanguageRuby,
Path: "example.rb",
Source: strings.TrimLeft(`
def greet(name)
"Hello, #{name}"
end
`, "\n"),
},
{
Language: LanguageSwift,
Path: "Example.swift",
Source: strings.TrimLeft(`
func greet(_ name: String) -> 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
}
+262
View File
@@ -0,0 +1,262 @@
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 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",
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
}
+443
View File
@@ -0,0 +1,443 @@
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 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
)
// 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:]...)
}
+307
View File
@@ -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)
}
+92
View File
@@ -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 = 46
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},
},
}
}
}
+64
View File
@@ -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)
}
+60
View File
@@ -0,0 +1,60 @@
// 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")
// 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 {
// 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
}
// LicenseAnswer holds the target license selection.
type LicenseAnswer struct {
// SPDXID is the SPDX identifier selected for generated config.
SPDXID string
}
// 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/<id>.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
}
+148
View File
@@ -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))
}
+190
View File
@@ -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)
}
+76
View File
@@ -0,0 +1,76 @@
package initwizard
import (
"fmt"
"strings"
"github.com/KofTwentyTwo/license-tool/internal/config"
"github.com/KofTwentyTwo/license-tool/internal/model"
"github.com/KofTwentyTwo/license-tool/internal/spdx"
)
// placeholderHolder stands in for an empty holder while previewing, so the live
// source/YAML preview is never blank before the user has typed a holder.
const placeholderHolder = "Example, Inc."
// TranslateOptions tunes Translate. AllowPlaceholders selects preview mode: an empty
// holder is filled with a placeholder and parse failures fall back to defaults
// instead of erroring, so the live preview always renders.
type TranslateOptions struct {
AllowPlaceholders bool
}
// Translate is the single conversion from wizard Answers to a model.Config, used by
// BOTH the live preview and the write path. WHY one function: a second translator
// (the old wizard previewConfig vs commands answersToConfig) could render a preview
// that disagreed with what got written. Strict mode (AllowPlaceholders false) is the
// write gate: it rejects an unrenderable license, an empty holder, and unparseable
// year/style. Preview mode tolerates all of those so the panel keeps rendering.
func Translate(a Answers, opts TranslateOptions) (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 !opts.AllowPlaceholders {
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")
}
} else if holder == "" {
holder = placeholderHolder
}
cfg := config.Defaults()
cfg.License = licenseID
cfg.Holder = holder
if year != "" {
ys, err := config.ParseYearSpec(year)
switch {
case err == nil:
cfg.Year = ys
case !opts.AllowPlaceholders:
return model.Config{}, err
}
}
if style != "" {
st, err := config.ParseStyle(style)
switch {
case err == nil:
cfg.Style = st
case !opts.AllowPlaceholders:
return model.Config{}, err
}
}
cfg.ManageLicenseFile = a.LicenseFiles.Manage
cfg.Includes = append([]string(nil), a.Coverage.Include...)
cfg.Excludes = append([]string(nil), a.Coverage.Exclude...)
return cfg, nil
}
+126
View File
@@ -0,0 +1,126 @@
package initwizard
import (
"testing"
"github.com/KofTwentyTwo/license-tool/internal/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestTranslateStrict drives the write-path gate: a valid case plus each rejection.
// WHY exhaustive: this is the single gate both the wizard and the flag-only init path
// funnel through, so every validation/parse arm must reject identically.
func TestTranslateStrict(t *testing.T) {
t.Run("valid answers build a config from defaults", func(t *testing.T) {
cfg, err := Translate(Answers{
License: LicenseAnswer{SPDXID: "MIT"},
Identity: IdentityAnswer{Holder: "Acme, LLC", Year: "2021-2026"},
HeaderStyle: HeaderStyleAnswer{Style: "reuse"},
LicenseFiles: LicenseFilesAnswer{Manage: false},
Coverage: CoverageAnswer{Include: []string{"src/**"}, Exclude: []string{"**/vendor/**"}},
}, TranslateOptions{})
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) {
cfg, err := Translate(Answers{
License: LicenseAnswer{SPDXID: "MIT"},
Identity: IdentityAnswer{Holder: "Acme"},
LicenseFiles: LicenseFilesAnswer{Manage: true},
}, TranslateOptions{})
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 := Translate(Answers{
License: LicenseAnswer{SPDXID: "NOT-A-LICENSE"},
Identity: IdentityAnswer{Holder: "Acme"},
}, TranslateOptions{})
require.Error(t, err)
assert.Contains(t, err.Error(), "not a recognized SPDX license identifier")
})
t.Run("valid but unrenderable license rejected", func(t *testing.T) {
// 0BSD is a real SPDX id; if the tool does not ship rendering for it, strict
// mode must reject it with the cannot-render message rather than the
// not-recognized one. Pick an id that validates but is not curated.
_, err := Translate(Answers{
License: LicenseAnswer{SPDXID: "Glide"},
Identity: IdentityAnswer{Holder: "Acme"},
}, TranslateOptions{})
require.Error(t, err)
assert.Contains(t, err.Error(), "cannot render")
})
t.Run("empty holder rejected", func(t *testing.T) {
_, err := Translate(Answers{License: LicenseAnswer{SPDXID: "MIT"}}, TranslateOptions{})
require.Error(t, err)
assert.Contains(t, err.Error(), "copyright holder is required")
})
t.Run("bad year rejected", func(t *testing.T) {
_, err := Translate(Answers{
License: LicenseAnswer{SPDXID: "MIT"},
Identity: IdentityAnswer{Holder: "Acme", Year: "not-a-year"},
}, TranslateOptions{})
require.Error(t, err)
assert.Contains(t, err.Error(), "year")
})
t.Run("bad style rejected", func(t *testing.T) {
_, err := Translate(Answers{
License: LicenseAnswer{SPDXID: "MIT"},
Identity: IdentityAnswer{Holder: "Acme"},
HeaderStyle: HeaderStyleAnswer{Style: "fancy"},
}, TranslateOptions{})
require.Error(t, err)
assert.Contains(t, err.Error(), "unknown style")
})
}
// TestTranslatePlaceholders verifies preview mode never errors and substitutes a
// placeholder holder, so the live preview keeps rendering mid-edit.
func TestTranslatePlaceholders(t *testing.T) {
opts := TranslateOptions{AllowPlaceholders: true}
t.Run("empty holder becomes placeholder", func(t *testing.T) {
cfg, err := Translate(Answers{License: LicenseAnswer{SPDXID: "MIT"}}, opts)
require.NoError(t, err)
assert.Equal(t, placeholderHolder, cfg.Holder)
})
t.Run("unparseable year and style fall back to defaults without error", func(t *testing.T) {
cfg, err := Translate(Answers{
License: LicenseAnswer{SPDXID: "MIT"},
Identity: IdentityAnswer{Holder: "Acme", Year: "not-a-year"},
HeaderStyle: HeaderStyleAnswer{Style: "fancy"},
}, opts)
require.NoError(t, err)
assert.Equal(t, model.YearGit, cfg.Year.Kind)
assert.Equal(t, model.StyleReusePlusNotice, cfg.Style)
})
t.Run("valid placeholder values pass through", func(t *testing.T) {
cfg, err := Translate(Answers{
License: LicenseAnswer{SPDXID: "MIT"},
Identity: IdentityAnswer{Holder: "Acme", Year: "current"},
HeaderStyle: HeaderStyleAnswer{Style: "notice"},
}, opts)
require.NoError(t, err)
assert.Equal(t, "Acme", cfg.Holder)
assert.Equal(t, model.YearCurrent, cfg.Year.Kind)
assert.Equal(t, model.StyleNotice, cfg.Style)
})
}
+338
View File
@@ -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 <SPDX> --holder \"<name>\""
}
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, del 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
}
+151
View File
@@ -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
View File
@@ -232,6 +232,8 @@ type Config struct {
Style HeaderStyle
// ManageLicenseFile enables writing top-level LICENSE + LICENSES/<id>.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.