aboutsummaryrefslogtreecommitdiffstats
path: root/tools/fs_patch.sh
blob: 2d9d7e4dea16bc060bf04215a9bcf3e8e271f966 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/env bash
set -uo pipefail

# @describe Apply a patch to a file at the specified path.
# NOTE: This tool NEVER exits with non-zero (even on missing args). It reports errors in output.
# @option --path The path of the file to apply to
# @option --contents The patch to apply to the file
# @env LLM_OUTPUT=/dev/stdout The output path

ROOT_DIR="${LLM_ROOT_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
OUT="${LLM_OUTPUT:-/dev/stdout}"

err() {
  echo "ERROR: $*" >> "$OUT"
  exit 0
}

main() {
  path="${argc_path:-}"
  patch="${argc_contents:-}"

  [[ -z "${path}" ]]  && err "missing --path"
  [[ -z "${patch}" ]] && err "missing --contents"
  [[ ! -e "${path}" ]] && err "file not found: ${path}"
  [[ ! -f "${path}" ]] && err "not a regular file: ${path}"
  [[ ! -r "${path}" ]] && err "file not readable: ${path}"

  new_contents=""
  if ! new_contents="$(awk -f "$ROOT_DIR/utils/patch.awk" "$path" <(printf "%s" "$patch") 2>/tmp/fs_patch.err)"; then
    msg="$(cat /tmp/fs_patch.err 2>/dev/null || true)"
    err "patch apply failed for ${path}: ${msg:-unknown error}"
  fi

  # Diff in Tool-Output schreiben (damit das LLM es sieht)
  printf "%s" "$new_contents" | git diff --no-index "$path" - >> "$OUT" 2>/dev/null || true

  # Guard kann “abbrechen” -> als ERROR ausgeben, aber exit 0
  if ! "$ROOT_DIR/utils/guard_operation.sh" "Apply changes?" >>"$OUT" 2>&1; then
    err "operation cancelled by user"
  fi

  if ! printf "%s" "$new_contents" > "$path" 2>/tmp/fs_patch_write.err; then
    msg="$(cat /tmp/fs_patch_write.err 2>/dev/null || true)"
    err "failed to write patched file ${path}: ${msg:-unknown error}"
  fi

  echo "The patch applied to: ${path}" >> "$OUT"
  exit 0
}

# IMPORTANT: Do not let argc failures abort the script.
# - remove "set -e"
# - and swallow argc's non-zero return
eval "$(argc --argc-eval "$0" "$@" 2>/tmp/argc_fs_patch.err || true)"

# If argc itself failed (e.g. parse error), report but still exit 0
if [[ -s /tmp/argc_fs_patch.err ]]; then
  echo "ERROR: argc parse failed: $(cat /tmp/argc_fs_patch.err)" >> "$OUT"
  rm -f /tmp/argc_fs_patch.err
  exit 0
fi
rm -f /tmp/argc_fs_patch.err

main