-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·417 lines (376 loc) · 14.6 KB
/
install.sh
File metadata and controls
executable file
·417 lines (376 loc) · 14.6 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
#!/bin/bash
# OpenCode Config Installer
#
# Usage:
# curl -fsSL https://raw.githubusercontent.com/huyusong10/opencode-config/main/install.sh | bash
# ./install.sh [--link]
#
# Modes:
# --copy Copy files (default, standalone installation)
# --link Create symlinks (debug mode, may conflict with existing configs)
#
# Migration: This script migrates opencode.json to opencode.jsonc (JSON with Comments)
set -e
CONFIG_DIR="$HOME/.config/opencode"
MODE="copy"
# Files to exclude from backup and installation (runtime/generated files)
EXCLUDE_FILES="opencode-notifier-state.json node_modules package.json bun.lock package-lock.json .gitignore"
# Parse arguments
for arg in "$@"; do
case $arg in
--copy) MODE="copy" ;;
--link) MODE="link" ;;
esac
done
# Determine script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
IS_GIT_REPO=false
if [ -d "$SCRIPT_DIR/.git" ]; then
IS_GIT_REPO=true
REPO_DIR="$SCRIPT_DIR"
fi
echo "==> Installing opencode-config (mode: $MODE)"
# Check if config directory is writable
if [ -d "$CONFIG_DIR" ]; then
if [ ! -w "$CONFIG_DIR" ]; then
echo "==> ERROR: Config directory '$CONFIG_DIR' is not writable."
echo "==> Please check permissions or run with appropriate user."
exit 1
fi
else
# Try to create config directory
if ! mkdir -p "$CONFIG_DIR" 2>/dev/null; then
echo "==> ERROR: Cannot create config directory '$CONFIG_DIR'."
echo "==> Please check permissions: mkdir -p $CONFIG_DIR"
exit 1
fi
fi
mkdir -p "$CONFIG_DIR" || {
echo "==> ERROR: Cannot create config directory '$CONFIG_DIR'. Permission denied?"
exit 1
}
# Function to find existing config file (returns path or empty)
find_existing_config() {
local dir="$1"
if [ -f "$dir/opencode.jsonc" ]; then
echo "$dir/opencode.jsonc"
elif [ -f "$dir/opencode.json" ]; then
echo "$dir/opencode.json"
fi
}
# Function to merge opencode config files
# Supports both JSON and JSONC formats, outputs JSONC
merge_opencode_config() {
local source_file="$1" # Our config (opencode.jsonc)
local target_dir="$2" # User's config directory
local output_file="$target_dir/opencode.jsonc"
# Try Python merge (preferred)
if command -v python3 &>/dev/null; then
# Create temp Python script
PY_MERGE_SCRIPT=$(mktemp)
cat > "$PY_MERGE_SCRIPT" << 'PYEOF'
import json
import re
import sys
import os
def strip_jsonc_comments(content):
"""Remove // and /* */ comments from JSONC content."""
# Remove single-line comments (// ...)
# Be careful not to remove // inside strings
result = []
i = 0
in_string = False
string_char = None
while i < len(content):
char = content[i]
# Handle string boundaries
if not in_string and char in '"\'':
in_string = True
string_char = char
result.append(char)
i += 1
elif in_string:
if char == '\\' and i + 1 < len(content):
# Escape sequence, append both chars
result.append(char)
result.append(content[i + 1])
i += 2
elif char == string_char:
in_string = False
string_char = None
result.append(char)
i += 1
else:
result.append(char)
i += 1
# Handle // comments
elif char == '/' and i + 1 < len(content) and content[i + 1] == '/':
# Skip until end of line
while i < len(content) and content[i] != '\n':
i += 1
# Handle /* */ comments
elif char == '/' and i + 1 < len(content) and content[i + 1] == '*':
i += 2
while i < len(content):
if content[i] == '*' and i + 1 < len(content) and content[i + 1] == '/':
i += 2
break
i += 1
else:
result.append(char)
i += 1
return ''.join(result)
def parse_jsonc_file(filepath):
"""Parse a JSON or JSONC file."""
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
# Try parsing as-is first (might be valid JSON)
try:
return json.loads(content)
except json.JSONDecodeError:
pass
# Strip comments and try again
try:
stripped = strip_jsonc_comments(content)
return json.loads(stripped)
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JSON/JSONC in {filepath}: {e}")
def deep_merge(base, override, path=""):
"""Merge override into base with special handling for specific keys."""
result = json.loads(json.dumps(base)) # Deep copy
for key, value in override.items():
if key in result:
# Keys that should NOT override existing values
if key in ("model", "small_model", "$schema"):
# Keep existing value, don't override
continue
# Keys that should deep merge objects
if key in ("provider", "mcp"):
if isinstance(result[key], dict) and isinstance(value, dict):
result[key] = deep_merge(result[key], value, f"{path}.{key}")
else:
result[key] = value
elif key == "permission":
if isinstance(result[key], dict) and isinstance(value, dict):
for perm_key, perm_val in value.items():
if perm_key in result[key]:
if isinstance(result[key][perm_key], dict) and isinstance(perm_val, dict):
result[key][perm_key].update(perm_val)
else:
result[key][perm_key] = perm_val
else:
result[key][perm_key] = perm_val
else:
result[key] = value
elif key == "plugin":
if isinstance(result[key], list) and isinstance(value, list):
existing = set(result[key])
for item in value:
if item not in existing:
result[key].append(item)
else:
result[key] = value
elif key == "instructions":
if isinstance(result[key], list) and isinstance(value, list):
existing = set(result[key])
for item in value:
if item not in existing:
result[key].append(item)
else:
result[key] = value
else:
result[key] = value
else:
result[key] = value
return result
source_file = sys.argv[1]
target_dir = sys.argv[2]
output_file = sys.argv[3]
# Find existing config file (prefer opencode.jsonc over opencode.json)
existing_config = None
existing_jsonc = os.path.join(target_dir, "opencode.jsonc")
existing_json = os.path.join(target_dir, "opencode.json")
if os.path.exists(existing_jsonc):
existing_config = existing_jsonc
has_old_json = False
elif os.path.exists(existing_json):
existing_config = existing_json
has_old_json = True
else:
has_old_json = False
# Parse source file (our config)
try:
source = parse_jsonc_file(source_file)
except Exception as e:
print(f"ERROR: Failed to parse source config: {e}")
sys.exit(1)
# Merge or use source directly
if existing_config:
try:
target = parse_jsonc_file(existing_config)
merged = deep_merge(target, source)
print(f"Merged config from {existing_config}")
except Exception as e:
print(f"WARNING: Failed to parse existing config, using source: {e}")
merged = source
else:
merged = source
# Write output as JSONC (just JSON for now, comments are preserved from source logic)
try:
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(merged, f, indent=2, ensure_ascii=False)
f.write('\n')
print(f"Config saved to {output_file}")
except IOError as e:
print(f"ERROR: Failed to write config: {e}")
sys.exit(1)
# Remove old opencode.json if it existed (migration to JSONC)
if has_old_json and os.path.exists(existing_json):
try:
os.remove(existing_json)
print(f"Removed old {existing_json} (migrated to JSONC)")
except Exception as e:
print(f"WARNING: Failed to remove old opencode.json: {e}")
PYEOF
# Execute the merge script
python3 "$PY_MERGE_SCRIPT" "$source_file" "$target_dir" "$output_file"
rm -f "$PY_MERGE_SCRIPT"
return $?
fi
# Fallback: try jq if available (won't handle JSONC comments)
if command -v jq &>/dev/null; then
local existing_config
existing_config=$(find_existing_config "$target_dir")
if [ -n "$existing_config" ]; then
echo "==> WARNING: jq cannot parse JSONC comments, using simple merge"
local tmp_file
tmp_file=$(mktemp)
# Try to use a simple approach - just copy our config
# jq will fail on JSONC, so we copy directly
if jq '.' "$source_file" >/dev/null 2>&1; then
# Source is valid JSON (no comments or already stripped)
if jq '.' "$existing_config" >/dev/null 2>&1; then
# Both are valid JSON
if jq -s '.[0] * .[1]' "$existing_config" "$source_file" > "$tmp_file" 2>/dev/null; then
mv "$tmp_file" "$target_dir/opencode.jsonc"
echo "Merged config saved to $target_dir/opencode.jsonc (using jq)"
# Remove old opencode.json if exists
[ -f "$target_dir/opencode.json" ] && rm -f "$target_dir/opencode.json"
return 0
fi
fi
fi
fi
# Fallback: just copy
echo "==> WARNING: jq merge failed, copying config directly"
cp "$source_file" "$target_dir/opencode.jsonc"
[ -f "$target_dir/opencode.json" ] && rm -f "$target_dir/opencode.json"
return 0
fi
# Last resort: just copy (warn user)
echo "WARNING: Neither python3 nor jq found, copying config as-is."
cp "$source_file" "$target_dir/opencode.jsonc"
[ -f "$target_dir/opencode.json" ] && rm -f "$target_dir/opencode.json"
}
# Files and directories to install
INSTALL_ITEMS="AGENTS.md agent command plugin skills tui.json rules scripts"
# Install
if [ "$MODE" = "copy" ]; then
echo "==> Copying files..."
# Remove runtime/generated files
for exclude in $EXCLUDE_FILES; do
[ -e "$CONFIG_DIR/$exclude" ] && rm -rf "$CONFIG_DIR/$exclude"
done
if [ "$IS_GIT_REPO" = true ]; then
# Handle opencode.jsonc separately for merging
if [ -f "$REPO_DIR/opencode.jsonc" ]; then
echo "==> Processing opencode.jsonc..."
merge_opencode_config "$REPO_DIR/opencode.jsonc" "$CONFIG_DIR"
fi
# Copy other files
for item in $INSTALL_ITEMS; do
[ -e "$REPO_DIR/$item" ] && cp -r "$REPO_DIR/$item" "$CONFIG_DIR/"
done
else
TEMP_DIR=$(mktemp -d)
trap 'rm -rf "$TEMP_DIR"' EXIT
echo "==> Cloning repository to temporary directory..."
if ! git clone --depth 1 https://github.com/huyusong10/opencode-config.git "$TEMP_DIR" 2>/dev/null; then
echo "==> ERROR: Failed to clone repository. Please check your network connection."
exit 1
fi
# Handle opencode.jsonc separately for merging
if [ -f "$TEMP_DIR/opencode.jsonc" ]; then
echo "==> Processing opencode.jsonc..."
merge_opencode_config "$TEMP_DIR/opencode.jsonc" "$CONFIG_DIR"
fi
# Copy other files
for item in $INSTALL_ITEMS; do
[ -e "$TEMP_DIR/$item" ] && cp -r "$TEMP_DIR/$item" "$CONFIG_DIR/"
done
fi
echo "==> Installation complete! Config is now independent of the repository."
else
# Link mode - for debugging only
echo "==> WARNING: Symlink mode is for debugging only. It may conflict with existing configs."
# Backup existing config before replacing with symlinks
if [ -d "$CONFIG_DIR" ]; then
BACKUP="$CONFIG_DIR/backup_$(date +%Y%m%d_%H%M%S)"
if [ -d "$BACKUP" ]; then
BACKUP="$CONFIG_DIR/backup_$(date +%Y%m%d_%H%M%S)_$$"
fi
echo "==> Backing up existing config to $BACKUP"
mkdir -p "$BACKUP"
for item in AGENTS.md agent command plugin skills tui.json rules scripts opencode.jsonc opencode.json; do
if [ -e "$CONFIG_DIR/$item" ]; then
mv "$CONFIG_DIR/$item" "$BACKUP/" 2>/dev/null || true
fi
done
fi
# Remove runtime/generated files
for exclude in $EXCLUDE_FILES; do
[ -e "$CONFIG_DIR/$exclude" ] && rm -rf "$CONFIG_DIR/$exclude"
done
if [ "$IS_GIT_REPO" = true ]; then
echo "==> Creating symlinks..."
# Create symlink for opencode.jsonc
if [ -f "$REPO_DIR/opencode.jsonc" ]; then
ln -sf "$REPO_DIR/opencode.jsonc" "$CONFIG_DIR/opencode.jsonc"
fi
# Link directories
for item in $INSTALL_ITEMS; do
if [ -e "$REPO_DIR/$item" ]; then
ln -sf "$REPO_DIR/$item" "$CONFIG_DIR/$item"
fi
done
echo "==> Done! Run 'cd $REPO_DIR && git pull' to update."
else
echo "==> Cloning repository..."
REPO_DIR="$HOME/opencode-config"
if ! git clone --depth 1 https://github.com/huyusong10/opencode-config.git "$REPO_DIR" 2>/dev/null; then
if [ -d "$REPO_DIR/.git" ]; then
echo "==> Repository exists, updating..."
cd "$REPO_DIR" && git pull || {
echo "==> ERROR: Failed to update repository."
exit 1
}
cd - > /dev/null
else
echo "==> ERROR: Failed to clone repository. Please check your network connection."
exit 1
fi
fi
# Create symlink for opencode.jsonc
if [ -f "$REPO_DIR/opencode.jsonc" ]; then
ln -sf "$REPO_DIR/opencode.jsonc" "$CONFIG_DIR/opencode.jsonc"
fi
# Link directories
for item in $INSTALL_ITEMS; do
if [ -e "$REPO_DIR/$item" ]; then
ln -sf "$REPO_DIR/$item" "$CONFIG_DIR/$item"
fi
done
echo "==> Done! Run 'cd $REPO_DIR && git pull' to update."
fi
fi
echo "==> Installation complete!"