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

# @describe Read the contents of a file at the specified path.
# Use this when you need to examine the contents of an existing file.
# Without --offset and --limit the whole file is printed.
# @option --path! The path of the file to read
# @option --offset <NUM> Start reading at byte offset (0-based, default: 0)
# @option --limit <NUM> Maximum number of bytes to read
# @env LLM_OUTPUT=/dev/stdout The output path

OUT="${LLM_OUTPUT:-/dev/stdout}"
MAX_BYTES="${LLM_MAX_BYTES:-200000}"

sanitize() {
  if command -v iconv >/dev/null 2>&1; then
    iconv -f UTF-8 -t UTF-8 -c
  else
    cat
  fi
}

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

main() {
  path="${argc_path:-}"
  [[ -z "$path" ]] && err "missing --path"
  [[ ! -e "$path" ]] && err "file not found: $path"
  [[ ! -f "$path" ]] && err "not a regular file: $path"
  [[ ! -r "$path" ]] && err "file not readable: $path"

  # Heuristik: Binärdateien nicht in den Chat kippen
  if LC_ALL=C grep -qP '\x00' "$path" 2>/dev/null; then
    err "file appears to be binary (NUL bytes detected): $path"
  fi

  offset="${argc_offset:-0}"
  limit="${argc_limit:-}"

  # Begrenzung auf MAX_BYTES
  if [[ -z "$limit" ]]; then
    limit="$MAX_BYTES"
  elif [[ "$limit" -gt "$MAX_BYTES" ]]; then
    limit="$MAX_BYTES"
  fi

  if [[ "$offset" -eq 0 ]]; then
    head -c "$limit" "$path" | sanitize >> "$OUT"
  else
    dd if="$path" bs=1 skip="$offset" count="$limit" status=none 2>/dev/null | sanitize >> "$OUT"
  fi

  exit 0
}

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