build: make repository text EOL deterministic (#5319)
* build: make repository text EOL deterministic Apply one repository-wide LF policy to detected text so Windows checkout settings cannot turn ordinary Go source or future text formats into CRLF. Preserve concise rationale for LF-sensitive hook templates, embedded Markdown, migration hashes, and generated-doc comparisons; keep the tracked JPEG explicitly binary and remove redundant path selectors. Exercise a real isolated Git checkout with core.autocrlf=true through a narrow test package. Bind the existing required Ubuntu, macOS, and Windows matrix to exact expected GOOS values, fail closed on missing or wrong host identity and skipped or zero EOL coverage, and preserve the original doc-freshness command as a separate step. Resolve and positively identify one canonical Git executable, reuse it under a curated environment with repo-local hooks, and protect the workflow topology with regression tests. Bind the required aggregate to startup-clean absolute Linux Bash and uname identities, require the exact POSIX checkout workspace, and re-enter privileged profile-free Bash with exec so ambient functions or startup state cannot turn a gate failure into success. Exercise the aggregate shell boundary in subprocess regressions with hostile exported source and exit functions, poisoned startup options, paired clean and failing fixtures, wrong-host falsification, and invalid-workspace cases. Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell * build: split CI-gate hardening from EOL policy Remove the profile-free CI-gate host-binding chain and its structural and subprocess tests from PR #5319 so the final diff matches the accepted repository EOL motivation. Preserve the required three-host EOL policy lane and its CI Gate propagation. The merge-gate hardening will be reconstructed from current main under its own threat model and review vehicle. Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
This commit is contained in:
parent
766e6c17f2
commit
6748ef650c
6 changed files with 616 additions and 27 deletions
29
.gitattributes
vendored
29
.gitattributes
vendored
|
|
@ -1,23 +1,8 @@
|
|||
# Keep repository text deterministic on every host. The global rule makes future
|
||||
# text formats opt in automatically and protects LF-sensitive hook templates,
|
||||
# embedded Markdown bytes, migration content hashes, and generated-doc byte
|
||||
# comparisons without requiring workstation Git configuration.
|
||||
* text=auto eol=lf
|
||||
|
||||
# Shell scripts must always use LF line endings (especially git hook templates)
|
||||
*.sh text eol=lf
|
||||
cmd/bd/templates/hooks/* text eol=lf
|
||||
|
||||
# Embedded markdown templates are shipped data, not user-edited text. Pin LF so
|
||||
# Windows checkouts (default core.autocrlf=true) don't bake CRLF into //go:embed
|
||||
# bytes, which breaks LF-only marker stripping in templateBody() and produces
|
||||
# doubled BEGIN/END BEADS INTEGRATION markers in installed AGENTS.md (#3552).
|
||||
internal/templates/agents/defaults/*.md text eol=lf
|
||||
|
||||
# Migration SQL is embedded into the binary and content-hashed after apply
|
||||
# (schema_migrations.content_hash, PR 4270). Pin LF so from-source builds on
|
||||
# Windows checkouts (core.autocrlf=true) hash identically to release builds
|
||||
# instead of reporting false migration-content skew.
|
||||
internal/storage/schema/migrations/**/*.sql text eol=lf
|
||||
|
||||
# CLI docs freshness compares committed artifacts byte-for-byte with an LF-only
|
||||
# scratch tree. Pin every generated surface so core.autocrlf cannot create false
|
||||
# drift on Windows.
|
||||
docs/CLI_REFERENCE.md text eol=lf
|
||||
docs/cli-reference/*.md text eol=lf
|
||||
docs/docs.json text eol=lf
|
||||
# Tracked binary assets must never pass through text conversion or text diffs.
|
||||
*.jpg binary
|
||||
|
|
|
|||
11
.github/workflows/pr.yml
vendored
11
.github/workflows/pr.yml
vendored
|
|
@ -375,7 +375,13 @@ jobs:
|
|||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
include:
|
||||
- os: ubuntu-latest
|
||||
expected_goos: linux
|
||||
- os: macos-latest
|
||||
expected_goos: darwin
|
||||
- os: windows-latest
|
||||
expected_goos: windows
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6
|
||||
|
||||
|
|
@ -396,6 +402,9 @@ jobs:
|
|||
- name: Exercise native date and Bash process boundary
|
||||
run: go test '-tags=integration,gms_pure_go' -count=1 -run '^TestDocFreshness' ./scripts
|
||||
|
||||
- name: Exercise repository text EOL policy boundary
|
||||
run: go test '-tags=integration,gms_pure_go' -count=1 ./scripts/gitattributespolicy -args -required-host -expected-goos '${{ matrix.expected_goos }}'
|
||||
|
||||
pr-preflight-platforms:
|
||||
name: PR preflight process (${{ matrix.os }})
|
||||
runs-on: ${{ matrix.os }}
|
||||
|
|
|
|||
|
|
@ -335,6 +335,87 @@ func TestPRPreflightPlatformsRunsTestScriptPrebuiltBinaryContract(t *testing.T)
|
|||
}
|
||||
}
|
||||
|
||||
func TestRepositoryTextEOLPolicyWorkflow(t *testing.T) {
|
||||
workflow := readCIWorkflow(t, "pr.yml")
|
||||
job := workflow.job(t, "check-doc-freshness-platforms")
|
||||
|
||||
if want := "${{ matrix.os }}"; job.RunsOn != want {
|
||||
t.Errorf("check-doc-freshness-platforms runs-on = %q, want %q", job.RunsOn, want)
|
||||
}
|
||||
wantMatrix := map[string]string{
|
||||
"ubuntu-latest": "linux",
|
||||
"macos-latest": "darwin",
|
||||
"windows-latest": "windows",
|
||||
}
|
||||
if len(job.Strategy.Matrix.OS) != 0 {
|
||||
t.Errorf("check-doc-freshness-platforms retains an unbound os-list matrix: %v", job.Strategy.Matrix.OS)
|
||||
}
|
||||
if got, want := len(job.Strategy.Matrix.Include), len(wantMatrix); got != want {
|
||||
t.Fatalf("check-doc-freshness-platforms include tuple count = %d, want %d", got, want)
|
||||
}
|
||||
seen := make(map[string]bool, len(wantMatrix))
|
||||
for _, tuple := range job.Strategy.Matrix.Include {
|
||||
wantGOOS, ok := wantMatrix[tuple.OS]
|
||||
if !ok {
|
||||
t.Errorf("unexpected check-doc-freshness-platforms runner tuple: %+v", tuple)
|
||||
continue
|
||||
}
|
||||
if seen[tuple.OS] {
|
||||
t.Errorf("duplicate check-doc-freshness-platforms runner tuple for %q", tuple.OS)
|
||||
}
|
||||
seen[tuple.OS] = true
|
||||
if tuple.ExpectedGOOS != wantGOOS {
|
||||
t.Errorf("runner %q expected_goos = %q, want %q", tuple.OS, tuple.ExpectedGOOS, wantGOOS)
|
||||
}
|
||||
if tuple.Coverage || tuple.TestFlags != "" {
|
||||
t.Errorf(
|
||||
"runner %q has unexpected shared matrix fields: coverage=%t test-flags=%q",
|
||||
tuple.OS,
|
||||
tuple.Coverage,
|
||||
tuple.TestFlags,
|
||||
)
|
||||
}
|
||||
if len(tuple.Extra) != 0 {
|
||||
t.Errorf("runner %q has unexpected matrix fields: %v", tuple.OS, tuple.Extra)
|
||||
}
|
||||
}
|
||||
|
||||
docStep := job.step(t, "Exercise native date and Bash process boundary")
|
||||
const wantDocCommand = "go test '-tags=integration,gms_pure_go' -count=1 -run '^TestDocFreshness' ./scripts"
|
||||
if docStep.Run != wantDocCommand {
|
||||
t.Errorf("doc-freshness command = %q, want exact original %q", docStep.Run, wantDocCommand)
|
||||
}
|
||||
|
||||
eolStep := job.step(t, "Exercise repository text EOL policy boundary")
|
||||
const wantEOLCommand = "go test '-tags=integration,gms_pure_go' -count=1 ./scripts/gitattributespolicy -args -required-host -expected-goos '${{ matrix.expected_goos }}'"
|
||||
if eolStep.Run != wantEOLCommand {
|
||||
t.Errorf("repository EOL command = %q, want %q", eolStep.Run, wantEOLCommand)
|
||||
}
|
||||
if eolStep.If != "" {
|
||||
t.Errorf("repository EOL step has conditional if = %q", eolStep.If)
|
||||
}
|
||||
if strings.Contains(eolStep.Run, "-run") {
|
||||
t.Errorf("repository EOL step may not filter the narrow package: %q", eolStep.Run)
|
||||
}
|
||||
if job.stepIndex(t, "Exercise native date and Bash process boundary") >=
|
||||
job.stepIndex(t, "Exercise repository text EOL policy boundary") {
|
||||
t.Error("repository EOL step must remain separate and follow doc freshness")
|
||||
}
|
||||
|
||||
gate := workflow.job(t, "ci-gate")
|
||||
if !contains(gate.Needs, "check-doc-freshness-platforms") {
|
||||
t.Errorf("ci-gate does not need check-doc-freshness-platforms: %v", gate.Needs)
|
||||
}
|
||||
gateEnv := gate.step(t, "Evaluate CI gate").Env
|
||||
const gateKey = "CHECK_DOC_FRESHNESS_PLATFORMS"
|
||||
if want := "${{ needs.check-doc-freshness-platforms.result }}"; gateEnv[gateKey] != want {
|
||||
t.Errorf("ci-gate env %s = %q, want %q", gateKey, gateEnv[gateKey], want)
|
||||
}
|
||||
if !contains(strings.Fields(gateEnv["CI_GATE_REQUIRED"]), gateKey) {
|
||||
t.Errorf("ci-gate CI_GATE_REQUIRED does not include %q", gateKey)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoCacheOwnershipTopology(t *testing.T) {
|
||||
workflows := map[string]ciWorkflow{
|
||||
"main.yml": readCIWorkflow(t, "main.yml"),
|
||||
|
|
@ -834,9 +915,11 @@ type ciWorkflowMatrix struct {
|
|||
}
|
||||
|
||||
type ciWorkflowMatrixInclude struct {
|
||||
OS string `yaml:"os"`
|
||||
Coverage bool `yaml:"coverage"`
|
||||
TestFlags string `yaml:"test-flags"`
|
||||
OS string `yaml:"os"`
|
||||
ExpectedGOOS string `yaml:"expected_goos"`
|
||||
Coverage bool `yaml:"coverage"`
|
||||
TestFlags string `yaml:"test-flags"`
|
||||
Extra map[string]any `yaml:",inline"`
|
||||
}
|
||||
|
||||
type ciWorkflowStep struct {
|
||||
|
|
|
|||
101
scripts/gitattributespolicy/git_boundary_test.go
Normal file
101
scripts/gitattributespolicy/git_boundary_test.go
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
package gitattributespolicy_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func resolveEOLPolicyGit(t *testing.T) string {
|
||||
t.Helper()
|
||||
|
||||
discovered, err := exec.LookPath("git")
|
||||
if err != nil {
|
||||
t.Fatalf("resolve Git once: %v", err)
|
||||
}
|
||||
absolute, err := filepath.Abs(discovered)
|
||||
if err != nil {
|
||||
t.Fatalf("make resolved Git path absolute: %v", err)
|
||||
}
|
||||
canonical, err := filepath.EvalSymlinks(absolute)
|
||||
if err != nil {
|
||||
t.Fatalf("canonicalize resolved Git path %q: %v", absolute, err)
|
||||
}
|
||||
canonical = filepath.Clean(canonical)
|
||||
if !filepath.IsAbs(canonical) {
|
||||
t.Fatalf("canonical Git path is not absolute: %q", canonical)
|
||||
}
|
||||
info, err := os.Stat(canonical)
|
||||
if err != nil {
|
||||
t.Fatalf("stat canonical Git path %q: %v", canonical, err)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
t.Fatalf("canonical Git path is not a regular file: %q (%s)", canonical, info.Mode())
|
||||
}
|
||||
return canonical
|
||||
}
|
||||
|
||||
func requireEOLPolicyGitVersion(t *testing.T, gitPath, repository string) {
|
||||
t.Helper()
|
||||
|
||||
version := strings.TrimSpace(runEOLPolicyGit(t, gitPath, repository, "--version"))
|
||||
if strings.ContainsAny(version, "\r\n") {
|
||||
t.Fatalf("Git version identity is not one line: %q", version)
|
||||
}
|
||||
fields := strings.Fields(version)
|
||||
if len(fields) < 3 || fields[0] != "git" || fields[1] != "version" ||
|
||||
fields[2] == "" || fields[2][0] < '0' || fields[2][0] > '9' ||
|
||||
!strings.Contains(fields[2], ".") {
|
||||
t.Fatalf("resolved executable did not positively identify as Git: %q", version)
|
||||
}
|
||||
}
|
||||
|
||||
func runEOLPolicyGit(
|
||||
t *testing.T,
|
||||
gitPath string,
|
||||
repository string,
|
||||
arguments ...string,
|
||||
) string {
|
||||
t.Helper()
|
||||
command := exec.Command(gitPath, arguments...)
|
||||
command.Dir = repository
|
||||
command.Env = eolPolicyGitEnvironment(repository, gitPath)
|
||||
output, err := command.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("git %s failed: %v\n%s", strings.Join(arguments, " "), err, output)
|
||||
}
|
||||
return string(output)
|
||||
}
|
||||
|
||||
func eolPolicyGitEnvironment(repository, gitPath string) []string {
|
||||
environment := make([]string, 0, 18)
|
||||
for _, name := range []string{
|
||||
"COMSPEC",
|
||||
"LANG",
|
||||
"LC_ALL",
|
||||
"LC_CTYPE",
|
||||
"PATHEXT",
|
||||
"SYSTEMDRIVE",
|
||||
"SYSTEMROOT",
|
||||
"TEMP",
|
||||
"TMP",
|
||||
"TMPDIR",
|
||||
"WINDIR",
|
||||
} {
|
||||
if value, ok := os.LookupEnv(name); ok {
|
||||
environment = append(environment, name+"="+value)
|
||||
}
|
||||
}
|
||||
return append(
|
||||
environment,
|
||||
"PATH="+filepath.Dir(gitPath),
|
||||
"HOME="+repository,
|
||||
"XDG_CONFIG_HOME="+filepath.Join(repository, ".xdg"),
|
||||
"GIT_ATTR_NOSYSTEM=1",
|
||||
"GIT_CONFIG_GLOBAL="+os.DevNull,
|
||||
"GIT_CONFIG_NOSYSTEM=1",
|
||||
"GIT_PAGER=cat",
|
||||
"GIT_TERMINAL_PROMPT=0")
|
||||
}
|
||||
288
scripts/gitattributespolicy/gitattributes_policy_test.go
Normal file
288
scripts/gitattributespolicy/gitattributes_policy_test.go
Normal file
|
|
@ -0,0 +1,288 @@
|
|||
package gitattributespolicy_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRepositoryTextPolicyKeepsLFWithAutoCrlf(t *testing.T) {
|
||||
eolTestRuns.Add(1)
|
||||
t.Cleanup(func() {
|
||||
if t.Skipped() {
|
||||
eolTestSkipped.Add(1)
|
||||
return
|
||||
}
|
||||
if !t.Failed() {
|
||||
eolTestPasses.Add(1)
|
||||
}
|
||||
})
|
||||
|
||||
repository := t.TempDir()
|
||||
gitPath := resolveEOLPolicyGit(t)
|
||||
requireEOLPolicyGitVersion(t, gitPath, repository)
|
||||
|
||||
attributes, err := os.ReadFile(filepath.Join("..", "..", ".gitattributes"))
|
||||
if err != nil {
|
||||
t.Fatalf("read repository attributes: %v", err)
|
||||
}
|
||||
|
||||
writeEOLPolicyFixture(t, filepath.Join(repository, ".gitattributes"), attributes)
|
||||
textFixtures := []struct {
|
||||
name string
|
||||
contents []byte
|
||||
}{
|
||||
{"fixture.go", []byte("package fixture\n\nconst value = 1\n")},
|
||||
{"future.unlisted", []byte("future text format\n")},
|
||||
}
|
||||
for _, fixture := range textFixtures {
|
||||
writeEOLPolicyFixture(
|
||||
t,
|
||||
filepath.Join(repository, fixture.name),
|
||||
fixture.contents)
|
||||
}
|
||||
binaryPath := filepath.Join(repository, "fixture.jpg")
|
||||
binaryBytes := []byte{0xff, 0xd8, 0x00, 0x0d, 0x0a, 0xff, 0xd9}
|
||||
writeEOLPolicyFixture(t, binaryPath, binaryBytes)
|
||||
|
||||
runEOLPolicyGit(t, gitPath, repository, "init", "--quiet")
|
||||
runEOLPolicyGit(t, gitPath, repository, "config", "--local", "user.name", "EOL Policy Test")
|
||||
runEOLPolicyGit(t, gitPath, repository, "config", "--local", "user.email", "eol-policy@example.invalid")
|
||||
runEOLPolicyGit(t, gitPath, repository, "config", "--local", "core.hooksPath", ".git/hooks")
|
||||
runEOLPolicyGit(t, gitPath, repository, "config", "--local", "core.autocrlf", "true")
|
||||
if hooksPath := strings.TrimSpace(runEOLPolicyGit(
|
||||
t,
|
||||
gitPath,
|
||||
repository,
|
||||
"config",
|
||||
"--local",
|
||||
"--get",
|
||||
"core.hooksPath")); hooksPath != ".git/hooks" {
|
||||
t.Fatalf("repo-local core.hooksPath = %q, want .git/hooks", hooksPath)
|
||||
}
|
||||
runEOLPolicyGit(t, gitPath, repository, "add", "--", ".")
|
||||
runEOLPolicyGit(t, gitPath, repository, "commit", "--quiet", "-m", "fixture")
|
||||
|
||||
for _, fixture := range textFixtures {
|
||||
if err := os.Remove(filepath.Join(repository, fixture.name)); err != nil {
|
||||
t.Fatalf("remove text fixture %s before checkout: %v", fixture.name, err)
|
||||
}
|
||||
}
|
||||
if err := os.Remove(binaryPath); err != nil {
|
||||
t.Fatalf("remove binary fixture before checkout: %v", err)
|
||||
}
|
||||
runEOLPolicyGit(t, gitPath, repository, "checkout-index", "--force", "--all")
|
||||
|
||||
for _, fixture := range textFixtures {
|
||||
checkedOutText, err := os.ReadFile(filepath.Join(repository, fixture.name))
|
||||
if err != nil {
|
||||
t.Fatalf("read checked-out text fixture %s: %v", fixture.name, err)
|
||||
}
|
||||
if !bytes.Equal(fixture.contents, checkedOutText) {
|
||||
t.Fatalf(
|
||||
"text checkout changed LF bytes for %s:\nwant %q\ngot %q",
|
||||
fixture.name,
|
||||
fixture.contents,
|
||||
checkedOutText)
|
||||
}
|
||||
}
|
||||
|
||||
checkedOutBinary, err := os.ReadFile(binaryPath)
|
||||
if err != nil {
|
||||
t.Fatalf("read checked-out binary fixture: %v", err)
|
||||
}
|
||||
if !bytes.Equal(binaryBytes, checkedOutBinary) {
|
||||
t.Fatalf("binary checkout changed bytes:\nwant %v\ngot %v", binaryBytes, checkedOutBinary)
|
||||
}
|
||||
|
||||
attributesOutput := runEOLPolicyGit(
|
||||
t,
|
||||
gitPath,
|
||||
repository,
|
||||
"check-attr",
|
||||
"-z",
|
||||
"text",
|
||||
"diff",
|
||||
"merge",
|
||||
"eol",
|
||||
"--",
|
||||
"fixture.go",
|
||||
"future.unlisted",
|
||||
"fixture.jpg")
|
||||
attributeRecords, err := parseGitAttributeRecords(attributesOutput)
|
||||
if err != nil {
|
||||
t.Fatalf("parse exact Git attributes: %v", err)
|
||||
}
|
||||
if err := compareExactGitAttributeRecords(
|
||||
attributeRecords,
|
||||
expectedGitAttributeRecords()); err != nil {
|
||||
t.Fatalf("Git attributes differ from the exact requested set: %v\n%q", err, attributesOutput)
|
||||
}
|
||||
|
||||
if status := strings.TrimSpace(
|
||||
runEOLPolicyGit(t, gitPath, repository, "status", "--porcelain")); status != "" {
|
||||
t.Fatalf("checkout is dirty under core.autocrlf=true:\n%s", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGitAttributeRecordsRejectLookalikeValues(t *testing.T) {
|
||||
records, err := parseGitAttributeRecords(
|
||||
"fixture.jpg\x00diff\x00unsetfoo\x00")
|
||||
if err != nil {
|
||||
t.Fatalf("parse lookalike fixture: %v", err)
|
||||
}
|
||||
expected := map[gitAttributeKey]string{
|
||||
{path: "fixture.jpg", attribute: "diff"}: "unset",
|
||||
}
|
||||
if err := compareExactGitAttributeRecords(records, expected); err == nil {
|
||||
t.Fatal("lookalike diff value satisfied the exact unset record")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGitAttributeRecordsRejectMalformedInput(t *testing.T) {
|
||||
const record = "fixture.jpg\x00diff\x00unset\x00"
|
||||
tests := []struct {
|
||||
name string
|
||||
output string
|
||||
wantReason string
|
||||
}{
|
||||
{name: "unterminated", output: "fixture.jpg\x00diff\x00unset", wantReason: "final NUL"},
|
||||
{name: "truncated", output: "fixture.jpg\x00diff\x00", wantReason: "triples"},
|
||||
{name: "empty path", output: "\x00diff\x00unset\x00", wantReason: "empty record field"},
|
||||
{name: "empty attribute", output: "fixture.jpg\x00\x00unset\x00", wantReason: "empty record field"},
|
||||
{name: "empty value", output: "fixture.jpg\x00diff\x00\x00", wantReason: "empty record field"},
|
||||
{name: "identical duplicate", output: record + record, wantReason: "duplicate path/attribute"},
|
||||
{
|
||||
name: "conflicting duplicate",
|
||||
output: record +
|
||||
"fixture.jpg\x00diff\x00unsetfoo\x00",
|
||||
wantReason: "duplicate path/attribute",
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
_, err := parseGitAttributeRecords(test.output)
|
||||
if err == nil {
|
||||
t.Fatal("malformed git check-attr records were accepted")
|
||||
}
|
||||
if !strings.Contains(err.Error(), test.wantReason) {
|
||||
t.Fatalf("failure = %q, want reason %q", err, test.wantReason)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGitAttributeRecordsRequireCompleteExpectedSet(t *testing.T) {
|
||||
expected := expectedGitAttributeRecords()
|
||||
missing := cloneGitAttributeRecords(expected)
|
||||
delete(missing, gitAttributeKey{path: "fixture.go", attribute: "diff"})
|
||||
extra := cloneGitAttributeRecords(expected)
|
||||
extra[gitAttributeKey{path: "fixture.extra", attribute: "diff"}] = "unset"
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
actual map[gitAttributeKey]string
|
||||
}{
|
||||
{name: "missing unasserted record", actual: missing},
|
||||
{name: "extra record", actual: extra},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if err := compareExactGitAttributeRecords(test.actual, expected); err == nil {
|
||||
t.Fatal("non-exact git check-attr record set was accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type gitAttributeKey struct {
|
||||
path string
|
||||
attribute string
|
||||
}
|
||||
|
||||
func parseGitAttributeRecords(output string) (map[gitAttributeKey]string, error) {
|
||||
fields := strings.Split(output, "\x00")
|
||||
if fields[len(fields)-1] != "" {
|
||||
return nil, fmt.Errorf(
|
||||
"git check-attr -z output lacks its final NUL: %q",
|
||||
output)
|
||||
}
|
||||
fields = fields[:len(fields)-1]
|
||||
if len(fields)%3 != 0 {
|
||||
return nil, fmt.Errorf(
|
||||
"git check-attr -z output is not path/attribute/value triples: %q",
|
||||
output)
|
||||
}
|
||||
records := make(map[gitAttributeKey]string, len(fields)/3)
|
||||
for index := 0; index < len(fields); index += 3 {
|
||||
key := gitAttributeKey{path: fields[index], attribute: fields[index+1]}
|
||||
value := fields[index+2]
|
||||
if key.path == "" || key.attribute == "" || value == "" {
|
||||
return nil, fmt.Errorf(
|
||||
"git check-attr -z returned an empty record field: key=%+v value=%q",
|
||||
key,
|
||||
value)
|
||||
}
|
||||
if _, duplicate := records[key]; duplicate {
|
||||
return nil, fmt.Errorf(
|
||||
"git check-attr -z returned a duplicate path/attribute: %+v",
|
||||
key)
|
||||
}
|
||||
records[key] = value
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
|
||||
func expectedGitAttributeRecords() map[gitAttributeKey]string {
|
||||
return map[gitAttributeKey]string{
|
||||
{path: "fixture.go", attribute: "text"}: "auto",
|
||||
{path: "fixture.go", attribute: "diff"}: "unspecified",
|
||||
{path: "fixture.go", attribute: "merge"}: "unspecified",
|
||||
{path: "fixture.go", attribute: "eol"}: "lf",
|
||||
{path: "future.unlisted", attribute: "text"}: "auto",
|
||||
{path: "future.unlisted", attribute: "diff"}: "unspecified",
|
||||
{path: "future.unlisted", attribute: "merge"}: "unspecified",
|
||||
{path: "future.unlisted", attribute: "eol"}: "lf",
|
||||
{path: "fixture.jpg", attribute: "text"}: "unset",
|
||||
{path: "fixture.jpg", attribute: "diff"}: "unset",
|
||||
{path: "fixture.jpg", attribute: "merge"}: "unset",
|
||||
{path: "fixture.jpg", attribute: "eol"}: "lf",
|
||||
}
|
||||
}
|
||||
|
||||
func compareExactGitAttributeRecords(
|
||||
actual map[gitAttributeKey]string,
|
||||
expected map[gitAttributeKey]string,
|
||||
) error {
|
||||
if len(actual) != len(expected) {
|
||||
return fmt.Errorf("record count = %d, want %d", len(actual), len(expected))
|
||||
}
|
||||
for key, want := range expected {
|
||||
got, ok := actual[key]
|
||||
if !ok {
|
||||
return fmt.Errorf("missing record for %+v", key)
|
||||
}
|
||||
if got != want {
|
||||
return fmt.Errorf("record %+v value = %q, want %q", key, got, want)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func cloneGitAttributeRecords(
|
||||
source map[gitAttributeKey]string,
|
||||
) map[gitAttributeKey]string {
|
||||
clone := make(map[gitAttributeKey]string, len(source))
|
||||
for key, value := range source {
|
||||
clone[key] = value
|
||||
}
|
||||
return clone
|
||||
}
|
||||
|
||||
func writeEOLPolicyFixture(t *testing.T, path string, contents []byte) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(path, contents, 0o644); err != nil {
|
||||
t.Fatalf("write %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
123
scripts/gitattributespolicy/required_host_test.go
Normal file
123
scripts/gitattributespolicy/required_host_test.go
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
package gitattributespolicy_test
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var (
|
||||
requiredHost = flag.Bool(
|
||||
"required-host",
|
||||
false,
|
||||
"require exact hosted GOOS and one successful EOL boundary test")
|
||||
expectedGOOS = flag.String(
|
||||
"expected-goos",
|
||||
"",
|
||||
"protected GOOS expected by the required hosted job")
|
||||
eolTestRuns atomic.Int32
|
||||
eolTestPasses atomic.Int32
|
||||
eolTestSkipped atomic.Int32
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
if !flag.Parsed() {
|
||||
flag.Parse()
|
||||
}
|
||||
if err := validateRequiredHost(*requiredHost, *expectedGOOS, runtime.GOOS); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "repository EOL required-host contract failed: %v\n", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
exitCode := m.Run()
|
||||
if *requiredHost {
|
||||
if err := validateRequiredEOLExecution(
|
||||
int(eolTestRuns.Load()),
|
||||
int(eolTestPasses.Load()),
|
||||
int(eolTestSkipped.Load())); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "repository EOL required-test contract failed: %v\n", err)
|
||||
if exitCode == 0 {
|
||||
exitCode = 2
|
||||
}
|
||||
}
|
||||
}
|
||||
os.Exit(exitCode)
|
||||
}
|
||||
|
||||
func TestRequiredHostContractRejectsMissingOrWrongGOOS(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
required bool
|
||||
expected string
|
||||
actual string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "ordinary local run", required: false, wantErr: false},
|
||||
{name: "missing expected GOOS", required: true, actual: "linux", wantErr: true},
|
||||
{name: "wrong runtime GOOS", required: true, expected: "linux", actual: "windows", wantErr: true},
|
||||
{name: "unsupported expected GOOS", required: true, expected: "plan9", actual: "plan9", wantErr: true},
|
||||
{name: "matching required GOOS", required: true, expected: "linux", actual: "linux", wantErr: false},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
err := validateRequiredHost(test.required, test.expected, test.actual)
|
||||
if (err != nil) != test.wantErr {
|
||||
t.Fatalf("validateRequiredHost(%t, %q, %q) error = %v, wantErr %t",
|
||||
test.required, test.expected, test.actual, err, test.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequiredEOLExecutionContractRejectsMissingOrSkippedTest(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
runs, passes, skips int
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "exact successful run", runs: 1, passes: 1, wantErr: false},
|
||||
{name: "zero selected tests", wantErr: true},
|
||||
{name: "skipped test", runs: 1, skips: 1, wantErr: true},
|
||||
{name: "failed test", runs: 1, wantErr: true},
|
||||
{name: "duplicate test", runs: 2, passes: 2, wantErr: true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
err := validateRequiredEOLExecution(test.runs, test.passes, test.skips)
|
||||
if (err != nil) != test.wantErr {
|
||||
t.Fatalf("validateRequiredEOLExecution(%d, %d, %d) error = %v, wantErr %t",
|
||||
test.runs, test.passes, test.skips, err, test.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func validateRequiredHost(required bool, expected, actual string) error {
|
||||
if !required {
|
||||
return nil
|
||||
}
|
||||
if expected == "" {
|
||||
return fmt.Errorf("-expected-goos is required when -required-host is set")
|
||||
}
|
||||
switch expected {
|
||||
case "linux", "darwin", "windows":
|
||||
default:
|
||||
return fmt.Errorf("unsupported expected GOOS %q", expected)
|
||||
}
|
||||
if actual != expected {
|
||||
return fmt.Errorf("runtime GOOS %q does not match protected expected GOOS %q", actual, expected)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateRequiredEOLExecution(runs, passes, skips int) error {
|
||||
if runs != 1 || passes != 1 || skips != 0 {
|
||||
return fmt.Errorf(
|
||||
"EOL boundary counts runs=%d passes=%d skips=%d, want exactly runs=1 passes=1 skips=0",
|
||||
runs,
|
||||
passes,
|
||||
skips)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue