-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopencode-stdin
More file actions
executable file
·100 lines (86 loc) · 2.5 KB
/
opencode-stdin
File metadata and controls
executable file
·100 lines (86 loc) · 2.5 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#!/usr/bin/env bash
set -euo pipefail
# Usage:
# opencode-stdin "Instruction here" [<extra claude flags>]
#
# Reads code from stdin, detects filetype from $NVIM_FILETYPE if set,
# builds a structured prompt, and prints Claude's response.
#
# If you want only code output, set CLAUDE_STRIP_CODEBLOCK=1.
INSTRUCTION=${1:-"Improve this code"}
shift || true
MODEL_ARGS=()
while [[ $# -gt 0 ]]; do
case "$1" in
-m|--model|--agent|-s|--session|-c|--continue|--share)
MODEL_ARGS+=("$1")
shift
if [[ $# -gt 0 && ! "$1" =~ ^- ]]; then
MODEL_ARGS+=("$1")
shift
fi
;;
--)
shift
while [[ $# -gt 0 ]]; do
MODEL_ARGS+=("$1")
shift
done
;;
*)
MODEL_ARGS+=("$1")
shift
;;
esac
done
CODE=$(cat)
FT="${NVIM_FILETYPE:-text}"
read -r -d '' PROMPT <<'EOF2' || true
You are an expert developer. Follow the user instruction and transform the provided code accordingly.
- Prefer deterministic, minimal changes unless explicitly asked otherwise.
- Keep semantics identical unless asked for a refactor or optimization.
- If returning code, reply with ONLY a single fenced code block in the same language.
EOF2
PROMPT+=$'\n\nUser instruction:\n'
PROMPT+="$INSTRUCTION"
PROMPT+=$'\n\nCode:\n'
PROMPT+="\`\`\`${FT}\n${CODE}\n\`\`\`"
if ! command -v claude >/dev/null 2>&1; then
echo "claude command not found in PATH" >&2
exit 127
fi
# Encourage non-interactive output if the CLI honors these flags/env vars.
: "${NO_COLOR:=1}"
: "${CLAUDE_NO_COLOR:=1}"
set +e
RAW_OUT=$(NO_COLOR="$NO_COLOR" CLAUDE_NO_COLOR="$CLAUDE_NO_COLOR" claude -p "${PROMPT}" "${MODEL_ARGS[@]}" 2>&1)
STATUS=$?
set -e
OUT=$RAW_OUT
# Strip ANSI escape sequences/spinners for clean buffer insertion.
if command -v python3 >/dev/null 2>&1; then
OUT=$(printf "%s" "$OUT" | python3 - <<'PY'
import sys, re
pattern = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]")
print(pattern.sub("", sys.stdin.read()).replace("\r", ""), end="")
PY
)
elif command -v perl >/dev/null 2>&1; then
OUT=$(printf "%s" "$OUT" | perl -pe 's/\e\[[0-9;?]*[ -\/]*[@-~]//g; s/\r//g')
else
# Fallback: remove a simple subset of color codes via parameter expansion.
OUT=${OUT//$'\e'\[*m/}
fi
if [[ $STATUS -ne 0 ]]; then
printf "claude command failed (exit %d)\n%s\n" "$STATUS" "$OUT"
exit 0
fi
if [[ "${CLAUDE_STRIP_CODEBLOCK:-0}" == "1" ]]; then
if grep -q '```' <<<"$OUT"; then
OUT="${OUT#*\`\`\`}"
OUT="${OUT#*$'\n'}"
OUT="${OUT%%\`\`\`*}"
OUT="${OUT%$'\n'}"
fi
fi
printf "%s" "$OUT"