package doccheck import ( "encoding/json" "fmt" "os" "path/filepath" "reflect" "regexp" "strings" "testing" "gopkg.in/yaml.v3" ) var markdownLinkPattern = regexp.MustCompile(`\[[^\]]+\]\(([^)]+)\)`) var markdownBackticks = regexp.MustCompile("`+") // documentationLinks excludes literal examples enclosed by matching backtick // runs before applying the existing lightweight link check. func documentationLinks(markdown string) [][]string { runs := markdownBackticks.FindAllStringIndex(markdown, -1) text := []byte(markdown) for i := 0; i < len(runs); i++ { width := runs[i][1] - runs[i][0] for j := i + 1; j < len(runs); j++ { if runs[j][1]-runs[j][0] != width { continue } for k := runs[i][0]; k < runs[j][1]; k++ { text[k] = ' ' } i = j break } } return markdownLinkPattern.FindAllStringSubmatch(string(text), -1) } func TestDocumentationLinksIgnoreCodeExamples(t *testing.T) { for _, example := range []string{ "`[Source](COMMIT_URL).`", "``[Source](COMMIT_URL) with a ` character``", "```markdown\n[Source](COMMIT_URL)\n```", } { t.Run(example, func(t *testing.T) { matches := documentationLinks("[before](before.md) " + example + " [after](after.md)") if len(matches) != 2 || matches[0][1] != "before.md" || matches[1][1] != "after.md" { t.Fatalf("links = %#v, want only the surrounding real links", matches) } }) } if matches := documentationLinks("unmatched ` [real](real.md)"); len(matches) != 1 || matches[0][1] != "real.md" { t.Fatalf("unmatched backtick hid a real link: %#v", matches) } } func TestDocumentationLinksResolve(t *testing.T) { root := repositoryRoot(t) for _, path := range []string{ filepath.Join(root, "README.md"), filepath.Join(root, "docs"), filepath.Join(root, "examples"), } { walkDocumentationLinks(t, root, path) } } func TestWoodpeckerWorkflowDependencies(t *testing.T) { root := repositoryRoot(t) paths, err := filepath.Glob(filepath.Join(root, ".woodpecker", "*.yml")) if err != nil { t.Fatalf("list Woodpecker workflows: %v", err) } if len(paths) == 0 { t.Fatal("no Woodpecker workflows found") } for _, path := range paths { data, err := os.ReadFile(path) if err != nil { t.Fatalf("read %q: %v", path, err) } var workflow woodpeckerWorkflow if err := yaml.Unmarshal(data, &workflow); err != nil { t.Fatalf("parse %q: %v", path, err) } if len(workflow.Steps) == 0 { t.Fatalf("workflow %q has no steps", path) } validateWorkflowDependencies(t, path, workflow.Steps) } } func TestVerifyWorkflowUsesFullSuiteWithoutFocusedDuplicates(t *testing.T) { path := filepath.Join(repositoryRoot(t), ".woodpecker", "verify.yml") data, err := os.ReadFile(path) if err != nil { t.Fatal(err) } var workflow woodpeckerWorkflow if err := yaml.Unmarshal(data, &workflow); err != nil { t.Fatal(err) } tests, ok := workflow.Steps["tests"] if !ok || !containsWorkflowCommand(tests.Commands, "go test ./...") { t.Fatalf("verify workflow lacks the full default suite: %#v", tests) } for name, step := range workflow.Steps { commands := strings.Join(step.Commands, "\n") if strings.Contains(commands, "go test ./internal/doccheck") || strings.Contains(commands, "go test ./internal/config -run") { t.Errorf("verify step %q repeats tests covered by the full suite", name) } } for _, dependency := range []string{"race-tests", "static-analysis", "build"} { if !workflowDependsOn(workflow.Steps, "cross-build", dependency, map[string]bool{}) { t.Errorf("cross-build does not depend on %q", dependency) } } } func TestReleaseProfileSelections(t *testing.T) { data, err := os.ReadFile(filepath.Join(repositoryRoot(t), "releasekit.json")) if err != nil { t.Fatal(err) } var profile struct { Product string `json:"product"` Remote string `json:"remote"` Validation struct { Go struct { Race bool `json:"race"` FullVet bool `json:"full_vet"` } `json:"go"` GoFormat bool `json:"go_format"` ModuleDistribution struct { LocalReplacements bool `json:"local_replacements"` } `json:"module_distribution"` } `json:"validation"` Build struct { MainPackage string `json:"main_package"` BinaryName string `json:"binary_name"` Targets []string `json:"targets"` } `json:"build"` Delivery struct { Forge string `json:"forge"` BaseURL string `json:"base_url"` Owner string `json:"owner"` Repository string `json:"repository"` TokenEnv string `json:"token_env"` } `json:"delivery"` } if err := json.Unmarshal(data, &profile); err != nil { t.Fatal(err) } if profile.Product != "Narratio" || profile.Remote != "origin" || !profile.Validation.Go.Race || !profile.Validation.Go.FullVet || !profile.Validation.GoFormat || !profile.Validation.ModuleDistribution.LocalReplacements { t.Fatalf("unexpected identity or validation: %+v", profile) } if profile.Build.MainPackage != "./cmd/narratio" || profile.Build.BinaryName != "narratio" || !reflect.DeepEqual(profile.Build.Targets, []string{"linux/amd64", "linux/arm64", "darwin/arm64"}) { t.Fatalf("unexpected build selection: %+v", profile.Build) } if profile.Delivery.Forge != "gitea" || profile.Delivery.BaseURL != "https://forge.maximumdirect.net" || profile.Delivery.Owner != "eric" || profile.Delivery.Repository != "narratio" || profile.Delivery.TokenEnv != "RELEASEKIT_GITEA_TOKEN" { t.Fatalf("unexpected delivery selection: %+v", profile.Delivery) } } func TestReleaseWorkflowDelivery(t *testing.T) { data, err := os.ReadFile(filepath.Join(repositoryRoot(t), ".woodpecker", "release.yml")) if err != nil { t.Fatal(err) } var workflow woodpeckerWorkflow if err := yaml.Unmarshal(data, &workflow); err != nil { t.Fatal(err) } deliver, ok := workflow.Steps["deliver"] if !ok || deliver.Image != "${GO_IMAGE}" || len(workflow.Matrix.Include) != 1 || workflow.Matrix.Include[0]["GO_IMAGE"] != "golang:1.27.4-bookworm" { t.Fatalf("unexpected delivery image: %+v", workflow) } token, ok := deliver.Environment["RELEASEKIT_GITEA_TOKEN"].(map[string]any) if !ok || token["from_secret"] != "GITEA_RELEASE_TOKEN" { t.Fatalf("unexpected delivery environment: %+v", deliver.Environment) } commands := strings.Join(deliver.Commands, "\n") if !strings.Contains(commands, "go.maximumdirect.net/releasekit") || !strings.Contains(commands, "cmd/releasekit") || !strings.Contains(commands, "ci-deliver") || !strings.Contains(commands, "--prepared") { t.Fatalf("delivery does not invoke the native tool: %s", commands) } } func TestWorkflowStepShapes(t *testing.T) { for _, input := range []string{ `steps: first: image: example environment: GOCACHE: /tmp/go-cache CGO_ENABLED: 0 TOKEN: from_secret: example_token second: depends_on: first `, `steps: - name: first image: example environment: GOCACHE: /tmp/go-cache CGO_ENABLED: 0 TOKEN: from_secret: example_token - name: second depends_on: first `, } { var workflow woodpeckerWorkflow if err := yaml.Unmarshal([]byte(input), &workflow); err != nil { t.Fatal(err) } if len(workflow.Steps) != 2 || workflow.Steps["first"].Image != "example" || !workflowDependsOn(workflow.Steps, "second", "first", map[string]bool{}) { t.Fatalf("unexpected decoded steps: %+v", workflow.Steps) } environment := workflow.Steps["first"].Environment if environment["GOCACHE"] != "/tmp/go-cache" || environment["CGO_ENABLED"] != 0 { t.Fatalf("unexpected literal environment values: %+v", environment) } token, ok := environment["TOKEN"].(map[string]any) if !ok || token["from_secret"] != "example_token" { t.Fatalf("unexpected secret reference: %+v", environment["TOKEN"]) } } } func containsWorkflowCommand(commands []string, want string) bool { for _, command := range commands { if strings.Contains(command, want) { return true } } return false } func repositoryRoot(t *testing.T) string { t.Helper() root, err := filepath.Abs(filepath.Join("..", "..")) if err != nil { t.Fatalf("resolve repository root: %v", err) } return root } func walkDocumentationLinks(t *testing.T, root, directory string) { t.Helper() if err := filepath.WalkDir(directory, func(path string, entry os.DirEntry, walkErr error) error { if walkErr != nil { return walkErr } if entry.IsDir() || filepath.Ext(path) != ".md" { return nil } data, err := os.ReadFile(path) if err != nil { return err } for _, match := range documentationLinks(string(data)) { target := strings.TrimSpace(match[1]) if !isLocalDocumentationTarget(target) { continue } target = strings.Trim(strings.SplitN(strings.SplitN(target, "#", 2)[0], "?", 2)[0], "<>") if target == "" { continue } resolved := filepath.Clean(filepath.Join(filepath.Dir(path), target)) if _, err := os.Stat(resolved); err != nil { t.Errorf("%s links to missing local target %q (%s): %v", relativeToRoot(root, path), target, relativeToRoot(root, resolved), err) } } return nil }); err != nil { t.Fatalf("walk documentation in %q: %v", directory, err) } } func isLocalDocumentationTarget(target string) bool { target = strings.TrimSpace(target) return target != "" && !strings.HasPrefix(target, "#") && !strings.HasPrefix(target, "/") && !strings.Contains(target, "://") && !strings.HasPrefix(target, "mailto:") } func relativeToRoot(root, path string) string { relative, err := filepath.Rel(root, path) if err != nil { return path } return relative } type woodpeckerWorkflow struct { Steps woodpeckerSteps `yaml:"steps"` Matrix struct { Include []map[string]string `yaml:"include"` } `yaml:"matrix"` } type woodpeckerSteps map[string]woodpeckerStep func (s *woodpeckerSteps) UnmarshalYAML(value *yaml.Node) error { switch value.Kind { case yaml.MappingNode: var steps map[string]woodpeckerStep if err := value.Decode(&steps); err != nil { return err } *s = steps return nil case yaml.SequenceNode: var list []woodpeckerStep if err := value.Decode(&list); err != nil { return err } steps := make(woodpeckerSteps, len(list)) for _, step := range list { if step.Name == "" { return fmt.Errorf("workflow step has no name") } if _, exists := steps[step.Name]; exists { return fmt.Errorf("duplicate workflow step %q", step.Name) } steps[step.Name] = step } *s = steps return nil default: return fmt.Errorf("workflow steps must be a mapping or sequence") } } type woodpeckerStep struct { Name string `yaml:"name"` Environment map[string]any `yaml:"environment"` DependsOn woodpeckerDependencies `yaml:"depends_on"` Image string `yaml:"image"` Commands []string `yaml:"commands"` } type woodpeckerDependencies []string func (d *woodpeckerDependencies) UnmarshalYAML(value *yaml.Node) error { switch value.Kind { case yaml.ScalarNode: *d = []string{value.Value} return nil case yaml.SequenceNode: dependencies := make([]string, 0, len(value.Content)) for _, item := range value.Content { if item.Kind != yaml.ScalarNode { return fmt.Errorf("dependency must be a step name") } dependencies = append(dependencies, item.Value) } *d = dependencies return nil default: return fmt.Errorf("dependency must be a string or list of strings") } } func validateWorkflowDependencies(t *testing.T, path string, steps map[string]woodpeckerStep) { t.Helper() for name, step := range steps { for _, dependency := range step.DependsOn { if _, ok := steps[dependency]; !ok { t.Errorf("workflow %q step %q depends on undefined step %q", path, name, dependency) } } } visiting := map[string]bool{} visited := map[string]bool{} var visit func(string) visit = func(name string) { if visiting[name] { t.Errorf("workflow %q has a dependency cycle at step %q", path, name) return } if visited[name] { return } visiting[name] = true for _, dependency := range steps[name].DependsOn { if _, ok := steps[dependency]; ok { visit(dependency) } } visiting[name] = false visited[name] = true } for name := range steps { visit(name) } } func workflowDependsOn(steps map[string]woodpeckerStep, stepName, dependencyName string, visited map[string]bool) bool { if visited[stepName] { return false } visited[stepName] = true for _, dependency := range steps[stepName].DependsOn { if dependency == dependencyName || workflowDependsOn(steps, dependency, dependencyName, visited) { return true } } return false }