diff --git a/.agents/rules/testing.md b/.agents/rules/testing.md index 2a5dc439657..5e34314a1c8 100644 --- a/.agents/rules/testing.md +++ b/.agents/rules/testing.md @@ -54,7 +54,7 @@ Ignore = ["databricks.yml"] - `contains.py SUBSTR [!SUBSTR_NOT]`: passthrough filter asserting substrings are present (or absent). - `print_requests.py //path [^//exclude] [--get] [--sort] [--unique] [--oneline] [--keep]`: print recorded requests (needs `RecordRequests = true`). Excludes GET unless `--get`; clears `out.requests.txt` unless `--keep` (don't `--keep` if another call follows: it double-prints). - `replace_ids.py [-t TARGET]`, `read_id.py [-t TARGET] NAME`: add `[NAME_ID]` replacements for resource IDs from state. -- `add_repl VALUE REPLACEMENT`: add a custom output replacement. Don't write `$ACC_REPLS` directly. +- `add_repl VALUE REPLACEMENT`: add a custom output replacement. A value that starts or ends with a letter or digit matches only as a whole alphanumeric run, so `add_repl 339 X` does not change `33939489e027`, but does change `job_339` and `339,339`. Don't write `$ACC_REPLS` directly. - `update_file.py FILENAME OLD NEW`, `find.py REGEX [--expect N]`, `diff.py A B` (diff with replacements applied), `print_state.py`, `edit_resource.py TYPE ID < script.py`, `gron.py` (flatten JSON; prefer `gron.py | grep field` over `jq` paths for single values). - `plan_filter.py [RESOURCE_KEY]`: filter `bundle plan -o json` for a golden, dropping `remote_state` and the deployment stamp. diff --git a/acceptance/acceptance_test.go b/acceptance/acceptance_test.go index eabeae572a1..ff4ae56fdf3 100644 --- a/acceptance/acceptance_test.go +++ b/acceptance/acceptance_test.go @@ -106,8 +106,8 @@ const ( // It is kept outside of the test directory, otherwise "bundle deploy" uploads it. // // Every line is one replacement encoded as a JSON object: "Old" is a regular expression - // (written by the harness), "Literal" is a value to replace verbatim (appended by - // add_repl.py). The harness writes its own replacements first, then the scripts add theirs: + // (written by the harness), "Literal" is a value to replace as a whole alphanumeric run + // (appended by add_repl.py). The harness writes its own replacements first, then the scripts add theirs: // // $ job_id=100200300 // $ add_repl "$job_id" MY_JOB # replaces 100200300 with [MY_JOB] in the output @@ -2144,7 +2144,7 @@ func loadScriptReplacements(t *testing.T, repls *testdiff.ReplacementsContext, r t.Errorf("Incomplete entry in %s: %#v", ReplsEnvVar, line) continue } - repls.SetWithOrder(entry.Literal, entry.New, entry.Order) + repls.SetWholeWordWithOrder(entry.Literal, entry.New, entry.Order) } } diff --git a/acceptance/bin/repls.py b/acceptance/bin/repls.py index f24da6ce638..1b3d1422d05 100644 --- a/acceptance/bin/repls.py +++ b/acceptance/bin/repls.py @@ -3,13 +3,14 @@ Read the replacements applied to the test output from $ACC_REPLS. Every line is one replacement encoded as a JSON object: "Old" is a regular expression -(written by the test harness), "Literal" is a value to replace verbatim (appended by -add_repl.py). "New" is the replacement, "Order" defines the order they are applied in. +(written by the test harness), "Literal" is a value to replace as a whole alphanumeric run +(appended by add_repl.py). "New" is the replacement, "Order" defines the order they are applied in. """ import json import os import re +import string import sys from pathlib import Path @@ -17,6 +18,9 @@ # from the harness: a job id must become [MY_JOB] even if a broader harness pattern matches it. USER_ORDER = -100 +# Must agree with isASCIIAlnum in libs/testdiff/replacement.go. +ALNUM = frozenset(string.ascii_letters + string.digits) + def read_entries(): """Return the raw entries of $ACC_REPLS.""" @@ -28,6 +32,27 @@ def read_entries(): return result +def literal_pattern(value): + r"""Regex for value as a whole alphanumeric run: the same rule as SetWholeWordWithOrder in Go. + + A side of the match where value starts or ends with an ASCII letter or digit must not be next + to another one. Other characters, including "_", are separators. + + >>> re.search(literal_pattern("339"), "33939489e027 id=339,339").span() + (16, 19) + >>> re.search(literal_pattern("339"), "job_339") is not None + True + >>> re.search(literal_pattern("/tmp/x/"), "/tmp/x/abc") is not None + True + """ + pattern = re.escape(value) + if value[:1] in ALNUM: + pattern = r"(?>> diff.py a.txt b.txt +diff done diff --git a/acceptance/selftest/add_repl_word/script b/acceptance/selftest/add_repl_word/script new file mode 100644 index 00000000000..3df5ceb4b96 --- /dev/null +++ b/acceptance/selftest/add_repl_word/script @@ -0,0 +1,14 @@ +job_id=339 +add_repl "$job_id" SHORT_ID + +# The ID is replaced as a whole token only, not inside the hex string or the longer number. +echo "job $job_id, commit 33939489e027, number 3390" +echo "job_$job_id deploy-$job_id /$job_id/ $job_id,$job_id" + +# diff.py applies the same replacements in Python. The files are equal only if the ID is +# not replaced inside the commit hash. +echo "job 339 commit 33939489e027" > a.txt +echo "job [SHORT_ID] commit 33939489e027" > b.txt +trace diff.py a.txt b.txt +rm a.txt b.txt +echo "diff done" diff --git a/libs/testdiff/replacement.go b/libs/testdiff/replacement.go index 6df2ade8434..0e9b1fb4038 100644 --- a/libs/testdiff/replacement.go +++ b/libs/testdiff/replacement.go @@ -34,6 +34,9 @@ type Replacement struct { New string Order int Distinct bool + // WholeWord is set for the literal values that scripts add with add_repl. Their matches + // must not cut into a longer alphanumeric run, see replaceWholeWord. + WholeWord bool } type ReplacementsContext struct { @@ -53,6 +56,10 @@ func (r *ReplacementsContext) Replace(s string) string { return cmp.Compare(a.Order, b.Order) }) for _, repl := range repls { + if repl.WholeWord { + s = replaceWholeWord(repl.Old, repl.New, s) + continue + } if !repl.Distinct { s = repl.Old.ReplaceAllString(s, repl.New) continue @@ -90,15 +97,51 @@ func (r *ReplacementsContext) append(pattern *regexp.Regexp, replacement string, }) } -func (r *ReplacementsContext) appendLiteral(old, new string, order int) { - r.append( +// replaceWholeWord replaces the matches of the literal pattern re in s, except for matches that +// cut into a longer alphanumeric run. A match whose first byte is an ASCII letter or digit must not +// be preceded by one, and a match whose last byte is one must not be followed by one. Other bytes, +// including "_", are separators, and a value that starts or ends with anything else has no check +// on that side. The neighbours are read from the original s, so matches separated by a single +// character are all replaced. +func replaceWholeWord(re *regexp.Regexp, repl, s string) string { + var b strings.Builder + copied := 0 // s[:copied] is already in b + for pos := 0; pos < len(s); { + loc := re.FindStringIndex(s[pos:]) + if loc == nil { + break + } + start, end := pos+loc[0], pos+loc[1] + leftOK := !isASCIIAlnum(s[start]) || start == 0 || !isASCIIAlnum(s[start-1]) + rightOK := !isASCIIAlnum(s[end-1]) || end == len(s) || !isASCIIAlnum(s[end]) + if !leftOK || !rightOK { + // Retry one byte later: a valid match may start inside the rejected one. + pos = start + 1 + continue + } + b.WriteString(s[copied:start]) + b.Write(re.ExpandString(nil, repl, s[pos:], loc)) + copied = end + pos = end + } + b.WriteString(s[copied:]) + return b.String() +} + +func isASCIIAlnum(c byte) bool { + return '0' <= c && c <= '9' || 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' +} + +func (r *ReplacementsContext) appendLiteral(old, new string, order int, wholeWord bool) { + r.Repls = append(r.Repls, Replacement{ // Transform the input strings such that they can be used as literal strings in regular expressions. - regexp.MustCompile(regexp.QuoteMeta(old)), + Old: regexp.MustCompile(regexp.QuoteMeta(old)), // Transform the replacement string such that `$` is interpreted as a literal dollar sign. // For more information about how the replacement string is used, see [regexp.Regexp.Expand]. - strings.ReplaceAll(new, `$`, `$$`), - order, - ) + New: strings.ReplaceAll(new, `$`, `$$`), + Order: order, + WholeWord: wholeWord, + }) } func (r *ReplacementsContext) Set(old, new string) { @@ -106,6 +149,16 @@ func (r *ReplacementsContext) Set(old, new string) { } func (r *ReplacementsContext) SetWithOrder(old, new string, order int) { + r.setLiteral(old, new, order, false) +} + +// SetWholeWordWithOrder is SetWithOrder for a value that only matches as a whole alphanumeric +// run, see replaceWholeWord. Used for the literals that scripts add with add_repl. +func (r *ReplacementsContext) SetWholeWordWithOrder(old, new string, order int) { + r.setLiteral(old, new, order, true) +} + +func (r *ReplacementsContext) setLiteral(old, new string, order int, wholeWord bool) { if old == "" || new == "" { return } @@ -121,12 +174,12 @@ func (r *ReplacementsContext) SetWithOrder(old, new string, order int) { encodedStrNew := trimQuotes(string(encodedNew)) encodedStrOld := trimQuotes(string(encodedOld)) if encodedStrNew != new || encodedStrOld != old { - r.appendLiteral(encodedStrOld, encodedStrNew, order) + r.appendLiteral(encodedStrOld, encodedStrNew, order, wholeWord) } } } - r.appendLiteral(old, new, order) + r.appendLiteral(old, new, order, wholeWord) } func trimQuotes(s string) string { diff --git a/libs/testdiff/replacement_test.go b/libs/testdiff/replacement_test.go index 53e025b4ff5..10e7571299e 100644 --- a/libs/testdiff/replacement_test.go +++ b/libs/testdiff/replacement_test.go @@ -84,3 +84,49 @@ func TestReplaceAppliesInOrder(t *testing.T) { got := rc.Replace(input) assert.Equal(t, "C", got) } + +func TestReplacement_WholeWord(t *testing.T) { + tests := []struct { + name string + value string + input string + want string + }{ + {"standalone", "339", "job 339 done", "job [ID] done"}, + {"inside hex string is not replaced", "339", "commit 33939489e027", "commit 33939489e027"}, + {"inside a longer number is not replaced", "339", "id 3390", "id 3390"}, + {"whole text", "339", "339", "[ID]"}, + {"underscore is a separator", "339", "job_339", "job_[ID]"}, + {"dash is a separator", "339", "deploy-339", "deploy-[ID]"}, + {"slash is a separator", "339", "/339/x", "/[ID]/x"}, + {"adjacent matches separated by one character", "339", "339,339", "[ID],[ID]"}, + {"value ending with non-alnum has no check on that side", "/tmp/x/", "/tmp/x/abc /tmp/x/", "[ID]abc [ID]"}, + {"value starting with non-alnum has no check on that side", "-ab", "x-ab", "x[ID]"}, + {"rejected match does not hide a later one", "a.a", "ba.a.a", "ba.[ID]"}, + {"non-ASCII letter is a separator", "339", "é339", "é[ID]"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var repls ReplacementsContext + repls.SetWholeWordWithOrder(tt.value, "[ID]", 0) + assert.Equal(t, tt.want, repls.Replace(tt.input)) + }) + } +} + +func TestReplacement_WholeWordJSON(t *testing.T) { + var repls ReplacementsContext + + repls.SetWholeWordWithOrder(`a"1`, "[V]", 0) + // The JSON-encoded form of the value, a\"1, is matched inside JSON output. + assert.Equal(t, `"[V]"`, repls.Replace(`"a\"1"`)) + assert.Equal(t, `"xa\"1"`, repls.Replace(`"xa\"1"`)) +} + +func TestReplacement_PlainLiteralUnchanged(t *testing.T) { + // Values from the harness (Set) keep matching inside longer strings, e.g. paths and versions. + var repls ReplacementsContext + + repls.Set("339", "[ID]") + assert.Equal(t, "[ID]39489e027", repls.Replace("33939489e027")) +}