ollie/tools/file_read

54 lines
1.5 KiB
Bash
Executable File

#!/usr/bin/env bash
# ollie:parallel read
# description: Read a file from the local filesystem with optional offset and line limit
# Args: <file_path> [offset] [limit]
file_path="$1"
offset="${2:-1}"
limit="${3:-2000}"
max_line_len=2000
max_size=$((8 * 1024 * 1024))
[ -z "$file_path" ] && echo "usage: file_read <file_path> [offset] [limit]" && exit 1
[[ "$file_path" != /* ]] && echo "error: path must be absolute, got: $file_path" && exit 1
[ ! -f "$file_path" ] && [ -e "$file_path" ] && echo "error: not a regular file: $file_path" && exit 1
if [ -z "$OLLIE_SESSION_ID" ]; then
echo "error: OLLIE_SESSION_ID is not set"
exit 1
fi
mkdir -p "/tmp/ollie/$OLLIE_SESSION_ID"
marker="/tmp/ollie/$OLLIE_SESSION_ID/$(printf '%s' "$file_path" | sha256sum | cut -c1-64)"
if [ ! -e "$file_path" ]; then
echo "(new file)"
: > "$marker"
exit 0
fi
size=$(wc -c < "$file_path")
[ "$size" -gt "$max_size" ] && echo "error: file too large ($size bytes, max $max_size)" && exit 1
if ! head -c 8192 "$file_path" | LC_ALL=C tr -d '\0' | cmp -s - <(head -c 8192 "$file_path"); then
echo "(binary file)"
exit 0
fi
content=$(awk -v off="$offset" -v lim="$limit" -v maxlen="$max_line_len" '
NR >= off && NR < off+lim {
if (length($0) > maxlen) print substr($0, 1, maxlen) "..."
else print
}
NR >= off+lim { exit }
' "$file_path")
if [ -z "$content" ]; then
echo "(empty file)"
else
printf '%s\n' "$content"
fi
# save content to marker (used by file_edit/file_write as staging area)
cp "$file_path" "$marker"