diff --git a/README.md b/README.md index 75d8c65..15eb036 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ goversion publish # publish Git refs and a GitHub Release, then seed the Go prox - **Go Module Publishing:** Validates a release, atomically publishes only incomplete Git refs, creates or reuses a GitHub Release through `gh`, and seeds the Go module proxy. - **CLI and Library:** Offers both a command-line interface for quick version updates and a library for integrating version management into your applications. - **Flexible Configuration:** Specify the path to your version file and include additional files for Git staging. -- **Module Path Updates:** Updates `go.mod` and package self-imports for major versions that require a `/vN` suffix. +- **Module Path Updates:** Updates `go.mod`, package self-imports, and documentation references for major versions that require a `/vN` suffix. - **Supplemental File Bumping:** Bump a semantic version in additional Go project metadata files by finding and replacing the first semantic version. - **Post-bump Hooks:** Run custom scripts after version bumping but before committing, with access to old and new version via environment variables. @@ -56,7 +56,7 @@ flowchart TD C --> D[Resolve the next semantic version] D --> E[Validate allowed worktree changes] E --> F{Major bump to v2 or newer?} - F -- Yes --> G[Update go.mod and rewrite self-imports] + F -- Yes --> G[Update module paths, self-imports, and documentation] F -- No --> H[Update version and supplemental files] G --> H H --> I{Post-bump hook configured?} @@ -140,6 +140,8 @@ go tool github.com/bcomnes/goversion/v2 publish [flags] - `-file`: Additional file to include in the commit. This flag can be used multiple times. - `-bump-file`: Additional Go project metadata file to scan for the first semantic version and bump. This flag can be used multiple times. Only valid semver strings are matched (no "v" prefix). - `-post-bump`: Script to execute after version bump but before git commit. Receives `GOVERSION_OLD_VERSION` and `GOVERSION_NEW_VERSION` environment variables. Files created or modified by the script must be specified with `-file` to be included in the commit. +- `-skip-docs`: Skip automatic documentation path updates during major bumps, including dry runs. + Module paths, self-imports, explicit bump files, and post-bump hooks are unaffected. - `-version`: Show the version of the `goversion` CLI tool and exit. - `-help`: Show usage instructions. @@ -230,13 +232,65 @@ This command will: - Stage the updated version file (plus any `-file` flags). - Commit with the new version as the commit message (no `v` prefix). - Tag the commit with the canonical module tag: `vX.Y.Z` for a root module or `/vX.Y.Z` for a nested module. -- For major version bumps ≥ v2, update go.mod module path and rewrite self-imports. +- For major version bumps ≥ v2, update the `go.mod` module path, self-imports, and documentation references. > **Note**: The working directory must be clean (no unstaged/uncommitted changes outside the listed files) or the command will fail to prevent accidental commits. +### Major-version documentation updates + +`goversion major` updates module references in Markdown (`.md`, `.markdown`) and Go comments alongside the module path: + +| Before | After a v2 major bump | +| --- | --- | +| `https://pkg.go.dev/example.com/widget#Client` | `https://pkg.go.dev/example.com/widget/v2#Client` | +| `https://pkg.go.dev/badge/example.com/widget.svg` | `https://pkg.go.dev/badge/example.com/widget/v2.svg` | +| `https://godoc.org/example.com/widget/client` | `https://godoc.org/example.com/widget/v2/client` | +| `import "example.com/widget/client"` in an example | `import "example.com/widget/v2/client"` | +| `go get example.com/widget@latest` | `go get example.com/widget/v2@latest` | + +Later major bumps replace the suffix, such as `/v2` → `/v3`. +Changes are committed automatically; preview them with `goversion -dry major`. + +- **Preserved:** anchors, query parameters, pinned versions (`@v1.2.3`), references to other major versions or modules, repository URLs, and runtime strings. +- **Module-scoped:** nested modules and references to their declared paths stay unchanged. +- **Git-aware:** tracked and nonignored files are eligible; fully ignored trees such as `node_modules` are pruned before descent. + Tracked files and ignore exceptions remain eligible regardless of directory name; `vendor`, `.git`, and symlinks are always skipped. + +This follows the `major` command's module-path migration; explicit versions and `premajor` do not migrate module paths. + +#### Skip all documentation updates + +```console +goversion -skip-docs major +goversion -skip-docs -dry major +``` + +Only automatic documentation rewriting is disabled; version updates, `go.mod`, self-imports, `-bump-file`, and hooks still run. +Library callers can set [`VersionOptions.SkipDocs`](https://pkg.go.dev/github.com/bcomnes/goversion/v2/pkg#VersionOptions) with `RunWithOptions` or `DryRunWithOptions`. + +#### Keep an individual reference + +To keep a v2 link when bumping to v3: + +```markdown + +See the [v2 API](https://pkg.go.dev/example.com/widget/v2#Client). +``` + +In Go documentation, use a standalone line comment: + +```go +// goversion:ignore-next-line +// Previous API: https://pkg.go.dev/example.com/widget/v2#Client +``` + +The directive protects the next physical line only; a blank line consumes it. +Both real and dry runs honor it for documentation, not actual imports or `go.mod`. +The HTML directive is hidden when rendered; the Go comment appears in generated documentation. + ### Publishing -Create a version, run the project validation you require, and publish the Go release: +Create a version, test it, and publish: ```console goversion patch @@ -244,45 +298,68 @@ go test ./... goversion publish ``` -`goversion publish` performs the following guarded steps: - -1. Reads the existing version from `version.go` and validates it against the module path in `go.mod`. -2. Requires a module within the Git repository, a clean worktree, a current branch, and its matching canonical local tag at `HEAD`. -3. Rejects an existing remote tag when it points to a different commit. -4. Atomically publishes only incomplete branch or version-tag refs to the configured remote. -5. Creates or reuses a GitHub Release with generated notes through the authenticated `gh` CLI. -6. Seeds and verifies the complete module through `go mod download` using the configured Go proxy. -7. With `-major-branch`, creates or advances the moving `vN` branch for GitHub Action consumers only after every earlier step succeeds. - -If `gh` is missing or unauthenticated, publishing continues without a GitHub Release and prints an actionable warning. -A failure from an available and authenticated `gh` command remains fatal so a real release error is not silently ignored. -Use `-no-release` to intentionally omit the GitHub Release or `-no-proxy` for a private module that should not reach the public proxy. -The CLI prints each phase before starting it and streams useful stdout and stderr from external `git`, `gh`, and `go` commands as they run. -Machine-readable proxy output is captured and displayed as curated JSON without temporary cache paths. -Each external command has a two-minute timeout by default. -Proxy seeding reports each attempt and retries recognized transient HTTP and network failures up to three times with short backoff. -It disables checksum-database lookup for this isolated fetch so `sum.golang.org` availability cannot block verification of the configured module proxy. -Permanent module and proxy-response failures are not retried. -Use `-timeout` to change the per-command limit or a negative duration such as `-timeout=-1s` to disable it. -Nested modules are supported by passing the same module directory to versioning and publishing. For example, `goversion -workdir tools/widget patch` creates `tools/widget/vX.Y.Z`, and `goversion publish -workdir tools/widget` validates and publishes that exact tag. Version discovery filters tags by this module-directory prefix, so tags belonging to other modules are ignored. +Preview the release without changing remote state: ```console goversion publish -dry +``` + +Publishing requires a clean worktree, a current branch, and the version's canonical local tag at `HEAD`. +The module must be inside the Git repository, and its `go.mod` path must match the version in `version.go`. +A remote tag pointing to a different commit is rejected. + +Once validated, `goversion`: + +1. Atomically pushes branch and version-tag refs that are not already published. +2. Creates or reuses a GitHub Release with generated notes through `gh`. +3. Downloads and verifies the module through the Go proxy. + +#### Customize publishing + +| Option | Purpose | +| --- | --- | +| `-remote upstream` | Push to a different Git remote. | +| `-proxy https://proxy.golang.org` | Select the Go module proxy. | +| `-no-release` | Skip the GitHub Release. | +| `-no-proxy` | Skip proxy access, for example for a private module. | +| `-timeout 5m` | Change the two-minute per-command timeout; `-timeout=-1s` disables it. | +| `-major-branch` | Update a moving `vN` branch for GitHub Action consumers after publishing succeeds. | + +If `gh` is missing or unauthenticated, publishing continues with a warning and no GitHub Release. +Errors from an available, authenticated `gh` remain fatal. + +#### Publish a nested module + +Use the same module directory for versioning and publishing: + +```console +goversion -workdir tools/widget patch goversion publish -workdir tools/widget -goversion publish -remote upstream -goversion publish -proxy https://proxy.golang.org -goversion publish -timeout 5m -goversion publish -no-release -goversion publish -no-proxy -goversion publish -major-branch # publish vN (for example v2) after the release and proxy ``` -Publishing is resumable after a failure. -Each branch, tag, GitHub Release, proxy, and moving major-branch step reports a `planned`, `completed`, `reused`, or `skipped` status. -On retry, `goversion` skips Git refs that already point to the expected commit, reuses an existing GitHub Release, and continues with the first incomplete stage. -The moving major branch is opt-in because it is intended for GitHub Actions referenced as `owner/action@vN`. It is derived from the validated semantic version and updated with a force-with-lease pinned to the remote value observed during preflight, preventing an unseen concurrent update from being overwritten. -If proxy seeding was the failed stage, read-only Git and GitHub checks are repeated before retrying the proxy request. -It reports a `pkg.go.dev` URL, but documentation indexing may complete asynchronously after the proxy accepts the module. +The module uses tags such as `tools/widget/v2.0.1`. +Tags belonging to other modules are ignored; each invocation versions or publishes only the selected module. + +#### Retry a failed publish + +Run `goversion publish` again after fixing the failure. +It rechecks Git and GitHub state, skips refs already pointing to the expected commit, and reuses an existing GitHub Release. +Each stage reports `planned`, `completed`, `reused`, or `skipped`, with command output streamed as it runs. + +Proxy seeding retries recognized transient HTTP and network failures up to three times with short backoff; permanent failures are not retried. +The isolated download disables checksum-database lookup so `sum.golang.org` availability cannot block proxy verification. +The reported `pkg.go.dev` URL may become available later, since documentation indexing is asynchronous. + +#### Publish a moving major branch + +For GitHub Actions consumed as `owner/action@v2`: + +```console +goversion publish -major-branch +``` + +The `vN` branch is derived from the release version and updated only after the release and proxy steps succeed. +A force-with-lease pinned to the remote value observed during preflight protects against overwriting concurrent updates. ### Library Usage diff --git a/pkg/doc.go b/pkg/doc.go index d12b3a6..f3539d9 100644 --- a/pkg/doc.go +++ b/pkg/doc.go @@ -1,6 +1,8 @@ // Package goversion bumps semantic versions and publishes tagged Go module releases. // // Run updates a Go version file, applies configured project-file changes, creates a version commit, and tags that commit locally. +// Major bumps that change the module path also update self-references in Markdown and Go comments, +// including documentation links, badges, and example imports, while preserving pinned versions. // DryRun reports the version and files that Run would update without changing files or Git state. // Publish validates an existing version commit and tag, publishes incomplete Git refs, creates or reuses a GitHub Release, and seeds the Go module proxy. // Publish is resumable, so retrying after a failure reuses completed remote Git and GitHub Release steps. diff --git a/pkg/documentation.go b/pkg/documentation.go new file mode 100644 index 0000000..786bb65 --- /dev/null +++ b/pkg/documentation.go @@ -0,0 +1,213 @@ +package goversion + +import ( + "fmt" + "go/parser" + "go/token" + "io/fs" + "os" + + "path/filepath" + "regexp" + "strings" + + "golang.org/x/mod/module" +) + +// Keep URL tokens whole so a module path inside an unrelated URL is not rewritten. +var documentationToken = regexp.MustCompile("https?://[^\\s<>\"'`]+|[^\\s<>\"'`()[\\]{}*|]+") +var documentationMajor = regexp.MustCompile(`^/v[0-9]+(?:/|$)`) + +const documentationIgnoreNextLine = "goversion:ignore-next-line" + +// rewriteDocumentationText updates Markdown references, honoring a standalone +// HTML ignore-next-line comment. Blank lines consume the directive too. +func rewriteDocumentationText(text, oldMod, newMod string, excludedModules ...string) string { + var result strings.Builder + ignore := false + for _, line := range strings.SplitAfter(text, "\n") { + directive := strings.TrimSpace(line) == "" + if ignore || directive { + result.WriteString(line) + } else { + result.WriteString(rewriteDocumentationLine(line, oldMod, newMod, excludedModules...)) + } + ignore = directive + } + return result.String() +} + +// rewriteDocumentationLine updates self module/package references while preserving +// unrelated URLs and explicit version pins. The moving @latest selector follows +// the new module path, unlike a pinned release such as @v1.2.3. +func rewriteDocumentationLine(text, oldMod, newMod string, excludedModules ...string) string { + if oldMod == "" || oldMod == newMod { + return text + } + _, oldMajor, _ := module.SplitPathVersion(oldMod) + return documentationToken.ReplaceAllStringFunc(text, func(reference string) string { + core := strings.TrimRight(reference, ".,;:!)]}*|") + punctuation := reference[len(core):] + prefix, target := "", core + badge := false + for _, host := range []string{"https://pkg.go.dev/badge/", "http://pkg.go.dev/badge/", "https://pkg.go.dev/", "http://pkg.go.dev/", "https://godoc.org/", "http://godoc.org/"} { + if strings.HasPrefix(target, host) { + prefix, target = host, strings.TrimPrefix(target, host) + badge = strings.Contains(host, "/badge/") + break + } + } + // Anchors and query parameters belong to the URL, not the module path. + path, suffix := target, "" + if i := strings.IndexAny(path, "?#"); i >= 0 { + path, suffix = target[:i], target[i:] + } + modulePath := strings.SplitN(path, "@", 2)[0] + if badge { + modulePath = strings.TrimSuffix(modulePath, ".svg") + } + if excludedModuleReference(modulePath, excludedModules) { + return reference + } + if !strings.HasPrefix(path, oldMod) { + return reference + } + if i := strings.IndexByte(path, '@'); i >= 0 { + version := strings.SplitN(path[i+1:], "/", 2)[0] + if badge { + version = strings.TrimSuffix(version, ".svg") + } + if version != "latest" { + return reference + } + } + rest := strings.TrimPrefix(path, oldMod) + if badge && rest == ".svg" { + return prefix + newMod + rest + suffix + punctuation + } + if rest != "" && !strings.HasPrefix(rest, "/") && !strings.HasPrefix(rest, "@latest") { + return reference + } + majorPath := strings.SplitN(rest, "@", 2)[0] + if badge { + majorPath = strings.TrimSuffix(majorPath, ".svg") + } + if oldMajor == "" && documentationMajor.MatchString(majorPath) { + return reference + } + return prefix + newMod + rest + suffix + punctuation + }) +} + +// rewriteGoDocumentation edits comment byte ranges only, leaving literals and +// executable code untouched. Work backwards so earlier offsets remain valid. +func rewriteGoDocumentation(filename string, data []byte, oldMod, newMod string, excludedModules ...string) ([]byte, error) { + fset := token.NewFileSet() + file, err := parser.ParseFile(fset, filename, data, parser.ParseComments) + if err != nil { + return nil, err + } + text := string(data) + ignoredLines := make(map[int]bool) + for _, group := range file.Comments { + for _, comment := range group.List { + if !strings.HasPrefix(comment.Text, "//") || strings.TrimSpace(comment.Text[2:]) != documentationIgnoreNextLine { + continue + } + position := fset.PositionFor(comment.Pos(), false) + lineStart := strings.LastIndexByte(text[:position.Offset], '\n') + 1 + if strings.TrimSpace(text[lineStart:position.Offset]) == "" { + ignoredLines[position.Line+1] = true + } + } + } + for i := len(file.Comments) - 1; i >= 0; i-- { + comments := file.Comments[i].List + for j := len(comments) - 1; j >= 0; j-- { + comment := comments[j] + position := fset.PositionFor(comment.Pos(), false) + start := position.Offset + // Comment.End excludes carriage returns. Locate the end in the + // original bytes instead to preserve CRLF files without truncation. + end := len(data) + if strings.HasPrefix(string(data[start:]), "/*") { + end = start + strings.Index(string(data[start:]), "*/") + 2 + } else if n := strings.IndexByte(string(data[start:]), '\n'); n >= 0 { + end = start + n + } + bodyStart, bodyEnd := start+2, end + if data[start+1] == '*' { + bodyEnd -= 2 + } + var updated strings.Builder + for n, line := range strings.SplitAfter(string(data[bodyStart:bodyEnd]), "\n") { + if !ignoredLines[position.Line+n] { + line = rewriteDocumentationLine(line, oldMod, newMod, excludedModules...) + } + updated.WriteString(line) + } + text = text[:bodyStart] + updated.String() + text[bodyEnd:] + } + } + return []byte(text), nil +} + +// updateDocumentationReferences shares discovery and transformation between dry +// and real runs. Only files owned by this module are considered; symlinks are not followed. +func updateDocumentationReferences(modDir, oldMod, newMod string, dryRun bool) ([]string, error) { + if oldMod == newMod || oldMod == "" { + return nil, nil + } + excludedModules, err := nestedModulePaths(modDir) + if err != nil { + return nil, err + } + var changed []string + err = walkModuleFiles(modDir, func(filename string, entry fs.DirEntry) error { + ext := strings.ToLower(filepath.Ext(filename)) + if ext != ".md" && ext != ".markdown" && ext != ".go" { + return nil + } + data, err := os.ReadFile(filename) + if err != nil { + return err + } + var updated []byte + if ext == ".go" { + updated, err = rewriteGoDocumentation(filename, data, oldMod, newMod, excludedModules...) + } else { + updated = []byte(rewriteDocumentationText(string(data), oldMod, newMod, excludedModules...)) + } + if err != nil { + return fmt.Errorf("rewrite documentation in %s: %w", filename, err) + } + if string(data) == string(updated) { + return nil + } + if !dryRun { + info, err := entry.Info() + if err != nil { + return err + } + if err := os.WriteFile(filename, updated, info.Mode().Perm()); err != nil { + return err + } + } + changed = append(changed, filename) + return nil + }) + return changed, err +} + +// uniquePaths removes duplicate file entries without changing discovery order. +func uniquePaths(paths []string) []string { + seen := make(map[string]bool, len(paths)) + var unique []string + for _, path := range paths { + if !seen[path] { + seen[path] = true + unique = append(unique, path) + } + } + return unique +} diff --git a/pkg/documentation_directive_test.go b/pkg/documentation_directive_test.go new file mode 100644 index 0000000..3c1dd42 --- /dev/null +++ b/pkg/documentation_directive_test.go @@ -0,0 +1,143 @@ +package goversion + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestRewriteDocumentationTextIgnoreNextLine(t *testing.T) { + const old = "example.com/acme/widget" + const next = old + "/v2" + const directive = "" + refs := "\t`" + old + "` " + old + "/client@latest https://pkg.go.dev/" + old + "/client#Overview " + updated := strings.ReplaceAll(refs, old, next) + for _, tc := range []struct{ name, input, want string }{ + {"one physical line", refs + "\n" + directive + "\n" + refs + "\n" + refs, updated + "\n" + directive + "\n" + refs + "\n" + updated}, + {"whitespace", " \t" + directive + "\t \n" + refs, " \t" + directive + "\t \n" + refs}, + {"blank consumes skip", directive + "\n\n" + refs, directive + "\n\n" + updated}, + {"whitespace line consumes skip", directive + "\n \t\n" + refs, directive + "\n \t\n" + updated}, + {"consecutive directives", directive + "\n" + directive + "\n" + refs + "\n" + refs, directive + "\n" + directive + "\n" + refs + "\n" + updated}, + {"prose prefix", "Use " + directive + "\n" + refs, "Use " + directive + "\n" + updated}, + {"prose suffix", directive + " is documented here\n" + refs, directive + " is documented here\n" + updated}, + {"bare mention", "goversion:ignore-next-line\n" + refs, "goversion:ignore-next-line\n" + updated}, + {"directive at EOF", refs + "\n" + directive, updated + "\n" + directive}, + } { + t.Run(tc.name, func(t *testing.T) { + documentationDirectiveLineEndings(t, tc.input, tc.want, func(input string) string { + return rewriteDocumentationText(input, old, next) + }) + }) + } +} + +func TestRewriteGoDocumentationIgnoreNextLine(t *testing.T) { + const old = "example.com/acme/widget" + const next = old + "/v2" + const directive = "// goversion:ignore-next-line" + refs := "// café " + old + " " + old + "/client@latest https://pkg.go.dev/" + old + "#Overview " + updated := strings.ReplaceAll(refs, old, next) + for _, tc := range []struct{ name, input, want string }{ + {"per comment not group", refs + "\n" + directive + "\n" + refs + "\n" + refs, updated + "\n" + directive + "\n" + refs + "\n" + updated}, + {"whitespace", " \t//\tgoversion:ignore-next-line \t\n" + refs, " \t//\tgoversion:ignore-next-line \t\n" + refs}, + {"no space after slashes", "//goversion:ignore-next-line\n" + refs, "//goversion:ignore-next-line\n" + refs}, + {"blank consumes skip", directive + "\n\n" + refs, directive + "\n\n" + updated}, + {"whitespace line consumes skip", directive + "\n \t\n" + refs, directive + "\n \t\n" + updated}, + {"consecutive directives", directive + "\n" + directive + "\n" + refs + "\n" + refs, directive + "\n" + directive + "\n" + refs + "\n" + updated}, + {"code consumes skip", directive + "\nvar N = 1\n" + refs, directive + "\nvar N = 1\n" + updated}, + {"next line trailing comment", directive + "\nvar N = 1 " + refs + "\n" + refs, directive + "\nvar N = 1 " + refs + "\n" + updated}, + {"prose prefix", "// Use goversion:ignore-next-line\n" + refs, "// Use goversion:ignore-next-line\n" + updated}, + {"prose suffix", directive + " is documented here\n" + refs, directive + " is documented here\n" + updated}, + {"non standalone trailing directive", "var N = 1 " + directive + "\n" + refs, "var N = 1 " + directive + "\n" + updated}, + {"non standalone after block comment", "/* note */ " + directive + "\n" + refs, "/* note */ " + directive + "\n" + updated}, + {"raw string directive", "var Raw = `\n" + directive + "\n` " + refs + "\n" + refs, "var Raw = `\n" + directive + "\n` " + updated + "\n" + updated}, + {"imports untouched by doc scanner", directive + "\nimport _ \"" + old + "/client\"\n" + refs, directive + "\nimport _ \"" + old + "/client\"\n" + updated}, + {"ordinary import untouched", "import _ \"" + old + "/client\"\n" + refs, "import _ \"" + old + "/client\"\n" + updated}, + {"directive at EOF", refs + "\n" + directive, updated + "\n" + directive}, + } { + t.Run(tc.name, func(t *testing.T) { + documentationDirectiveLineEndings(t, "package widget\n\n"+tc.input, "package widget\n\n"+tc.want, func(input string) string { + got, err := rewriteGoDocumentation("directive.go", []byte(input), old, next) + if err != nil { + t.Fatalf("rewriteGoDocumentation: %v", err) + } + return string(got) + }) + }) + } +} + +func documentationDirectiveLineEndings(t *testing.T, input, want string, rewrite func(string) string) { + t.Helper() + for _, ending := range []struct{ name, value string }{{"LF", "\n"}, {"CRLF", "\r\n"}} { + for _, final := range []struct{ name, value string }{{"final newline", "\n"}, {"no final newline", ""}} { + t.Run(ending.name+"/"+final.name, func(t *testing.T) { + before := strings.ReplaceAll(input+final.value, "\n", ending.value) + expected := strings.ReplaceAll(want+final.value, "\n", ending.value) + if got := rewrite(before); got != expected { + t.Errorf("rewrite = %q; want %q", got, expected) + } + }) + } + } +} + +func TestDocumentationIgnoreNextLineMajorIntegration(t *testing.T) { + if err := checkGit(); err != nil { + t.Skip("git is not available on system") + } + const old = "example.com/acme/repo/tools/widget" + const next = old + "/v2" + root, dir := initNestedModuleRepo(t, old, "1.9.0") + readme := filepath.Join(dir, "README.md") + consumer := filepath.Join(dir, "consumer.go") + protectedMarkdown := filepath.Join(dir, "protected.markdown") + protectedGo := filepath.Join(dir, "protected.go") + mod := filepath.Join(dir, "go.mod") + original := map[string]string{ + readme: "\n" + old + " " + old + "/client@latest\nSee " + old + ".\n", + consumer: "package widget\n\n// goversion:ignore-next-line\nimport _ \"" + old + "/client\"\n\n// goversion:ignore-next-line\n// " + old + " " + old + "/client\n// Ordinary " + old + ".\n", + protectedMarkdown: " \t \t\r\n" + old + " https://pkg.go.dev/" + old, + protectedGo: "package widget\r\n\r\n//goversion:ignore-next-line\r\n// " + old + " " + old + "/client", + mod: "// goversion:ignore-next-line\nmodule " + old + "\n\ngo 1.23\n", + } + for path, content := range original { + documentationWrite(t, path, content) + } + gitRun(t, root, "add", ".") + gitRun(t, root, "commit", "-m", "add ignore-next-line fixtures") + options := VersionOptions{WorkDir: dir} + dry, err := DryRunWithOptions(options, "major") + if err != nil { + t.Fatal(err) + } + wantPaths := []string{mod, filepath.Join(dir, "version.go"), readme, consumer} + documentationAssertPaths(t, dry.UpdatedFiles, wantPaths) + for path, content := range original { + documentationAssertContent(t, path, content) + } + if status := gitOutput(t, root, "--no-pager", "status", "--porcelain"); status != "" { + t.Fatalf("dry run changed worktree/index: %s", status) + } + wet, err := RunWithOptions(options, "major") + if err != nil { + t.Fatal(err) + } + documentationAssertPaths(t, wet.UpdatedFiles, wantPaths) + documentationAssertPaths(t, wet.UpdatedFiles, dry.UpdatedFiles) + documentationAssertContent(t, readme, strings.Replace(original[readme], "See "+old, "See "+next, 1)) + wantConsumer := strings.Replace(original[consumer], "import _ \""+old, "import _ \""+next, 1) + wantConsumer = strings.Replace(wantConsumer, "// Ordinary "+old, "// Ordinary "+next, 1) + documentationAssertContent(t, consumer, wantConsumer) + for _, path := range []string{protectedMarkdown, protectedGo} { + documentationAssertContent(t, path, original[path]) + } + data, err := os.ReadFile(mod) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(data), "module "+next+"\n") { + t.Errorf("go.mod directive must not prevent module migration: %s", data) + } +} diff --git a/pkg/documentation_test.go b/pkg/documentation_test.go new file mode 100644 index 0000000..b50d15c --- /dev/null +++ b/pkg/documentation_test.go @@ -0,0 +1,360 @@ +package goversion + +import ( + "os" + "path/filepath" + "slices" + "strings" + "testing" +) + +func TestRewriteDocumentationText(t *testing.T) { + for _, migration := range []struct{ name, oldMod, newMod string }{ + {"v1 to v2", "github.com/acme/foo", "github.com/acme/foo/v2"}, + {"v2 to v3", "github.com/acme/foo/v2", "github.com/acme/foo/v3"}, + } { + t.Run(migration.name, func(t *testing.T) { + old, next := migration.oldMod, migration.newMod + for _, tc := range []struct{ name, input, want string }{ + {"bare module", old, next}, + {"bold module", "**" + old + "**", "**" + next + "**"}, + {"italic package", "*" + old + "/client*", "*" + next + "/client*"}, + {"bold docs URL", "**https://pkg.go.dev/" + old + "#Overview**", "**https://pkg.go.dev/" + next + "#Overview**"}, + {"italic docs URL", "*https://godoc.org/" + old + "/client*", "*https://godoc.org/" + next + "/client*"}, + {"compact module table", "|" + old + "|" + old + "/client|", "|" + next + "|" + next + "/client|"}, + {"compact URL table", "|https://pkg.go.dev/" + old + "|", "|https://pkg.go.dev/" + next + "|"}, + {"latest module", "go get " + old + "@latest", "go get " + next + "@latest"}, + {"latest godoc", "https://godoc.org/" + old + "@latest/client?tab=doc#Client", "https://godoc.org/" + next + "@latest/client?tab=doc#Client"}, + {"commands", "go get " + old + "\ngo install " + old + "/cmd/foo\n", "go get " + next + "\ngo install " + next + "/cmd/foo\n"}, + {"example import", "```go\nimport \"" + old + "/client\"\n```", "```go\nimport \"" + next + "/client\"\n```"}, + {"punctuation", "Use (`" + old + "`), \"" + old + "/client\".", "Use (`" + next + "`), \"" + next + "/client\"."}, + {"package docs", "[API](https://pkg.go.dev/" + old + "/client?tab=doc#Client)", "[API](https://pkg.go.dev/" + next + "/client?tab=doc#Client)"}, + {"module docs", "https://pkg.go.dev/" + old + "#section-readme", "https://pkg.go.dev/" + next + "#section-readme"}, + {"badge", "https://pkg.go.dev/badge/" + old, "https://pkg.go.dev/badge/" + next}, + {"svg badge", "![docs](https://pkg.go.dev/badge/" + old + ".svg?status=ok#badge)", "![docs](https://pkg.go.dev/badge/" + next + ".svg?status=ok#badge)"}, + {"subpackage badge", "https://pkg.go.dev/badge/" + old + "/client.svg", "https://pkg.go.dev/badge/" + next + "/client.svg"}, + {"godoc", "https://godoc.org/" + old + "/client?status.svg#Client", "https://godoc.org/" + next + "/client?status.svg#Client"}, + {"mixed references", old + " https://github.com/acme/foo " + old + "/client", next + " https://github.com/acme/foo " + next + "/client"}, + {"latest command", "go install " + old + "/cmd/foo@latest", "go install " + next + "/cmd/foo@latest"}, + {"latest package docs", "https://pkg.go.dev/" + old + "@latest/client#Client", "https://pkg.go.dev/" + next + "@latest/client#Client"}, + {"latest package suffix", "https://pkg.go.dev/" + old + "/client@latest#Client", "https://pkg.go.dev/" + next + "/client@latest#Client"}, + {"latest badge", "https://pkg.go.dev/badge/" + old + "@latest.svg", "https://pkg.go.dev/badge/" + next + "@latest.svg"}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := rewriteDocumentationText(tc.input, old, next); got != tc.want { + t.Errorf("rewriteDocumentationText(%q) = %q; want %q", tc.input, got, tc.want) + } + }) + } + for _, input := range []string{ + "", "unrelated documentation", old + "-tools", old + "bar", "not" + old, + "go get " + old + "@v1.2.3", "go install " + old + "/cmd/foo@v1.2.3", + "import \"" + old + "@v1.2.3/client\"", + "https://pkg.go.dev/" + old + "@v1.2.3/client?tab=doc#Client", + "https://pkg.go.dev/" + old + "/client@v1.2.3#Client", + "https://pkg.go.dev/badge/" + old + "@v1.2.3.svg", + "https://godoc.org/" + old + "@v1.2.3/client#Client", + "https://pkg.go.dev/" + old + "-tools/client", + "https://github.com/acme/foo", "https://github.com/acme/foo/tree/main/client", + "https://" + old + "/client", "https://example.org/" + old, + "https://example.org/?module=" + old, + "https://example.org/?module=(" + old + ")", + "https://example.org/a(b)?module=" + old, + "[other](https://example.org/?module=(" + old + "/client)&next=ok)", + "https://example.org/?module=((" + old + "))#section", + } { + t.Run("preserve "+input, func(t *testing.T) { + if got := rewriteDocumentationText(input, old, next); got != input { + t.Errorf("rewriteDocumentationText(%q) = %q; want unchanged", input, got) + } + }) + } + }) + } +} + +func TestRewriteDocumentationTextPreservesOtherMajors(t *testing.T) { + const old = "github.com/acme/foo" + for _, suffix := range []string{"/v2", "/v3/client", "/v20/client", "/v2@latest", "/v3@latest/client"} { + for _, prefix := range []string{"", "https://pkg.go.dev/", "https://pkg.go.dev/badge/", "https://godoc.org/"} { + input := prefix + old + suffix + if got := rewriteDocumentationText(input, old, old+"/v2"); got != input { + t.Errorf("rewriteDocumentationText(%q) = %q; want unchanged", input, got) + } + } + } + input := old + " https://pkg.go.dev/" + old + "/client#Client" + if got := rewriteDocumentationText(input, old, old); got != input { + t.Errorf("same-module rewrite = %q; want %q", got, input) + } +} + +func TestUpdateDocumentationReferences(t *testing.T) { + const old = "github.com/acme/foo" + const next = old + "/v2" + dir := t.TempDir() + before := map[string]string{ + "go.mod": "module " + old + "\n\ngo 1.23\n", + "README.md": "go get " + old + "\n", + "docs/guide.MD": "import \"" + old + "/client\"\n", + "docs/api.MarkDown": "https://pkg.go.dev/" + old + "#Overview\n", + "docs/usage.markdown": "https://godoc.org/" + old + "/client\n", + "doc.go": "// Package foo uses " + old + ".\npackage foo\n\n/* See https://pkg.go.dev/" + old + "/client#Client. */\nconst URL = \"" + old + "\"\nconst Raw = `https://pkg.go.dev/" + old + "`\nvar _ = \"https://example.org\" // " + old + "/client\n", + "literal.go": "package foo\nconst Text = \"// " + old + "\"\nconst Block = `/* " + old + " */`\n", + "imports.go": "package foo\nimport _ \"" + old + "/client\"\n", + "notes.txt": old, + "unchanged.md": old + "@v1.2.3\n", + ".git/hidden.md": old, + "vendor/dependency/README.md": old, + "nested/go.mod": "module example.com/nested\n\ngo 1.23\n", + "nested/README.md": old, + "nested/deep/doc.go": "package nested // " + old + "\n", + } + after := make(map[string]string, len(before)) + for name, content := range before { + documentationWrite(t, filepath.Join(dir, name), content) + after[name] = content + } + for _, name := range []string{"README.md", "docs/guide.MD", "docs/api.MarkDown", "docs/usage.markdown"} { + after[name] = strings.ReplaceAll(before[name], old, next) + } + after["doc.go"] = "// Package foo uses " + next + ".\npackage foo\n\n/* See https://pkg.go.dev/" + next + "/client#Client. */\nconst URL = \"" + old + "\"\nconst Raw = `https://pkg.go.dev/" + old + "`\nvar _ = \"https://example.org\" // " + next + "/client\n" + readme := filepath.Join(dir, "README.md") + if err := os.Chmod(readme, 0o640); err != nil { + t.Fatal(err) + } + outside := t.TempDir() + external := filepath.Join(outside, "README.md") + documentationWrite(t, external, old) + for name, target := range map[string]string{"linked.md": external, "linked-dir": outside, "internal-link.md": readme, "broken.md": filepath.Join(outside, "missing")} { + if err := os.Symlink(target, filepath.Join(dir, name)); err != nil { + t.Fatal(err) + } + } + want := []string{readme, filepath.Join(dir, "docs/guide.MD"), filepath.Join(dir, "docs/api.MarkDown"), filepath.Join(dir, "docs/usage.markdown"), filepath.Join(dir, "doc.go")} + for _, dry := range []bool{true, false} { + got, err := updateDocumentationReferences(dir, old, next, dry) + if err != nil { + t.Fatalf("dryRun=%v: %v", dry, err) + } + documentationAssertPaths(t, got, want) + expected := after + if dry { + expected = before + } + for name, content := range expected { + documentationAssertContent(t, filepath.Join(dir, name), content) + } + documentationAssertContent(t, external, old) + info, err := os.Stat(readme) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o640 { + t.Errorf("dryRun=%v: mode = %o; want 640", dry, info.Mode().Perm()) + } + for _, name := range []string{"linked.md", "linked-dir", "internal-link.md", "broken.md"} { + info, err := os.Lstat(filepath.Join(dir, name)) + if err != nil || info.Mode()&os.ModeSymlink == 0 { + t.Errorf("symlink %s was changed: %v", name, err) + } + } + } + for _, dry := range []bool{true, false} { + got, err := updateDocumentationReferences(dir, next, next, dry) + if err != nil || len(got) != 0 { + t.Errorf("same module dryRun=%v: files=%v err=%v; want no-op", dry, got, err) + } + for name, content := range after { + documentationAssertContent(t, filepath.Join(dir, name), content) + } + } +} + +func TestUpdateDocumentationReferencesPreservesCommentBytes(t *testing.T) { + const old = "github.com/acme/foo" + const next = old + "/v2" + dir := t.TempDir() + path := filepath.Join(dir, "doc.go") + // Deliberately retain CRLF, non-gofmt spacing, Unicode, and a final comment without a newline. + before := "// Package foo: café " + old + "\r\npackage foo\r\n\r\n" + + "/* first line\r\n\t" + old + "/client\r\n last line */\r\n" + + "var Literal = \"" + old + "\" // " + old + "@latest\r\n" + + "var Raw = `/* " + old + " */`\r\n" + + "// https://pkg.go.dev/" + old + "#Overview" + want := "// Package foo: café " + next + "\r\npackage foo\r\n\r\n" + + "/* first line\r\n\t" + next + "/client\r\n last line */\r\n" + + "var Literal = \"" + old + "\" // " + next + "@latest\r\n" + + "var Raw = `/* " + old + " */`\r\n" + + "// https://pkg.go.dev/" + next + "#Overview" + documentationWrite(t, path, before) + for _, dry := range []bool{true, false} { + got, err := updateDocumentationReferences(dir, old, next, dry) + if err != nil { + t.Fatalf("dryRun=%v: %v", dry, err) + } + documentationAssertPaths(t, got, []string{path}) + expected := want + if dry { + expected = before + } + documentationAssertContent(t, path, expected) + } +} + +func TestDocumentationMajorIntegration(t *testing.T) { + for _, tc := range []struct{ version, oldMod, newMod, tag string }{ + {"1.9.0", "example.com/acme/repo/tools/widget", "example.com/acme/repo/tools/widget/v2", "tools/widget/v2.0.0"}, + {"2.9.0", "example.com/acme/repo/tools/widget/v2", "example.com/acme/repo/tools/widget/v3", "tools/widget/v3.0.0"}, + } { + t.Run(tc.version, func(t *testing.T) { + root, dir := initNestedModuleRepo(t, tc.oldMod, tc.version) + readme := filepath.Join(dir, "README.md") + consumer := filepath.Join(dir, "consumer.go") + comment := filepath.Join(dir, "doc.go") + testFile := filepath.Join(dir, "consumer_test.go") + trackedIgnored := filepath.Join(dir, "generated", "tracked.md") + ignored := filepath.Join(dir, "generated", "untracked.md") + original := map[string]string{ + readme: "go get " + tc.oldMod + "\n", + testFile: "package widget_test\n\nimport _ \"" + tc.oldMod + "/client\"\n\n// See https://pkg.go.dev/" + tc.oldMod + "/client.\nconst RuntimePath = \"" + tc.oldMod + "\"\n", + trackedIgnored: "go get " + tc.oldMod + "@latest\n", + consumer: "package widget\n\nimport _ \"" + tc.oldMod + "/client\"\n\n// See https://pkg.go.dev/" + tc.oldMod + "/client.\nconst RuntimePath = \"" + tc.oldMod + "\"\n", + comment: "// Package widget uses " + tc.oldMod + ".\npackage widget\n", + } + for path, content := range original { + documentationWrite(t, path, content) + } + outside := filepath.Join(root, "README.md") + documentationWrite(t, outside, tc.oldMod) + documentationWrite(t, filepath.Join(dir, ".gitignore"), "generated/\n") + documentationWrite(t, ignored, "go get "+tc.oldMod+"\n") + gitRun(t, root, "add", ".") + gitRun(t, root, "add", "-f", trackedIgnored) + gitRun(t, root, "commit", "-m", "add documentation fixtures") + head := gitOutput(t, root, "--no-pager", "rev-parse", "HEAD") + options := VersionOptions{WorkDir: dir} + dry, err := DryRunWithOptions(options, "major") + if err != nil { + t.Fatal(err) + } + want := []string{filepath.Join(dir, "go.mod"), filepath.Join(dir, "version.go"), readme, consumer, comment, testFile, trackedIgnored} + documentationAssertPaths(t, dry.UpdatedFiles, want) + for path, content := range original { + documentationAssertContent(t, path, content) + } + documentationAssertContent(t, ignored, "go get "+tc.oldMod+"\n") + if got := gitOutput(t, root, "--no-pager", "rev-parse", "HEAD"); got != head { + t.Error("dry run changed HEAD") + } + if got := gitOutput(t, root, "--no-pager", "tag", "--list"); got != "" { + t.Errorf("dry run created tags: %s", got) + } + if got := gitOutput(t, root, "--no-pager", "status", "--porcelain"); got != "" { + t.Fatalf("dry run changed worktree/index: %s", got) + } + wet, err := RunWithOptions(options, "major") + if err != nil { + t.Fatal(err) + } + documentationAssertPaths(t, wet.UpdatedFiles, want) + if dry.Tag != tc.tag || wet.Tag != tc.tag || dry.NewVersion != wet.NewVersion { + t.Errorf("unexpected metadata: dry=%+v wet=%+v", dry, wet) + } + documentationAssertContent(t, readme, strings.ReplaceAll(original[readme], tc.oldMod, tc.newMod)) + documentationAssertContent(t, comment, strings.ReplaceAll(original[comment], tc.oldMod, tc.newMod)) + documentationAssertContent(t, trackedIgnored, strings.ReplaceAll(original[trackedIgnored], tc.oldMod, tc.newMod)) + for _, path := range []string{consumer, testFile} { + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + for _, text := range []string{"import _ \"" + tc.newMod + "/client\"", "// See https://pkg.go.dev/" + tc.newMod + "/client.", "const RuntimePath = \"" + tc.oldMod + "\""} { + if !strings.Contains(string(data), text) { + t.Errorf("%s missing %q:\n%s", path, text, data) + } + } + } + documentationAssertContent(t, outside, tc.oldMod) + documentationAssertContent(t, ignored, "go get "+tc.oldMod+"\n") + if got := gitOutput(t, root, "--no-pager", "status", "--porcelain"); got != "" { + t.Errorf("run left unstaged/uncommitted changes: %s", got) + } + if got := gitOutput(t, root, "--no-pager", "ls-files", "--", ignored); got != "" { + t.Errorf("ignored Markdown was added to Git: %s", got) + } + for _, path := range []string{readme, consumer, comment, testFile, trackedIgnored} { + rel, err := filepath.Rel(root, path) + if err != nil { + t.Fatal(err) + } + committed := gitOutput(t, root, "--no-pager", "show", tc.tag+":"+filepath.ToSlash(rel)) + documentationAssertContent(t, path, committed) + } + }) + } +} + +func TestDocumentationNonMigratingBumps(t *testing.T) { + for _, tc := range []struct{ version, bump string }{ + {"1.9.0", "patch"}, {"1.9.0", "minor"}, {"1.9.0", "premajor"}, {"1.9.0", "2.0.0"}, {"0.9.0", "major"}, + } { + t.Run(tc.version+"/"+tc.bump, func(t *testing.T) { + const mod = "example.com/acme/repo/tools/widget" + root, dir := initNestedModuleRepo(t, mod, tc.version) + path := filepath.Join(dir, "README.md") + documentationWrite(t, path, "go get "+mod+"\n") + gitRun(t, root, "add", ".") + gitRun(t, root, "commit", "-m", "add documentation fixture") + for _, run := range []func(VersionOptions, string) (VersionMeta, error){DryRunWithOptions, RunWithOptions} { + meta, err := run(VersionOptions{WorkDir: dir}, tc.bump) + if err != nil { + t.Fatal(err) + } + if containsPath(meta.UpdatedFiles, path) { + t.Errorf("non-migrating bump reports documentation: %v", meta.UpdatedFiles) + } + documentationAssertContent(t, path, "go get "+mod+"\n") + data, err := os.ReadFile(filepath.Join(dir, "go.mod")) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(data), "module "+mod+"\n") { + t.Errorf("non-migrating bump changed module path: %s", data) + } + } + }) + } +} + +func documentationWrite(t *testing.T, path, content string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } +} + +func documentationAssertContent(t *testing.T, path, want string) { + t.Helper() + got, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if string(got) != want { + t.Errorf("%s contents = %q; want %q", path, got, want) + } +} + +func documentationAssertPaths(t *testing.T, got, want []string) { + t.Helper() + got = slices.Clone(got) + want = slices.Clone(want) + slices.Sort(got) + slices.Sort(want) + if !slices.Equal(got, want) { + t.Errorf("updated files = %v; want %v (each exactly once)", got, want) + } +} diff --git a/pkg/goversion.go b/pkg/goversion.go index b43c82e..41ca984 100644 --- a/pkg/goversion.go +++ b/pkg/goversion.go @@ -47,6 +47,10 @@ type VersionOptions struct { BumpFiles []string // PostBumpScript runs after updates and before commit. A relative path is resolved within WorkDir. PostBumpScript string + // SkipDocs disables automatic documentation reference rewriting during major + // module-path migrations. It also omits those changes from dry-run reporting. + // Module paths, self-imports, BumpFiles, and PostBumpScript are unaffected. + SkipDocs bool } // normalizeVersion ensures the version string starts with a "v" if it's not "dev". @@ -309,17 +313,58 @@ func readCurrentVersionForModule(path, moduleDir string) (string, error) { // commits with a message equal to the new version (without the "v" prefix), // and then tags the commit with the same version prefixed by "v". func gitCommit(workDir, newVersion, tag string, extraFiles []string) error { - // Ensure that the version file is included. - files := extraFiles - - // Stage files. - addArgs := append([]string{"add"}, files...) - addCmd := exec.Command("git", addArgs...) - addCmd.Dir = workDir + // Updating tracked files separately handles documentation in ignored + // directories without force-adding any ignored, untracked build output. + root, err := gitRootDir(workDir) + if err != nil { + return err + } + list := exec.Command("git", "ls-files", "--cached", "--full-name", "-z") + list.Dir = workDir + out, err := list.Output() + if err != nil { + return fmt.Errorf("list tracked files: %w", err) + } + tracked := make(map[string]bool) + for _, name := range strings.Split(string(out), "\x00") { + if name != "" { + tracked[filepath.Join(root, filepath.FromSlash(name))] = true + } + } + var updates, additions []string + for _, file := range extraFiles { + absolute := file + if !filepath.IsAbs(absolute) { + absolute = filepath.Join(workDir, absolute) + } + absolute, err = filepath.Abs(absolute) + if err != nil { + return err + } + if tracked[absolute] { + updates = append(updates, file) + } else { + additions = append(additions, file) + } + } var stderr bytes.Buffer - addCmd.Stderr = &stderr - if err := addCmd.Run(); err != nil { - return fmt.Errorf("git add failed: %v, detail: %s", err, stderr.String()) + for i, files := range [][]string{updates, additions} { + if len(files) == 0 { + continue + } + args := []string{"add"} + if i == 0 { + args = append(args, "--update") + } + args = append(args, "--") + args = append(args, files...) + addCmd := exec.Command("git", args...) + addCmd.Dir = workDir + stderr.Reset() + addCmd.Stderr = &stderr + if err := addCmd.Run(); err != nil { + return fmt.Errorf("git add failed: %v, detail: %s", err, stderr.String()) + } } // Commit changes. @@ -416,12 +461,15 @@ func ModuleVersionTag(gitRoot, moduleDir, version string) (string, error) { // postBumpScript runs after file updates and before the commit with GOVERSION_OLD_VERSION and GOVERSION_NEW_VERSION in its environment. // // For a major bump to v2 or newer, Run updates the module path in go.mod and rewrites self-imports. +// It also updates unpinned self-references in Markdown files and Go comments, +// including documentation URLs, badges, and example imports. // Run requires unrelated worktree changes to be absent and returns metadata for the files it updates. func Run(versionFilePath, versionArg string, extraFiles []string, bumpFiles []string, postBumpScript string) (VersionMeta, error) { return runWithOptions(VersionOptions{VersionFile: versionFilePath, ExtraFiles: extraFiles, BumpFiles: bumpFiles, PostBumpScript: postBumpScript}, versionArg, false) } -// RunWithOptions applies a semantic version bump using repository-confined paths relative to options.WorkDir. +// RunWithOptions bumps a version using repository-confined paths relative to options.WorkDir. +// Set options.SkipDocs to leave automatic documentation references unchanged. func RunWithOptions(options VersionOptions, versionArg string) (VersionMeta, error) { return runWithOptions(options, versionArg, true) } @@ -543,6 +591,13 @@ func runWithOptions(options VersionOptions, versionArg string, confinePaths bool if err != nil { return meta, err } + if !options.SkipDocs { + docs, err := updateDocumentationReferences(modDir, oldModPath, newModPath, false) + if err != nil { + return meta, err + } + rewritten = uniquePaths(append(rewritten, docs...)) + } } // 6.7. Process bump files @@ -572,7 +627,7 @@ func runWithOptions(options VersionOptions, versionArg string, confinePaths bool } filesToCommit = append(filesToCommit, rewritten...) filesToCommit = append(filesToCommit, bumpedFiles...) - if err := gitCommit(workDir, meta.NewVersion, meta.Tag, filesToCommit); err != nil { + if err := gitCommit(workDir, meta.NewVersion, meta.Tag, uniquePaths(filesToCommit)); err != nil { return meta, err } @@ -581,18 +636,21 @@ func runWithOptions(options VersionOptions, versionArg string, confinePaths bool if meta.BumpType == "major" && hasGoMod { meta.UpdatedFiles = append([]string{filepath.Join(modDir, "go.mod")}, meta.UpdatedFiles...) } + meta.UpdatedFiles = uniquePaths(meta.UpdatedFiles) return meta, nil } // DryRun calculates a version bump without changing files or Git state. // -// It reports the resulting version and every file that Run would update, including versionFilePath, major-version module changes, rewritten self-imports, and bumpFiles. +// It reports the resulting version and every file that Run would update, including versionFilePath, +// major-version module changes, rewritten self-imports and documentation references, and bumpFiles. func DryRun(versionFilePath, versionArg string, bumpFiles []string) (VersionMeta, error) { return dryRunWithOptions(VersionOptions{VersionFile: versionFilePath, BumpFiles: bumpFiles}, versionArg, false) } // DryRunWithOptions calculates a bump using repository-confined paths relative to options.WorkDir without changing Git state. +// It honors options.SkipDocs when reporting files that would be updated. func DryRunWithOptions(options VersionOptions, versionArg string) (VersionMeta, error) { return dryRunWithOptions(options, versionArg, true) } @@ -660,8 +718,14 @@ func dryRunWithOptions(options VersionOptions, versionArg string, confinePaths b files = append(files, gomodPath) // Parse old module path - data, _ := os.ReadFile(gomodPath) - f, _ := modfile.Parse("go.mod", data, nil) + data, err := os.ReadFile(gomodPath) + if err != nil { + return meta, err + } + f, err := modfile.Parse("go.mod", data, nil) + if err != nil { + return meta, err + } oldMod := f.Module.Mod.Path // Compute new module path @@ -675,8 +739,17 @@ func dryRunWithOptions(options VersionOptions, versionArg string, confinePaths b } // Scan for all .go files needing import updates - if more, err := scanSelfImports(modDir, oldMod, newMod); err == nil { - files = append(files, more...) + more, err := scanSelfImports(modDir, oldMod, newMod) + if err != nil { + return meta, err + } + files = append(files, more...) + if !options.SkipDocs { + docs, err := updateDocumentationReferences(modDir, oldMod, newMod, true) + if err != nil { + return meta, err + } + files = append(files, docs...) } } @@ -687,7 +760,7 @@ func dryRunWithOptions(options VersionOptions, versionArg string, confinePaths b } } - meta.UpdatedFiles = files + meta.UpdatedFiles = uniquePaths(files) return meta, nil } @@ -940,18 +1013,19 @@ func checkUncommittedFiles(workDir string, allowed []string) error { return nil } -// scanSelfImports returns the list of .go files under modDir -// whose imports would be rewritten from oldMod → newMod. +// scanSelfImports returns eligible .go files owned by modDir whose imports +// would be rewritten from oldMod to newMod, using the shared Git-aware scan. func scanSelfImports(modDir, oldMod, newMod string) ([]string, error) { + if oldMod == newMod { + return nil, nil + } + excludedModules, err := nestedModulePaths(modDir) + if err != nil { + return nil, err + } var matches []string - err := filepath.WalkDir(modDir, func(path string, d fs.DirEntry, err error) error { - if err != nil || d.IsDir() { - if d != nil && d.IsDir() && d.Name() == "vendor" { - return filepath.SkipDir - } - return nil - } - if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { + err = walkModuleFiles(modDir, func(path string, _ fs.DirEntry) error { + if !strings.HasSuffix(path, ".go") { return nil } @@ -963,7 +1037,7 @@ func scanSelfImports(modDir, oldMod, newMod string) ([]string, error) { } for _, imp := range f.Imports { p, _ := strconv.Unquote(imp.Path.Value) - if strings.HasPrefix(p, oldMod) { + if matchesModulePath(p, oldMod) && !excludedModuleReference(p, excludedModules) { matches = append(matches, path) break } @@ -973,21 +1047,19 @@ func scanSelfImports(modDir, oldMod, newMod string) ([]string, error) { return matches, err } -// updateSelfImports walks all .go files under modDir, updating imports from oldMod to newMod. +// updateSelfImports updates imports from oldMod to newMod in eligible .go files +// owned by modDir, pruning Git-ignored trees and other modules. // Returns the list of files modified. func updateSelfImports(modDir, oldMod, newMod string) ([]string, error) { + if oldMod == newMod { + return nil, nil + } + excludedModules, err := nestedModulePaths(modDir) + if err != nil { + return nil, err + } var modified []string - err := filepath.WalkDir(modDir, func(path string, d fs.DirEntry, err error) error { - if err != nil { - return err - } - // Skip vendor directories - if d.IsDir() { - if d.Name() == "vendor" { - return filepath.SkipDir - } - return nil - } + err = walkModuleFiles(modDir, func(path string, _ fs.DirEntry) error { // Only consider .go files if !strings.HasSuffix(path, ".go") { return nil @@ -1005,7 +1077,7 @@ func updateSelfImports(modDir, oldMod, newMod string) ([]string, error) { if err != nil { continue } - if strings.HasPrefix(p, oldMod) { + if matchesModulePath(p, oldMod) && !excludedModuleReference(p, excludedModules) { newPath := strings.Replace(p, oldMod, newMod, 1) imp.Path.Value = strconv.Quote(newPath) changed = true diff --git a/pkg/module_files.go b/pkg/module_files.go new file mode 100644 index 0000000..13ce0a6 --- /dev/null +++ b/pkg/module_files.go @@ -0,0 +1,137 @@ +package goversion + +import ( + "fmt" + "io/fs" + "os" + "os/exec" + "path/filepath" + "strings" + + "golang.org/x/mod/modfile" + "golang.org/x/mod/module" +) + +// moduleScanPaths asks Git for tracked and nonignored untracked files, rather +// than enumerating ignored content. Ancestor entries let the walker prune whole +// directories before reading them while retaining tracked files and exceptions. +// A nil set means the directory is outside Git and filesystem discovery applies. +func moduleScanPaths(modDir string) (map[string]bool, error) { + if _, err := gitRootDir(modDir); err != nil { + return nil, nil + } + cmd := exec.Command("git", "ls-files", "--cached", "--others", "--exclude-standard", "-z") + cmd.Dir = modDir + out, err := cmd.Output() + if err != nil { + return nil, fmt.Errorf("list module scan files: %w", err) + } + paths := map[string]bool{modDir: true} + for _, name := range strings.Split(string(out), "\x00") { + if name == "" { + continue + } + path := filepath.Join(modDir, filepath.FromSlash(name)) + for !paths[path] { + paths[path] = true + parent := filepath.Dir(path) + if parent == path { + break + } + path = parent + } + } + return paths, nil +} + +// walkModuleFiles visits regular files owned by this module. Git-ineligible +// directories are pruned before descent; nested modules, vendor, Git internals, +// and symlinks are excluded regardless of tracking status. +func walkModuleFiles(modDir string, visit func(string, fs.DirEntry) error) error { + return walkModuleTree(modDir, visit, nil) +} + +// walkModuleTree reports module boundaries without descending into them. +// File and boundary callbacks are optional so discovery can collect identities +// before a rewriting pass visits any parent-module references. +func walkModuleTree(modDir string, visit func(string, fs.DirEntry) error, visitModule func(string) error) error { + modDir = filepath.Clean(modDir) + paths, err := moduleScanPaths(modDir) + if err != nil { + return err + } + return filepath.WalkDir(modDir, func(path string, entry fs.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + if entry.IsDir() { + if path != modDir { + if entry.Name() == ".git" || entry.Name() == "vendor" || (paths != nil && !paths[path]) { + return filepath.SkipDir + } + if fileExists(filepath.Join(path, "go.mod")) { + if visitModule != nil { + if err := visitModule(filepath.Join(path, "go.mod")); err != nil { + return err + } + } + return filepath.SkipDir + } + } + return nil + } + if !entry.Type().IsRegular() || (paths != nil && !paths[path]) { + return nil + } + if visit != nil { + return visit(path, entry) + } + return nil + }) +} + +// nestedModulePaths collects declared child module families, not directory names. +// Their paths remain independent of the parent's major-version migration. +func nestedModulePaths(modDir string) ([]string, error) { + var paths []string + err := walkModuleTree(modDir, nil, func(filename string) error { + info, err := os.Lstat(filename) + if err != nil { + return err + } + if !info.Mode().IsRegular() { + return nil + } + data, err := os.ReadFile(filename) + if err != nil { + return err + } + declared := modfile.ModulePath(data) + if declared == "" { + return fmt.Errorf("missing module path in %s", filename) + } + base, _, ok := module.SplitPathVersion(declared) + if !ok { + return fmt.Errorf("invalid module path %q in %s", declared, filename) + } + paths = append(paths, base) + return nil + }) + return uniquePaths(paths), err +} + +// matchesModulePath uses a path boundary so sibling modules with a shared text +// prefix (such as repo-tools) do not become self-references. +func matchesModulePath(path, modulePath string) bool { + return path == modulePath || strings.HasPrefix(path, modulePath+"/") +} + +// excludedModuleReference protects a nested module and all of its major versions. +func excludedModuleReference(path string, excludedModules []string) bool { + for _, modulePath := range excludedModules { + if matchesModulePath(path, modulePath) { + return true + } + } + return false +} diff --git a/pkg/module_files_test.go b/pkg/module_files_test.go new file mode 100644 index 0000000..ee294af --- /dev/null +++ b/pkg/module_files_test.go @@ -0,0 +1,275 @@ +package goversion + +import ( + "errors" + "io/fs" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +const moduleFilesOld = "example.com/acme/widget" +const moduleFilesNew = moduleFilesOld + "/v2" + +type moduleFilesFixture struct { + dir string + before map[string]string + eligible []string + imports []string + docs []string + links []string +} + +func newModuleFilesFixture(t *testing.T, git, nested bool) moduleFilesFixture { + t.Helper() + root := t.TempDir() + if git { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git is not available") + } + gitRun(t, root, "init") + } else { + cmd := exec.Command("git", "rev-parse", "--show-toplevel") + cmd.Dir = root + if err := cmd.Run(); err == nil { + t.Fatal("filesystem fallback fixture unexpectedly belongs to a Git repository") + } + } + dir := root + if nested { + dir = filepath.Join(root, "tools", "widget") + documentationWrite(t, filepath.Join(root, "sibling.go"), "not Go source\n") + documentationWrite(t, filepath.Join(root, "go.mod"), "module example.com/acme/repo\n") + } + f := moduleFilesFixture{dir: dir, before: make(map[string]string)} + write := func(name, content string) { + path := filepath.Join(dir, filepath.FromSlash(name)) + documentationWrite(t, path, content) + f.before[path] = content + } + write("go.mod", "module "+moduleFilesOld+"\n\ngo 1.23\n") + f.eligible = append(f.eligible, filepath.Join(dir, "go.mod")) + prefixes := []string{"src", "untracked/deep", "web/node_modules/package", "space and\nnewline"} + if git { + write(".gitignore", "/node_modules/\n/generated/*\n!/generated/keep/\n/artifacts/\n") + f.eligible = append(f.eligible, filepath.Join(dir, ".gitignore")) + prefixes = append(prefixes, "node_modules/tracked/deep", "generated/tracked/deep", "generated/keep/deep") + } else { + // Ignore rules have no effect outside Git, including for node_modules. + write(".gitignore", "node_modules/\ngenerated/\n") + f.eligible = append(f.eligible, filepath.Join(dir, ".gitignore")) + prefixes = append(prefixes, "node_modules/package", "generated/deep") + } + for _, prefix := range prefixes { + goName := prefix + "/consumer.go" + mdName := prefix + "/README.markdown" + write(goName, "// Package widget uses "+moduleFilesOld+".\npackage widget\n\nimport _ \""+moduleFilesOld+"/client\"\n") + write(mdName, "go get "+moduleFilesOld+"/client\n") + goPath, mdPath := filepath.Join(dir, goName), filepath.Join(dir, mdName) + f.eligible = append(f.eligible, goPath, mdPath) + f.imports = append(f.imports, goPath) + f.docs = append(f.docs, goPath, mdPath) + } + write("notes.txt", moduleFilesOld) + f.eligible = append(f.eligible, filepath.Join(dir, "notes.txt")) + write("nested/go.mod", "module example.com/other\n") + excluded := []string{"vendor/dependency", "nested/deep", ".git/walker-fixture", "deep/.git", "deep/vendor", "deep/nested"} + write("deep/nested/go.mod", "module example.com/other/deep\n") + if git { + excluded = append(excluded, "node_modules/broken/deep", "generated/discard/deep", "artifacts/arbitrary/deep") + } + for _, prefix := range excluded { + write(prefix+"/broken.go", "not valid Go source\n") + write(prefix+"/consumer.go", "package excluded\nimport _ \""+moduleFilesOld+"/client\"\n") + write(prefix+"/README.md", moduleFilesOld+"\n") + } + outside := t.TempDir() + for name, content := range map[string]string{ + "consumer.go": "package external\nimport _ \"" + moduleFilesOld + "/client\"\n", + "README.md": moduleFilesOld + "\n", + } { + path := filepath.Join(outside, name) + documentationWrite(t, path, content) + f.before[path] = content + } + for name, target := range map[string]string{ + "linked.go": filepath.Join(outside, "consumer.go"), + "linked.md": filepath.Join(outside, "README.md"), + "linked-dir": outside, + "internal-link.go": filepath.Join(dir, "src", "consumer.go"), + "broken-link.go": filepath.Join(outside, "missing.go"), + } { + path := filepath.Join(dir, name) + if err := os.Symlink(target, path); err != nil { + t.Fatal(err) + } + f.links = append(f.links, path) + } + if git { + // Index entries must remain eligible even though their directories are ignored. + gitRun(t, dir, "add", "-f", "--", "go.mod", ".gitignore", "src", "node_modules/tracked", "generated/tracked", "vendor", "nested", "deep/vendor", "deep/nested", "linked.go", "linked.md", "linked-dir", "internal-link.go", "broken-link.go") + } + return f +} + +func (f moduleFilesFixture) assertUnchanged(t *testing.T) { + t.Helper() + for path, content := range f.before { + documentationAssertContent(t, path, content) + } +} + +func TestWalkModuleFilesEligibility(t *testing.T) { + for _, tc := range []struct { + name string + git bool + nested bool + }{ + {"git root", true, false}, + {"module below git root", true, true}, + {"outside git", false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newModuleFilesFixture(t, tc.git, tc.nested) + var got []string + err := walkModuleFiles(f.dir, func(path string, entry fs.DirEntry) error { + if entry.Type()&os.ModeSymlink != 0 { + t.Errorf("visitor received symlink %s", path) + } + if !entry.IsDir() { + got = append(got, path) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + documentationAssertPaths(t, got, f.eligible) + f.assertUnchanged(t) + }) + } +} + +func TestWalkModuleFilesPropagatesErrors(t *testing.T) { + t.Run("visitor", func(t *testing.T) { + f := newModuleFilesFixture(t, true, false) + wantErr := errors.New("visitor stopped") + calls := 0 + err := walkModuleFiles(f.dir, func(_ string, entry fs.DirEntry) error { + if entry.IsDir() { + return nil + } + calls++ + return wantErr + }) + if !errors.Is(err, wantErr) { + t.Fatalf("error = %v; want visitor error %v", err, wantErr) + } + if calls != 1 { + t.Errorf("file visitor called %d times; want 1", calls) + } + }) + t.Run("missing root", func(t *testing.T) { + err := walkModuleFiles(filepath.Join(t.TempDir(), "missing"), func(string, fs.DirEntry) error { + t.Error("visitor called for missing root") + return nil + }) + if !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("error = %v; want fs.ErrNotExist", err) + } + }) +} + +func TestWalkModuleFilesPrunesIgnoredDirectoriesBeforeReading(t *testing.T) { + f := newModuleFilesFixture(t, true, false) + blocked := filepath.Join(f.dir, "artifacts") + if err := os.Chmod(blocked, 0); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := os.Chmod(blocked, 0o755); err != nil { + t.Error(err) + } + }) + if _, err := os.ReadDir(blocked); err == nil { + t.Skip("process can read mode-000 directories; cannot verify pre-descent pruning") + } else if !errors.Is(err, fs.ErrPermission) { + t.Fatal(err) + } + var got []string + err := walkModuleFiles(f.dir, func(path string, entry fs.DirEntry) error { + if !entry.IsDir() { + got = append(got, path) + } + return nil + }) + if err != nil { + t.Fatalf("walk descended into ignored unreadable directory: %v", err) + } + documentationAssertPaths(t, got, f.eligible) +} + +func TestModuleFilesScannerParity(t *testing.T) { + for _, git := range []bool{true, false} { + name := "outside git" + if git { + name = "git" + } + t.Run(name, func(t *testing.T) { + for _, scanner := range []string{"imports", "documentation"} { + t.Run(scanner, func(t *testing.T) { + f := newModuleFilesFixture(t, git, git) + var dry, wet []string + var err error + want := f.imports + if scanner == "imports" { + dry, err = scanSelfImports(f.dir, moduleFilesOld, moduleFilesNew) + } else { + want = f.docs + dry, err = updateDocumentationReferences(f.dir, moduleFilesOld, moduleFilesNew, true) + } + if err != nil { + t.Fatalf("dry scan: %v", err) + } + documentationAssertPaths(t, dry, want) + f.assertUnchanged(t) + if scanner == "imports" { + wet, err = updateSelfImports(f.dir, moduleFilesOld, moduleFilesNew) + } else { + wet, err = updateDocumentationReferences(f.dir, moduleFilesOld, moduleFilesNew, false) + } + if err != nil { + t.Fatalf("wet scan parsed an excluded file or failed: %v", err) + } + documentationAssertPaths(t, wet, want) + documentationAssertPaths(t, wet, dry) + changed := make(map[string]bool) + for _, path := range want { + changed[path] = true + } + for path, before := range f.before { + expected := before + if changed[path] { + if scanner == "imports" { + expected = strings.ReplaceAll(before, "\""+moduleFilesOld+"/client\"", "\""+moduleFilesNew+"/client\"") + } else if strings.HasSuffix(path, ".go") { + expected = strings.ReplaceAll(before, "// Package widget uses "+moduleFilesOld+".", "// Package widget uses "+moduleFilesNew+".") + } else { + expected = strings.ReplaceAll(before, moduleFilesOld, moduleFilesNew) + } + } + documentationAssertContent(t, path, expected) + } + for _, path := range f.links { + info, err := os.Lstat(path) + if err != nil || info.Mode()&os.ModeSymlink == 0 { + t.Errorf("symlink %s changed: %v", path, err) + } + } + }) + } + }) + } +} diff --git a/pkg/nested_references_test.go b/pkg/nested_references_test.go new file mode 100644 index 0000000..a105e14 --- /dev/null +++ b/pkg/nested_references_test.go @@ -0,0 +1,240 @@ +package goversion + +import ( + "go/format" + "os" + "path/filepath" + "strings" + "testing" +) + +const nestedReferencesParent = "example.com/repo" + +var nestedReferencesCases = []struct { + name, directory, module string +}{ + {"matching directory", "tools", "example.com/repo/tools"}, + {"declared path differs from directory", "internal/buildkit", "example.com/repo/tools"}, + {"versioned child family", "tools", "example.com/repo/tools/v2"}, +} + +// Exercise discovery through the scan/update APIs rather than supplying an +// exclusion list: the boundary's module declaration must determine ownership. +func TestNestedReferencesDocumentation(t *testing.T) { + for _, tc := range nestedReferencesCases { + t.Run(tc.name, func(t *testing.T) { + dir, before, after := nestedReferencesFixture(t, tc.directory, tc.module) + want := nestedReferencesPaths(dir, "mixed.md", "doc.go") + for _, dry := range []bool{true, false} { + got, err := updateDocumentationReferences(dir, nestedReferencesParent, nestedReferencesParent+"/v2", dry) + if err != nil { + t.Fatal(err) + } + documentationAssertPaths(t, got, want) + for name, content := range before { + if !dry && (name == "mixed.md" || name == "doc.go") { + content = after[name] + } + documentationAssertContent(t, filepath.Join(dir, name), content) + } + } + }) + } +} + +func TestNestedReferencesImports(t *testing.T) { + for _, tc := range nestedReferencesCases { + t.Run(tc.name, func(t *testing.T) { + dir, before, after := nestedReferencesFixture(t, tc.directory, tc.module) + want := nestedReferencesPaths(dir, "consumer.go", "consumer_test.go") + got, err := scanSelfImports(dir, nestedReferencesParent, nestedReferencesParent+"/v2") + if err != nil { + t.Fatal(err) + } + documentationAssertPaths(t, got, want) + for name, content := range before { + documentationAssertContent(t, filepath.Join(dir, name), content) + } + got, err = updateSelfImports(dir, nestedReferencesParent, nestedReferencesParent+"/v2") + if err != nil { + t.Fatal(err) + } + documentationAssertPaths(t, got, want) + for name, content := range before { + if name == "consumer.go" || name == "consumer_test.go" { + nestedReferencesAssertGo(t, filepath.Join(dir, name), after[name]) + } else { + documentationAssertContent(t, filepath.Join(dir, name), content) + } + } + + }) + } +} + +func TestNestedReferencesMajorIntegration(t *testing.T) { + for _, tc := range nestedReferencesCases { + t.Run(tc.name, func(t *testing.T) { + dir, before, after := nestedReferencesFixture(t, tc.directory, tc.module) + gitRun(t, dir, "init") + gitRun(t, dir, "config", "user.email", "test@example.com") + gitRun(t, dir, "config", "user.name", "Test User") + gitRun(t, dir, "add", ".") + gitRun(t, dir, "commit", "-m", "nested reference fixture") + for _, name := range []string{"go.mod", "README.md", "child.go", "child_test.go"} { + path := filepath.ToSlash(filepath.Join(tc.directory, name)) + if got := gitOutput(t, dir, "--no-pager", "ls-files", "--", path); strings.TrimSpace(got) != path { + t.Fatalf("nested fixture is not tracked: %s (%q)", path, got) + } + } + head := gitOutput(t, dir, "--no-pager", "rev-parse", "HEAD") + want := nestedReferencesPaths(dir, "go.mod", "version.go", "mixed.md", "doc.go", "consumer.go", "consumer_test.go") + options := VersionOptions{WorkDir: dir} + dry, err := DryRunWithOptions(options, "major") + if err != nil { + t.Fatal(err) + } + documentationAssertPaths(t, dry.UpdatedFiles, want) + for name, content := range before { + documentationAssertContent(t, filepath.Join(dir, name), content) + } + if got := gitOutput(t, dir, "--no-pager", "rev-parse", "HEAD"); got != head { + t.Error("DryRun changed HEAD") + } + if got := gitOutput(t, dir, "--no-pager", "tag", "--list"); got != "" { + t.Errorf("DryRun created tags: %s", got) + } + if got := gitOutput(t, dir, "--no-pager", "status", "--porcelain"); got != "" { + t.Errorf("DryRun changed worktree/index: %s", got) + } + wet, err := RunWithOptions(options, "major") + if err != nil { + t.Fatal(err) + } + documentationAssertPaths(t, wet.UpdatedFiles, want) + if dry.Tag != "v2.0.0" || wet.Tag != dry.Tag || wet.NewVersion != dry.NewVersion { + t.Errorf("unexpected metadata: dry=%+v wet=%+v", dry, wet) + } + for name, content := range after { + path := filepath.Join(dir, name) + if name == "consumer.go" || name == "consumer_test.go" { + nestedReferencesAssertGo(t, path, content) + } else if name == "version.go" { + version, err := readCurrentVersion(path) + if err != nil || normalizeVersion(version) != "v2.0.0" { + t.Errorf("version = %q, err = %v; want v2.0.0", version, err) + } + } else { + documentationAssertContent(t, path, content) + } + committed := gitOutput(t, dir, "--no-pager", "show", wet.Tag+":"+filepath.ToSlash(name)) + documentationAssertContent(t, path, committed) + } + if got := gitOutput(t, dir, "--no-pager", "status", "--porcelain"); got != "" { + t.Errorf("Run left worktree/index dirty: %s", got) + } + }) + } +} + +func nestedReferencesFixture(t *testing.T, childDir, childModule string) (string, map[string]string, map[string]string) { + t.Helper() + dir := t.TempDir() + const old = nestedReferencesParent + const next = old + "/v2" + // A /v2 declaration protects the entire child family, not just /v2. + var protected strings.Builder + for _, module := range []string{old + "/tools", old + "/tools/v2", old + "/tools/v3", old + "/tools/v20", old + "-tools"} { + protected.WriteString(nestedReferencesDocumentation(module)) + } + own := nestedReferencesDocumentation(old) + updatedOwn := nestedReferencesDocumentation(next) + // Similar package names are still parent-owned, not part of the child family. + own += old + "/toolshed/pkg\n" + old + "/tools-extra/pkg\n" + updatedOwn += next + "/toolshed/pkg\n" + next + "/tools-extra/pkg\n" + // The physical directory is not the module's import path. + if childDir != "tools" { + own += old + "/" + filepath.ToSlash(childDir) + "/pkg\n" + updatedOwn += next + "/" + filepath.ToSlash(childDir) + "/pkg\n" + } + runtime := "const RuntimePath = \"" + old + "/pkg\"\nconst RuntimeDocs = `https://pkg.go.dev/" + old + "#Overview`\n" + doc := "// Package repo references " + old + " and " + old + "/tools.\npackage repo\n\n/*\n" + protected.String() + own + "*/\n" + runtime + updatedDoc := "// Package repo references " + next + " and " + old + "/tools.\npackage repo\n\n/*\n" + protected.String() + updatedOwn + "*/\n" + runtime + protectedImports := "" + for _, path := range []string{old + "/tools", old + "/tools/pkg", old + "/tools/v2/pkg", old + "/tools/v3/pkg", old + "/tools/v20/pkg", old + "-tools/pkg"} { + protectedImports += "import _ \"" + path + "\"\n" + } + before := map[string]string{ + "go.mod": "module " + old + "\n\ngo 1.23\n", + "version.go": "package repo\n\nvar Version = \"1.9.0\"\n", + "README.md": protected.String(), + "mixed.md": protected.String() + own, + "doc.go": doc, + "protected.go": "package repo\n\n" + protectedImports, + "protected_test.go": "package repo_test\n\n" + protectedImports, + "consumer.go": "package repo\n\n" + protectedImports + "import _ \"" + old + "\"\nimport _ \"" + old + "/pkg\"\nimport _ \"" + old + "/toolshed/pkg\"\n\n" + runtime, + "consumer_test.go": "package repo_test\n\n" + protectedImports + "import _ \"" + old + "/pkg\"\n\n" + runtime, + filepath.Join(childDir, "go.mod"): "module " + childModule + "\n\ngo 1.23\n", + filepath.Join(childDir, "README.md"): own + protected.String(), + filepath.Join(childDir, "child.go"): "// Package tools uses " + old + "/pkg.\npackage tools\n\nimport _ \"" + old + "/pkg\"\n", + filepath.Join(childDir, "child_test.go"): "package tools_test\n\nimport _ \"" + old + "/pkg\"\n", + } + after := make(map[string]string, len(before)) + for name, content := range before { + documentationWrite(t, filepath.Join(dir, name), content) + after[name] = content + } + after["go.mod"] = "module " + next + "\n\ngo 1.23\n" + after["mixed.md"] = protected.String() + updatedOwn + after["doc.go"] = updatedDoc + for _, name := range []string{"consumer.go", "consumer_test.go"} { + content := before[name] + for _, suffix := range []string{"", "/pkg", "/toolshed/pkg"} { + content = strings.ReplaceAll(content, "import _ \""+old+suffix+"\"", "import _ \""+next+suffix+"\"") + } + after[name] = content + } + return dir, before, after +} + +func nestedReferencesDocumentation(module string) string { + return strings.Join([]string{ + module, module + "/pkg", "go get " + module + "@latest", + "go install " + module + "/cmd/tool@latest", + "[API](https://pkg.go.dev/" + module + "#Overview)", + "https://pkg.go.dev/" + module + "@latest/pkg?tab=doc#Symbol", + "https://pkg.go.dev/" + module + "/pkg@latest#Symbol", + "https://godoc.org/" + module + "/pkg?status.svg#Symbol", + "https://godoc.org/" + module + "@latest/pkg#Symbol", + "![docs](https://pkg.go.dev/badge/" + module + ".svg?status=ok#badge)", + "https://pkg.go.dev/badge/" + module + "@latest.svg#badge", + "https://pkg.go.dev/badge/" + module + "/pkg.svg#badge", + }, "\n") + "\n" +} + +func nestedReferencesPaths(dir string, names ...string) []string { + paths := make([]string, len(names)) + for i, name := range names { + paths[i] = filepath.Join(dir, name) + } + return paths +} + +func nestedReferencesAssertGo(t *testing.T, path, want string) { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + got, err := format.Source(data) + if err != nil { + t.Fatal(err) + } + expected, err := format.Source([]byte(want)) + if err != nil { + t.Fatal(err) + } + if string(got) != string(expected) { + t.Errorf("%s contents after gofmt:\n%s\nwant:\n%s", path, got, expected) + } +} diff --git a/pkg/skip_docs_test.go b/pkg/skip_docs_test.go new file mode 100644 index 0000000..8f95887 --- /dev/null +++ b/pkg/skip_docs_test.go @@ -0,0 +1,71 @@ +package goversion + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestSkipDocsPreservesExplicitBumpsAndHooks(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("fixture uses a shell post-bump hook") + } + const old = "example.com/acme/repo/tools/widget" + root, dir := initNestedModuleRepo(t, old, "1.9.0") + readme := filepath.Join(dir, "README.md") + bumpFile := filepath.Join(dir, "release.md") + hookFile := filepath.Join(dir, "hook.md") + consumer := filepath.Join(dir, "consumer.go") + goDoc := filepath.Join(dir, "doc.go") + script := filepath.Join(dir, "hook.sh") + original := map[string]string{ + readme: "https://pkg.go.dev/" + old + "#Client\n", + bumpFile: "Version 1.9.0\nhttps://pkg.go.dev/" + old + "\n", + hookFile: "before hook\n", + consumer: "package widget\nimport _ \"" + old + "/client\"\n// See " + old + ".\n", + goDoc: "// Package widget: https://pkg.go.dev/" + old + "\npackage widget\n", + script: "#!/bin/sh\nprintf 'hook ran\\n' > hook.md\n", + } + for path, content := range original { + documentationWrite(t, path, content) + } + if err := os.Chmod(script, 0o755); err != nil { + t.Fatal(err) + } + gitRun(t, root, "add", ".") + gitRun(t, root, "commit", "-m", "add skip-docs fixtures") + options := VersionOptions{ + WorkDir: dir, SkipDocs: true, + BumpFiles: []string{"release.md"}, ExtraFiles: []string{"hook.md"}, PostBumpScript: "hook.sh", + } + dry, err := DryRunWithOptions(options, "major") + if err != nil { + t.Fatal(err) + } + wantPaths := []string{filepath.Join(dir, "go.mod"), filepath.Join(dir, "version.go"), consumer, bumpFile} + documentationAssertPaths(t, dry.UpdatedFiles, wantPaths) + for path, content := range original { + documentationAssertContent(t, path, content) + } + wet, err := RunWithOptions(options, "major") + if err != nil { + t.Fatal(err) + } + documentationAssertPaths(t, wet.UpdatedFiles, wantPaths) + documentationAssertContent(t, readme, original[readme]) + documentationAssertContent(t, goDoc, original[goDoc]) + documentationAssertContent(t, bumpFile, strings.Replace(original[bumpFile], "1.9.0", "2.0.0", 1)) + documentationAssertContent(t, hookFile, "hook ran\n") + data, err := os.ReadFile(consumer) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(data), "\""+old+"/v2/client\"") || !strings.Contains(string(data), "// See "+old+".") { + t.Fatalf("expected updated import and unchanged comment: %s", data) + } + if status := gitOutput(t, root, "--no-pager", "status", "--porcelain"); status != "" { + t.Fatalf("uncommitted changes: %s", status) + } +} diff --git a/version_cli.go b/version_cli.go index 7978258..58a5406 100644 --- a/version_cli.go +++ b/version_cli.go @@ -35,6 +35,7 @@ func runVersionCommand(arguments []string, output, errorOutput io.Writer) int { flags.Var(&bumpFiles, "bump-file", "Additional file to scan for first semver and bump it. May be repeated.") postBump := flags.String("post-bump", "", "Script to execute after version bump but before git commit. Receives GOVERSION_OLD_VERSION and GOVERSION_NEW_VERSION env vars.") dryRun := flags.Bool("dry", false, "Perform a dry run without modifying any files or git repository") + skipDocs := flags.Bool("skip-docs", false, "Skip automatic documentation path updates; module paths, self-imports, bump files, and hooks are unaffected") showVersion := flags.Bool("version", false, "Show CLI version and exit") help := flags.Bool("help", false, "Show help message and exit") flags.Usage = func() { printVersionUsage(flags.Output(), flags) } @@ -79,6 +80,7 @@ func runVersionCommand(arguments []string, output, errorOutput io.Writer) int { ExtraFiles: extraFiles, BumpFiles: bumpFiles, PostBumpScript: *postBump, + SkipDocs: *skipDocs, } if *dryRun { meta, err = goversion.DryRunWithOptions(options, flags.Arg(0)) @@ -118,10 +120,12 @@ func printVersionUsage(output io.Writer, flags *flag.FlagSet) { goversion [options] Bumps the version in a Go source file (default: ./version.go), commits the change with the version string (no "v" prefix), -and tags the commit with the version prefixed with "v". For major version bumps >= v2, go.mod and all self references are also updated. +and tags the commit with the version prefixed with "v". For major version bumps >= v2, go.mod and self-imports are also updated. +Documentation references are updated unless -skip-docs is set. Examples: goversion minor + goversion -skip-docs major goversion 1.2.3 goversion -workdir tools/widget patch goversion -bump-file docs/version.txt patch diff --git a/version_skip_docs_test.go b/version_skip_docs_test.go new file mode 100644 index 0000000..b24fd93 --- /dev/null +++ b/version_skip_docs_test.go @@ -0,0 +1,175 @@ +package main + +import ( + "bytes" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +func TestVersionSkipDocsHelp(t *testing.T) { + out, err := runCLI([]string{"-help"}) + if err != nil { + t.Fatalf("help failed: %v\n%s", err, out) + } + if !strings.Contains(out, "-skip-docs") { + t.Errorf("help missing -skip-docs:\n%s", out) + } +} + +func TestVersionSkipDocsWorkdir(t *testing.T) { + runners := []struct { + name string + run func([]string) (string, error) + }{ + {"runCLI", func(args []string) (string, error) { return runCLI(args) }}, + {"runVersionCommand", func(args []string) (string, error) { + var output, errorOutput bytes.Buffer + if code := runVersionCommand(args, &output, &errorOutput); code != 0 { + return output.String(), fmt.Errorf("exit code %d: %s", code, errorOutput.String()) + } + return output.String(), nil + }}, + } + for _, runner := range runners { + t.Run(runner.name, func(t *testing.T) { + for _, tc := range []struct { + name string + skipDocs bool + dry bool + }{ + {"skipDocsDry", true, true}, + {"skipDocsReal", true, false}, + {"defaultUpdatesDocs", false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + dir, before := newVersionSkipDocsFixture(t) + head := versionSkipDocsGit(t, dir, "rev-parse", "HEAD") + args := []string{"-workdir", dir} + if tc.skipDocs { + args = append(args, "-skip-docs") + } + if tc.dry { + args = append(args, "-dry") + } + args = append(args, "major") + out, err := runner.run(args) + if err != nil { + t.Fatalf("major bump failed: %v\n%s", err, out) + } + for _, want := range []string{"Old Version: 1.2.3", "New Version: 2.0.0", "Tag: v2.0.0"} { + if !strings.Contains(out, want) { + t.Errorf("output missing %q:\n%s", want, out) + } + } + heading := "Files updated:\n" + if tc.dry { + heading = "Files that would be updated:\n" + } + _, files, found := strings.Cut(out, heading) + if !found { + t.Fatalf("output missing %q:\n%s", heading, out) + } + listed := make(map[string]bool) + for _, line := range strings.Split(strings.TrimSpace(files), "\n") { + listed[filepath.Base(strings.TrimSpace(line))] = true + } + for _, name := range []string{"version.go", "go.mod", "consumer.go", "README.md", "doc.go"} { + want := !tc.skipDocs || (name != "README.md" && name != "doc.go") + if listed[name] != want { + t.Errorf("updated file list contains %s = %v, want %v:\n%s", name, listed[name], want, out) + } + } + for name, original := range before { + want := original + if !tc.dry { + switch name { + case "version.go": + want = strings.ReplaceAll(original, "1.2.3", "2.0.0") + case "go.mod": + want = strings.ReplaceAll(original, versionSkipDocsModule, versionSkipDocsModule+"/v2") + case "consumer.go": + want = strings.Replace(original, `import _ "`+versionSkipDocsModule+`/client"`, `import _ "`+versionSkipDocsModule+`/v2/client"`, 1) + } + if !tc.skipDocs && (name == "README.md" || name == "doc.go" || name == "consumer.go") { + want = strings.ReplaceAll(original, versionSkipDocsModule, versionSkipDocsModule+"/v2") + } + } + got, err := os.ReadFile(filepath.Join(dir, name)) + if err != nil { + t.Fatal(err) + } + if string(got) != want { + t.Errorf("%s contents:\ngot:\n%s\nwant:\n%s", name, got, want) + } + } + if status := versionSkipDocsGit(t, dir, "status", "--porcelain"); status != "" { + t.Errorf("working tree is dirty: %s", status) + } + if tc.dry { + if got := versionSkipDocsGit(t, dir, "rev-parse", "HEAD"); got != head { + t.Errorf("dry run changed HEAD: %s -> %s", head, got) + } + if tags := versionSkipDocsGit(t, dir, "tag", "--list"); tags != "" { + t.Errorf("dry run created tags: %s", tags) + } + } else { + if tag := versionSkipDocsGit(t, dir, "rev-parse", "v2.0.0^{commit}"); tag != versionSkipDocsGit(t, dir, "rev-parse", "HEAD") || tag == head { + t.Errorf("version tag does not identify a new HEAD commit: %s", tag) + } + } + }) + } + }) + } +} + +const versionSkipDocsModule = "example.com/acme/widget" + +func newVersionSkipDocsFixture(t *testing.T) (string, map[string]string) { + t.Helper() + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git is not available") + } + dir := t.TempDir() + before := map[string]string{ + "go.mod": "module " + versionSkipDocsModule + "\n\ngo 1.23\n", + "version.go": "package widget\n\nvar (\n\tVersion = \"1.2.3\"\n)\n", + "README.md": "# Widget\n\ngo get " + versionSkipDocsModule + "\n\nhttps://pkg.go.dev/" + versionSkipDocsModule + "#Overview\n", + "doc.go": "// Package widget uses " + versionSkipDocsModule + ".\npackage widget\n\n/* See https://pkg.go.dev/" + versionSkipDocsModule + "/client. */\n", + "consumer.go": "package widget\n\n// See https://pkg.go.dev/" + versionSkipDocsModule + "/client.\nimport _ \"" + versionSkipDocsModule + "/client\"\t// " + versionSkipDocsModule + "/client\n\n/* Install with go get " + versionSkipDocsModule + ". */\n", + "client/client.go": "package client\n", + } + for name, content := range before { + path := filepath.Join(dir, name) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + versionSkipDocsGit(t, dir, "init") + versionSkipDocsGit(t, dir, "config", "user.email", "test@example.com") + versionSkipDocsGit(t, dir, "config", "user.name", "Test User") + versionSkipDocsGit(t, dir, "config", "commit.gpgsign", "false") + versionSkipDocsGit(t, dir, "config", "tag.gpgsign", "false") + versionSkipDocsGit(t, dir, "add", ".") + versionSkipDocsGit(t, dir, "commit", "-m", "initial") + return dir, before +} + +func versionSkipDocsGit(t *testing.T, dir string, args ...string) string { + t.Helper() + cmd := exec.Command("git", append([]string{"--no-pager"}, args...)...) + cmd.Dir = dir + cmd.Env = append(os.Environ(), "GIT_EDITOR=true") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + return strings.TrimSpace(string(out)) +}