aboutsummaryrefslogtreecommitdiffstats
path: root/tools/fs_write.sh
blob: 746c24b5f4a4a76ba3ca5396d8cdf409c284711b (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
#!/usr/bin/env bash
set -uo pipefail

# @describe Write the full file contents to a file at the specified path.
# @option --path! The path of the file to write to
# @option --contents! The full contents to write 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:-}"
  contents="${argc_contents:-}"

  [[ -z "$path" ]] && err "missing --path"
  # contents darf leer sein – das ist erlaubt (File leeren)
  dir="$(dirname "$path")"

  if [[ -e "$path" && ! -f "$path" ]]; then
    err "target exists but is not a regular file: $path"
  fi

  if [[ -f "$path" ]]; then
    # Diff in Output schreiben (damit LLM es sieht)
    printf "%s" "$contents" | git diff --no-index "$path" - >> "$OUT" 2>/dev/null || true
    if ! "$ROOT_DIR/utils/guard_operation.sh" "Apply changes?" >>"$OUT" 2>&1; then
      err "operation cancelled by user"
    fi
  else
    if ! "$ROOT_DIR/utils/guard_path.sh" "$path" "Write '$path'?" >>"$OUT" 2>&1; then
      err "operation cancelled by user"
    fi
    if ! mkdir -p "$dir" 2>/tmp/fs_write_mkdir.err; then
      msg="$(cat /tmp/fs_write_mkdir.err 2>/dev/null || true)"
      err "failed to create parent dir $dir: ${msg:-unknown error}"
    fi
  fi

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

  echo "The contents written to: $path" >> "$OUT"
  exit 0
}

eval "$(argc --argc-eval "$0" "$@")"
main