-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaude-switch.sh
More file actions
424 lines (351 loc) · 11.8 KB
/
Copy pathclaude-switch.sh
File metadata and controls
424 lines (351 loc) · 11.8 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
418
419
420
421
422
423
424
#!/bin/bash
# claude-switch.sh - Bash version of claude-switch utility
# Switch between Claude Code settings profiles
#
# Note: this is derived from the Go version, which is the "canonical" implementation.
set -euo pipefail
PROG_NAME="claude-switch"
CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/$PROG_NAME"
CONFIG_FILE="${CLAUDE_SWITCH_CONFIG:-$CONFIG_DIR/claude-switch.json}"
SETTINGS_FILE="${CLAUDE_SWITCH_SETTINGS:-$HOME/.claude/settings.json}"
# Verify dependencies
if ! command -v jq &>/dev/null; then
echo "error: $PROG_NAME requires 'jq' but it is not installed" >&2
exit 1
fi
# Function to print usage
usage() {
cat >&2 <<EOF
Usage: $PROG_NAME [flags] [profile]
Switch between Claude Code settings.json profiles.
With no arguments, shows an interactive selection menu.
With a profile name, switches to that profile directly.
Flags:
-l, --list list available profiles
-c, --current show current active profile
-h, --help show this help message
Config: $CONFIG_FILE
Target: $SETTINGS_FILE
EOF
}
# Function to get current settings as compact JSON
get_current_settings() {
if [[ -f "$SETTINGS_FILE" ]]; then
jq -c . "$SETTINGS_FILE"
else
echo ""
fi
}
# Function to load config
load_config() {
if [[ -f "$CONFIG_FILE" ]]; then
cat "$CONFIG_FILE"
return 0
fi
return 1
}
# Function to initialize config (mirrors Go's initConfig)
init_config() {
mkdir -p "$(dirname "$CONFIG_FILE")"
local default_profile
if [[ -f "$SETTINGS_FILE" ]]; then
default_profile=$(jq -c . "$SETTINGS_FILE")
else
default_profile='{"model":"opus","effortLevel":"high"}'
fi
local z_profile='{"env":{"ANTHROPIC_AUTH_TOKEN":"your_zai_api_key","ANTHROPIC_BASE_URL":"https://api.z.ai/api/anthropic","API_TIMEOUT_MS":"3000000"}}'
# Build config with default and z profiles, then pretty-print
jq -n --argjson default "$default_profile" --argjson z "$z_profile" \
'{"default": $default, "z": $z}' > "$CONFIG_FILE"
printf 'Created config at:\n\n'
printf ' \033[32m%s\033[0m\n\n' "$CONFIG_FILE"
printf 'Your current ~/.claude/settings.json has been saved as the "default" profile.\n'
printf 'Edit the file to add more profiles, then run %s again. Each top-level key is a profile name.\nIts value becomes ~/.claude/settings.json when that profile is selected.\n' "$PROG_NAME"
}
# Function to calculate string similarity (returns integer 0-1000)
calculate_similarity() {
local str1="$1"
local str2="$2"
if [[ "$str1" == "$str2" ]]; then
echo "1000"
return
fi
if [[ -z "$str1" && -z "$str2" ]]; then
echo "1000"
return
fi
if [[ -z "$str1" || -z "$str2" ]]; then
echo "0"
return
fi
local len1=${#str1}
local len2=${#str2}
local max_len=$((len1 > len2 ? len1 : len2))
if [[ $max_len -eq 0 ]]; then
echo "1000"
return
fi
local matches=0
local min_len=$((len1 < len2 ? len1 : len2))
for ((i=0; i<min_len; i++)); do
if [[ "${str1:$i:1}" == "${str2:$i:1}" ]]; then
((matches++))
fi
done
echo $(( matches * 1000 / max_len ))
}
# Function to detect current profile
# Returns two lines: exact_match and closest_match (either may be empty)
detect_current_profile() {
local profiles_json="$1"
local current_settings
current_settings=$(get_current_settings)
if [[ -z "$current_settings" ]]; then
echo ""
echo ""
return
fi
# Try exact match first (compare compact JSON)
local profile_name
while IFS= read -r profile_name; do
[[ -z "$profile_name" ]] && continue
local profile_json
profile_json=$(jq -c --arg prof "$profile_name" '.[$prof]' <<< "$profiles_json")
if [[ "$current_settings" == "$profile_json" ]]; then
echo "$profile_name"
echo ""
return
fi
done < <(jq -r 'keys[]' <<< "$profiles_json")
# No exact match - find closest using string similarity
local best_score=0
local best_profile=""
while IFS= read -r profile_name; do
[[ -z "$profile_name" ]] && continue
local profile_json
profile_json=$(jq -c --arg prof "$profile_name" '.[$prof]' <<< "$profiles_json")
local score
score=$(calculate_similarity "$current_settings" "$profile_json")
if (( score > best_score )); then
best_score=$score
best_profile="$profile_name"
fi
done < <(jq -r 'keys[]' <<< "$profiles_json")
echo ""
echo "$best_profile"
}
# Read detect_current_profile results into two variables
read_profile_detection() {
local profiles_json="$1"
local result
result=$(detect_current_profile "$profiles_json")
DETECTED_EXACT=$(sed -n '1p' <<< "$result")
DETECTED_SIMILAR=$(sed -n '2p' <<< "$result")
}
# Function to apply profile
apply_profile() {
local profile_name="$1"
local profiles_json="$2"
local profile_data
profile_data=$(jq --arg prof "$profile_name" '.[$prof]' <<< "$profiles_json")
if [[ -z "$profile_data" || "$profile_data" == "null" ]]; then
echo "error: unknown profile '$profile_name'" >&2
return 1
fi
# Create settings directory if needed
mkdir -p "$(dirname "$SETTINGS_FILE")"
# Pretty-print with 2-space indent and trailing newline (matches Go's MarshalIndent)
jq --indent 2 '.' <<< "$profile_data" > "$SETTINGS_FILE"
}
# Function to get profile summary
profile_summary() {
local profile_name="$1"
local profiles_json="$2"
local profile_data
profile_data=$(jq -r --arg prof "$profile_name" '.[$prof]' <<< "$profiles_json")
local parts=()
while IFS= read -r key; do
[[ -z "$key" ]] && continue
local value_type
value_type=$(jq -r --arg k "$key" '.[$k] | type' <<< "$profile_data")
case "$value_type" in
string)
local value
value=$(jq -r --arg k "$key" '.[$k]' <<< "$profile_data")
parts+=("$key=$value")
;;
object)
if [[ "$key" == "env" ]]; then
local env_keys
env_keys=$(jq -r --arg k "$key" '.[$k] | keys | join(",")' <<< "$profile_data")
parts+=("env=[$env_keys]")
else
parts+=("$key={...}")
fi
;;
*)
local value
value=$(jq -r --arg k "$key" '.[$k]' <<< "$profile_data")
parts+=("$key=$value")
;;
esac
done < <(jq -r 'keys[]' <<< "$profile_data")
mapfile -t sorted_parts < <(printf '%s\n' "${parts[@]}" | sort)
echo "${sorted_parts[*]}"
}
# Function to list profiles
list_profiles() {
local profiles_json="$1"
read_profile_detection "$profiles_json"
local current_profile="$DETECTED_EXACT"
local similar_profile="$DETECTED_SIMILAR"
local profile_names
mapfile -t profile_names < <(jq -r 'keys[]' <<< "$profiles_json")
# Find max name length for formatting
local max_name_len=0
for name in "${profile_names[@]}"; do
if [[ ${#name} -gt $max_name_len ]]; then
max_name_len=${#name}
fi
done
# Print each profile
for name in "${profile_names[@]}"; do
local marker=" "
if [[ "$name" == "$current_profile" ]]; then
marker="* "
elif [[ -z "$current_profile" && "$name" == "$similar_profile" ]]; then
marker="~ "
fi
local summary
summary=$(profile_summary "$name" "$profiles_json")
printf "%s%-${max_name_len}s %s\n" "$marker" "$name" "$summary"
done
if [[ -z "$current_profile" && -n "$similar_profile" ]]; then
printf '\n\033[33m~\033[0m = closest match - current settings differ from all profiles. Some providers modify settings (e.g., model names).\n'
fi
}
# Function for interactive selection
interactive_select() {
local profiles_json="$1"
read_profile_detection "$profiles_json"
local current_profile="$DETECTED_EXACT"
echo "Available profiles:"
echo
local profile_names
mapfile -t profile_names < <(jq -r 'keys[]' <<< "$profiles_json")
local num_profiles=${#profile_names[@]}
# Find max name length for formatting
local max_name_len=0
for name in "${profile_names[@]}"; do
if [[ ${#name} -gt $max_name_len ]]; then
max_name_len=${#name}
fi
done
local idx_width=${#num_profiles}
# Print each profile with index
for ((i=0; i<num_profiles; i++)); do
local name="${profile_names[$i]}"
local marker=" "
if [[ "$name" == "$current_profile" ]]; then
marker="* "
fi
local summary
summary=$(profile_summary "$name" "$profiles_json")
printf "%s[%*d] %-*s %s\n" "$marker" "$idx_width" "$((i+1))" "$max_name_len" "$name" "$summary"
done
echo
printf "Select profile [1-%d] or name: " "$num_profiles"
local input
read -r input
if [[ -z "$input" ]]; then
return
fi
# Try numeric selection first
if [[ "$input" =~ ^[0-9]+$ ]]; then
if [[ $input -ge 1 && $input -le $num_profiles ]]; then
local selected_name="${profile_names[$((input-1))]}"
apply_profile "$selected_name" "$profiles_json"
echo "Switched to profile: $selected_name"
return
else
echo "error: invalid selection $input" >&2
exit 1
fi
fi
# Try named selection
if jq -e --arg prof "$input" 'has($prof)' <<< "$profiles_json" >/dev/null 2>&1; then
apply_profile "$input" "$profiles_json"
echo "Switched to profile: $input"
return
fi
printf 'error: unknown profile %q\n' "$input" >&2
exit 1
}
# Main execution
main() {
local list_flag=false
local current_flag=false
local profile_arg=""
# Parse flags
while [[ $# -gt 0 ]]; do
case $1 in
-l|--list)
list_flag=true
shift
;;
-c|--current)
current_flag=true
shift
;;
-h|--help)
usage
exit 0
;;
-*)
echo "Unknown flag: $1" >&2
usage
exit 1
;;
*)
profile_arg="$1"
shift
;;
esac
done
# Load config (or initialize if missing)
local profiles_json
if ! profiles_json=$(load_config); then
init_config
return
fi
# Execute based on flags and arguments
if [[ "$list_flag" == true ]]; then
list_profiles "$profiles_json"
elif [[ "$current_flag" == true ]]; then
read_profile_detection "$profiles_json"
if [[ -n "$DETECTED_EXACT" ]]; then
echo "$DETECTED_EXACT"
elif [[ -n "$DETECTED_SIMILAR" ]]; then
printf '(no exact match, closest: %s)\n' "$DETECTED_SIMILAR"
echo "" >&2
echo "Note: Some providers modify settings (e.g., model names), causing drift from saved profiles." >&2
else
echo "(no matching profile)"
fi
elif [[ -n "$profile_arg" ]]; then
if jq -e --arg prof "$profile_arg" 'has($prof)' <<< "$profiles_json" >/dev/null 2>&1; then
apply_profile "$profile_arg" "$profiles_json"
echo "Switched to profile: $profile_arg"
else
printf 'error: unknown profile %q\n' "$profile_arg" >&2
echo "Available profiles: $(jq -r 'keys | join(", ")' <<< "$profiles_json")" >&2
exit 1
fi
else
interactive_select "$profiles_json"
fi
}
# Run main function with all arguments (skip when sourced, e.g. for testing)
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi