Skip to content
Merged
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
53 changes: 46 additions & 7 deletions relay/common/override.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"fmt"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"regexp"
"strconv"
"strings"
)

Expand Down Expand Up @@ -151,7 +153,9 @@ func checkConditions(jsonStr string, conditions []ConditionOperation, logic stri
}

func checkSingleCondition(jsonStr string, condition ConditionOperation) (bool, error) {
value := gjson.Get(jsonStr, condition.Path)
// 处理负数索引
path := processNegativeIndex(jsonStr, condition.Path)
value := gjson.Get(jsonStr, path)
if !value.Exists() {
if condition.PassMissingKey {
return true, nil
Expand All @@ -177,6 +181,37 @@ func checkSingleCondition(jsonStr string, condition ConditionOperation) (bool, e
return result, nil
}

func processNegativeIndex(jsonStr string, path string) string {
re := regexp.MustCompile(`\.(-\d+)`)
matches := re.FindAllStringSubmatch(path, -1)

if len(matches) == 0 {
return path
}

result := path
for _, match := range matches {
negIndex := match[1]
index, _ := strconv.Atoi(negIndex)

arrayPath := strings.Split(path, negIndex)[0]
if strings.HasSuffix(arrayPath, ".") {
arrayPath = arrayPath[:len(arrayPath)-1]
}

array := gjson.Get(jsonStr, arrayPath)
if array.IsArray() {
length := len(array.Array())
actualIndex := length + index
if actualIndex >= 0 && actualIndex < length {
result = strings.Replace(result, match[0], "."+strconv.Itoa(actualIndex), 1)
}
}
}

return result
}
Comment on lines +184 to +213

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Bug: nested/multiple negative indices can resolve incorrectly.

arrayPath is computed from the original path and may still contain unresolved negative indices, breaking lookups for subsequent matches (e.g., a.-1.b.-2). Iterate left-to-right on the progressively updated result and compute arrayPath via match indices.

Apply this diff:

-func processNegativeIndex(jsonStr string, path string) string {
-	re := regexp.MustCompile(`\.(-\d+)`)
-	matches := re.FindAllStringSubmatch(path, -1)
-
-	if len(matches) == 0 {
-		return path
-	}
-
-	result := path
-	for _, match := range matches {
-		negIndex := match[1]
-		index, _ := strconv.Atoi(negIndex)
-
-		arrayPath := strings.Split(path, negIndex)[0]
-		if strings.HasSuffix(arrayPath, ".") {
-			arrayPath = arrayPath[:len(arrayPath)-1]
-		}
-
-		array := gjson.Get(jsonStr, arrayPath)
-		if array.IsArray() {
-			length := len(array.Array())
-			actualIndex := length + index
-			if actualIndex >= 0 && actualIndex < length {
-				result = strings.Replace(result, match[0], "."+strconv.Itoa(actualIndex), 1)
-			}
-		}
-	}
-
-	return result
-}
+// processNegativeIndex walks the path and resolves ".-N" against the array length at that point.
+func processNegativeIndex(jsonStr string, path string) string {
+	if path == "" {
+		return ""
+	}
+	re := regexp.MustCompile(`\.-(\d+)`) // or use package-level negativeIndexRe
+	result := path
+	offset := 0
+	for {
+		loc := re.FindStringSubmatchIndex(result[offset:])
+		if loc == nil {
+			break
+		}
+		start := offset + loc[0]
+		end := offset + loc[1]
+		digitsStart := offset + loc[2]
+		digitsEnd := offset + loc[3]
+		idx, err := strconv.Atoi("-" + result[digitsStart:digitsEnd])
+		if err != nil {
+			offset = end
+			continue
+		}
+		arrayPath := strings.TrimSuffix(result[:start], ".")
+		arr := gjson.Get(jsonStr, arrayPath)
+		if arr.IsArray() {
+			length := len(arr.Array())
+			actual := length + idx
+			if actual >= 0 && actual < length {
+				repl := "." + strconv.Itoa(actual)
+				result = result[:start] + repl + result[end:]
+				offset = start + len(repl)
+				continue
+			}
+		}
+		offset = end
+	}
+	return result
+}


// compareGjsonValues 直接比较两个gjson.Result,支持所有比较模式
func compareGjsonValues(jsonValue, targetValue gjson.Result, mode string) (bool, error) {
switch mode {
Expand Down Expand Up @@ -274,21 +309,25 @@ func applyOperations(jsonStr string, operations []ParamOperation) (string, error
if !ok {
continue // 条件不满足,跳过当前操作
}
// 处理路径中的负数索引
opPath := processNegativeIndex(result, op.Path)
opFrom := processNegativeIndex(result, op.From)
opTo := processNegativeIndex(result, op.To)

Comment on lines +312 to 316

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Validate required fields after preprocessing.

Prevent operations with empty paths (e.g., missing from/to for move) to avoid surprises like querying the root with empty path.

 		opPath := processNegativeIndex(result, op.Path)
 		opFrom := processNegativeIndex(result, op.From)
 		opTo := processNegativeIndex(result, op.To)
+		// basic validation
+		switch op.Mode {
+		case "move":
+			if opFrom == "" || opTo == "" {
+				return "", fmt.Errorf("move requires both 'from' and 'to'")
+			}
+		default:
+			if opPath == "" {
+				return "", fmt.Errorf("%s requires non-empty 'path'", op.Mode)
+			}
+		}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// 处理路径中的负数索引
opPath := processNegativeIndex(result, op.Path)
opFrom := processNegativeIndex(result, op.From)
opTo := processNegativeIndex(result, op.To)
// 处理路径中的负数索引
opPath := processNegativeIndex(result, op.Path)
opFrom := processNegativeIndex(result, op.From)
opTo := processNegativeIndex(result, op.To)
// basic validation
switch op.Mode {
case "move":
if opFrom == "" || opTo == "" {
return "", fmt.Errorf("move requires both 'from' and 'to'")
}
default:
if opPath == "" {
return "", fmt.Errorf("%s requires non-empty 'path'", op.Mode)
}
}
🤖 Prompt for AI Agents
In relay/common/override.go around lines 312 to 316, after calling
processNegativeIndex for op.Path, op.From, and op.To, validate that required
path fields are non-empty (e.g., op.Path for most ops, and both op.From and
op.To for move operations); if any required path is empty, return an explicit
error (or skip the operation) instead of continuing and potentially querying the
root — ensure validation happens after preprocessing so negative-index
resolution is considered.

switch op.Mode {
case "delete":
result, err = sjson.Delete(result, op.Path)
result, err = sjson.Delete(result, opPath)
case "set":
if op.KeepOrigin && gjson.Get(result, op.Path).Exists() {
if op.KeepOrigin && gjson.Get(result, opPath).Exists() {
continue
}
result, err = sjson.Set(result, op.Path, op.Value)
result, err = sjson.Set(result, opPath, op.Value)
case "move":
result, err = moveValue(result, op.From, op.To)
result, err = moveValue(result, opFrom, opTo)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Moving into a descendant of source will delete the newly set value.

Current order (set then delete) removes the destination when toPath is under fromPath. Handle descendant case by deleting first, then setting with the captured value.

Proposed change in moveValue (outside this hunk):

 func moveValue(jsonStr, fromPath, toPath string) (string, error) {
   sourceValue := gjson.Get(jsonStr, fromPath)
   if !sourceValue.Exists() {
     return jsonStr, fmt.Errorf("source path does not exist: %s", fromPath)
   }
-  result, err := sjson.Set(jsonStr, toPath, sourceValue.Value())
-  if err != nil {
-    return "", err
-  }
-  return sjson.Delete(result, fromPath)
+  // Delete-first if destination is a descendant of source.
+  if toPath == fromPath || strings.HasPrefix(toPath, fromPath+".") {
+    tmp, err := sjson.Delete(jsonStr, fromPath)
+    if err != nil {
+      return "", err
+    }
+    return sjson.Set(tmp, toPath, sourceValue.Value())
+  }
+  result, err := sjson.Set(jsonStr, toPath, sourceValue.Value())
+  if err != nil {
+    return "", err
+  }
+  return sjson.Delete(result, fromPath)
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
result, err = moveValue(result, opFrom, opTo)
func moveValue(jsonStr, fromPath, toPath string) (string, error) {
sourceValue := gjson.Get(jsonStr, fromPath)
if !sourceValue.Exists() {
return jsonStr, fmt.Errorf("source path does not exist: %s", fromPath)
}
// Delete-first if destination is a descendant of source.
if toPath == fromPath || strings.HasPrefix(toPath, fromPath+".") {
tmp, err := sjson.Delete(jsonStr, fromPath)
if err != nil {
return "", err
}
return sjson.Set(tmp, toPath, sourceValue.Value())
}
// Default: set then delete
result, err := sjson.Set(jsonStr, toPath, sourceValue.Value())
if err != nil {
return "", err
}
return sjson.Delete(result, fromPath)
}
🤖 Prompt for AI Agents
In relay/common/override.go around line 326, the call currently does set then
delete which causes the destination to be removed when toPath is a descendant of
fromPath; modify moveValue so it first detects if toPath is a descendant of
fromPath, capture the source value into a temporary variable, perform the delete
on fromPath first, then set the captured value at toPath (otherwise keep the
existing set-then-delete flow). Ensure the descendant check is robust (path
prefix or tree-structure comparison) and preserve existing error handling and
return values.

case "prepend":
result, err = modifyValue(result, op.Path, op.Value, op.KeepOrigin, true)
result, err = modifyValue(result, opPath, op.Value, op.KeepOrigin, true)
case "append":
result, err = modifyValue(result, op.Path, op.Value, op.KeepOrigin, false)
result, err = modifyValue(result, opPath, op.Value, op.KeepOrigin, false)
default:
return "", fmt.Errorf("unknown operation: %s", op.Mode)
}
Expand Down