Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .agents/rules/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
6 changes: 3 additions & 3 deletions acceptance/acceptance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
}

Expand Down
33 changes: 29 additions & 4 deletions acceptance/bin/repls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,24 @@
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

# Order of the replacements added by the scripts, so that they are applied before the ones
# 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."""
Expand All @@ -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"(?<![0-9A-Za-z])" + pattern
if value[-1:] in ALNUM:
pattern = pattern + r"(?![0-9A-Za-z])"
return pattern


def read_repls():
"""Return (pattern, replacement, distinct) tuples in application order."""
entries = []
Expand All @@ -45,8 +70,8 @@ def read_repls():
# values with quotes or backslashes are replaced inside JSON output as well.
encoded = json.dumps(literal, ensure_ascii=False)[1:-1]
if encoded != literal:
entries.append((order, re.escape(encoded), new, False))
entries.append((order, re.escape(literal), new, False))
entries.append((order, literal_pattern(encoded), new, False))
entries.append((order, literal_pattern(literal), new, False))

# Stable sort: replacements with the same order are applied in the order they were added.
entries.sort(key=lambda entry: entry[0])
Expand Down
1 change: 1 addition & 0 deletions acceptance/selftest/add_repl_word/out.test.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Cloud = false
5 changes: 5 additions & 0 deletions acceptance/selftest/add_repl_word/output.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
job [SHORT_ID], commit 33939489e027, number 3390
job_[SHORT_ID] deploy-[SHORT_ID] /[SHORT_ID]/ [SHORT_ID],[SHORT_ID]

>>> diff.py a.txt b.txt
diff done
14 changes: 14 additions & 0 deletions acceptance/selftest/add_repl_word/script
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
job_id=339

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nit] acceptance/selftest/add_repl/ already tests add_repl replacement of a job ID. .agents/rules/testing.md asks to extend the existing acceptance directory when coverage overlaps. Could these whole-word cases go there instead of a new add_repl_word/?

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nice to have] This check passes even if literal_pattern goes back to re.escape(value). Both files contain 33939489e027, so the old rule turns both lines into job [SHORT_ID] commit [SHORT_ID]39489e027. They still compare equal and the golden still only shows diff done, which also makes the comment above wrong. Can you make the Python result visible? For example, put the hash only in a.txt and write the old mangled form [SHORT_ID]39489e027 in b.txt, so the old rule prints no diff and the new rule prints one. Or make the files differ elsewhere, so diff.py prints already-replaced lines into the golden.

# not replaced inside the commit hash.
echo "job 339 commit 33939489e027" > a.txt

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nit] a.txt and b.txt have fixed contents, and .agents/rules/testing.md says to commit static test inputs into the test directory rather than create them in script. Can you commit them and drop the echo > lines and the rm on line 13?

echo "job [SHORT_ID] commit 33939489e027" > b.txt
trace diff.py a.txt b.txt
rm a.txt b.txt
echo "diff done"
69 changes: 61 additions & 8 deletions libs/testdiff/replacement.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
Expand Down Expand Up @@ -90,22 +97,68 @@ 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) {
r.SetWithOrder(old, new, 0)
}

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
}
Expand All @@ -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 {
Expand Down
46 changes: 46 additions & 0 deletions libs/testdiff/replacement_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
}
Loading