-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.go
More file actions
364 lines (343 loc) · 10.9 KB
/
Copy pathmain.go
File metadata and controls
364 lines (343 loc) · 10.9 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
package main
import (
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
tea "github.com/charmbracelet/bubbletea"
"github.com/sendbird/ccx/internal/clauderegistry"
"github.com/sendbird/ccx/internal/cli"
"github.com/sendbird/ccx/internal/kitty"
"github.com/sendbird/ccx/internal/session"
"github.com/sendbird/ccx/internal/tui"
"gopkg.in/yaml.v3"
)
var version = "dev"
func defaultConfigHeader() string {
return "# ccx configuration\n# Keybindings: session, actions, views, navigation\n# Preferences: preferences section (auto-saved on quit)\n# Claude: command_template controls local Claude launches; {{args}} expands to ccx-provided args.\n# Open: command_template controls how URLs open; {{url}} expands to the URL (empty = OS default open/xdg-open).\n\n"
}
func runConfigCommand(args []string) error {
if len(args) == 0 {
return fmt.Errorf("usage: ccx config <view|edit|path|get|set> [path] [value]")
}
path := filepath.Join(os.Getenv("HOME"), ".config", "ccx", "config.yaml")
switch args[0] {
case "path":
fmt.Println(path)
return nil
case "view", "list", "ls":
data, err := os.ReadFile(path)
if err != nil {
return err
}
fmt.Print(string(data))
return nil
case "edit":
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return err
}
if _, err := os.Stat(path); os.IsNotExist(err) {
if err := os.WriteFile(path, []byte(defaultConfigHeader()), 0644); err != nil {
return err
}
}
editor := os.Getenv("EDITOR")
if editor == "" {
editor = "vi"
}
cmd := exec.Command(editor, path)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
case "get":
if len(args) != 2 {
return fmt.Errorf("usage: ccx config get <dot.path>")
}
cfg, err := readConfigMap(path)
if err != nil {
return err
}
val, ok := getConfigPath(cfg, args[1])
if !ok {
return fmt.Errorf("config path not found: %s", args[1])
}
data, err := yaml.Marshal(val)
if err != nil {
return err
}
fmt.Print(string(data))
return nil
case "set":
if len(args) != 3 {
return fmt.Errorf("usage: ccx config set <dot.path> <value>")
}
cfg, err := readConfigMap(path)
if err != nil {
return err
}
setConfigPath(cfg, args[1], parseConfigValue(args[2]))
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return err
}
data, err := yaml.Marshal(cfg)
if err != nil {
return err
}
if err := os.WriteFile(path, []byte(defaultConfigHeader()+string(data)), 0644); err != nil {
return err
}
fmt.Printf("%s = %v\n", args[1], parseConfigValue(args[2]))
return nil
default:
return fmt.Errorf("unknown config command %q", args[0])
}
}
func readConfigMap(path string) (map[string]interface{}, error) {
cfg := map[string]interface{}{}
data, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return cfg, nil
}
return nil, err
}
if err := yaml.Unmarshal(data, &cfg); err != nil {
return nil, err
}
return cfg, nil
}
func getConfigPath(cfg map[string]interface{}, dotPath string) (interface{}, bool) {
cur := interface{}(cfg)
for _, part := range strings.Split(dotPath, ".") {
m, ok := cur.(map[string]interface{})
if !ok {
return nil, false
}
cur, ok = m[part]
if !ok {
return nil, false
}
}
return cur, true
}
func setConfigPath(cfg map[string]interface{}, dotPath string, value interface{}) {
parts := strings.Split(dotPath, ".")
cur := cfg
for _, part := range parts[:len(parts)-1] {
next, _ := cur[part].(map[string]interface{})
if next == nil {
next = map[string]interface{}{}
cur[part] = next
}
cur = next
}
cur[parts[len(parts)-1]] = value
}
func parseConfigValue(value string) interface{} {
switch value {
case "true":
return true
case "false":
return false
case "null", "nil", "~":
return nil
default:
return value
}
}
func main() {
var (
showVersion bool
claudeDir string
tmuxEnabled bool
tmuxAutoLive bool
initialFocus string
worktreeDir string
searchQuery string
groupMode string
previewMode string
viewMode string
sessionID string
jumpSession string
jumpUUID string
)
// Handle subcommands before global flag parsing
if len(os.Args) > 1 {
switch os.Args[1] {
case "sessions":
fs := flag.NewFlagSet("sessions", flag.ExitOnError)
all := fs.Bool("all", false, "list all sessions (default: current tmux window only)")
pick := fs.Bool("pick", false, "launch interactive picker and emit JSON on stdout")
search := fs.String("search", "", "initial filter query (same syntax as TUI /)")
multi := fs.Bool("multi", false, "allow multi-select (with --pick)")
dirFlag := fs.String("dir", "", "path to Claude data directory (default: ~/.claude)")
fs.Parse(os.Args[2:])
dir := resolveClaudeDir(*dirFlag)
if *pick {
os.Exit(int(cli.RunPickSessionTUI(dir, *search, *multi)))
}
if err := cli.RunSessions(dir, *all); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
os.Exit(0)
case "config":
if err := runConfigCommand(os.Args[2:]); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
os.Exit(0)
case "move":
fs := flag.NewFlagSet("move", flag.ExitOnError)
sess := fs.String("session", "", "session ID to move (prefix match); default: current tmux window's session")
from := fs.String("from", "", "project directory to move by path instead of session ID (moves every session under it)")
dirFlag := fs.String("dir", "", "path to Claude data directory (default: ~/.claude)")
fs.Usage = func() {
fmt.Fprintf(os.Stderr, "Move a Claude session's project path to a new location.\n\n")
fmt.Fprintf(os.Stderr, "Usage:\n")
fmt.Fprintf(os.Stderr, " ccx move <new-path> Move current tmux session's project path\n")
fmt.Fprintf(os.Stderr, " ccx move --session <id> <new-path> Move a specific session by ID\n")
fmt.Fprintf(os.Stderr, " ccx move --from <dir> <new-path> Move a project dir by path (no session lookup)\n\n")
fmt.Fprintf(os.Stderr, "Flags:\n")
fs.PrintDefaults()
}
fs.Parse(os.Args[2:])
if fs.NArg() != 1 {
fs.Usage()
os.Exit(1)
}
dir := resolveClaudeDir(*dirFlag)
if err := cli.RunMove(dir, *sess, *from, fs.Arg(0)); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
os.Exit(0)
case "urls", "refs", "files", "changes", "images", "conversation", "info", "help":
subcmd := os.Args[1]
fs := flag.NewFlagSet(subcmd, flag.ExitOnError)
plain := fs.Bool("plain", false, "force plain text output (no interactive picker)")
fs.Parse(os.Args[2:])
dir := resolveClaudeDir("")
result, err := cli.Run(subcmd, dir, *plain)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
if result != nil && result.JumpSession != "" {
// Picker selected "jump to conversation" — launch full TUI
jumpSession = result.JumpSession
jumpUUID = result.JumpUUID
claudeDir = dir
} else {
os.Exit(0)
}
}
}
// Only parse global flags if we didn't handle a subcommand
if jumpSession == "" {
flag.BoolVar(&showVersion, "version", false, "print version and exit")
flag.BoolVar(&showVersion, "v", false, "print version and exit (shorthand)")
flag.StringVar(&claudeDir, "dir", "", "path to Claude data directory (default: ~/.claude)")
flag.BoolVar(&tmuxEnabled, "tmux", false, "enable tmux integration (auto-detected if inside tmux)")
flag.BoolVar(&tmuxAutoLive, "tmux-auto-live", false, "auto-enter live session in same tmux window on startup")
flag.StringVar(&initialFocus, "initial-focus", "", "startup focus strategy: tmux (default: tmux window match, else most recent) | cwd (adds a CWD-based directory-walk fallback before most recent)")
flag.StringVar(&worktreeDir, "worktree-dir", ".worktree", "subdirectory name for git worktrees")
flag.StringVar(&searchQuery, "search", "", "start with session list filtered by search query")
flag.StringVar(&groupMode, "group", "", "initial group mode (flat|proj|tree|chain|fork|repo|projects|daily)")
flag.StringVar(&previewMode, "preview", "", "initial preview mode (conv|stats|mem|scratch|tasks|agents|wf|shells|contexts|refs|outputs)")
flag.StringVar(&viewMode, "view", "", "initial view (sessions|config|plugins|stats)")
flag.StringVar(&sessionID, "session", "", "open a specific session by ID (prefix match)")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "ccx — Claude Code Explorer\n\n")
fmt.Fprintf(os.Stderr, "Usage: ccx [flags]\n")
fmt.Fprintf(os.Stderr, " ccx <command> [--plain]\n")
fmt.Fprintf(os.Stderr, " ccx config <view|edit|path|get|set> ...\n\n")
fmt.Fprintf(os.Stderr, "Commands:\n")
for _, c := range cli.Commands {
fmt.Fprintf(os.Stderr, " %-10s %s\n", c.Name, c.Desc)
}
fmt.Fprintf(os.Stderr, "\nFlags:\n")
flag.PrintDefaults()
}
flag.Parse()
if showVersion {
fmt.Println("ccx", version)
os.Exit(0)
}
claudeDir = resolveClaudeDir(claudeDir)
}
if !tmuxEnabled && os.Getenv("TMUX") != "" {
tmuxEnabled = true
}
configPath := filepath.Join(os.Getenv("HOME"), ".config", "ccx", "config.yaml")
km, _, _, _, cc, oc, _ := tui.LoadCCXConfig(configPath)
initialSessions := session.LoadCachedSessions(claudeDir)
if len(initialSessions) == 0 {
livePaths := clauderegistry.Cwds()
initialSessions, _ = session.ScanSessionsForPaths(claudeDir, livePaths)
}
// Live sessions started since the last full scan aren't in the cache;
// pull them in so the first paint already shows them as [LIVE].
initialSessions = session.MergeLiveSessions(claudeDir, initialSessions)
if sessionID != "" {
found := false
for _, s := range initialSessions {
if strings.HasPrefix(s.ID, sessionID) {
jumpSession = s.ID
found = true
break
}
}
if !found {
if s, ok := session.FindSessionByID(claudeDir, sessionID); ok {
initialSessions = append([]session.Session{s}, initialSessions...)
jumpSession = s.ID
} else {
fmt.Fprintf(os.Stderr, "Error: session %q not found\n", sessionID)
os.Exit(1)
}
}
}
app := tui.NewApp(initialSessions, tui.Config{
ClaudeDir: claudeDir,
TmuxEnabled: tmuxEnabled,
TmuxAutoLive: tmuxAutoLive,
InitialFocus: initialFocus,
WorktreeDir: worktreeDir,
SearchQuery: searchQuery,
Keymap: km,
GroupMode: groupMode,
PreviewMode: previewMode,
ViewMode: viewMode,
JumpSession: jumpSession,
JumpUUID: jumpUUID,
Claude: cc,
Open: oc,
})
p := tea.NewProgram(app, tea.WithAltScreen(), tea.WithMouseCellMotion())
if _, err := p.Run(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
// Clear any Kitty inline images before exiting
if kitty.Supported() {
fmt.Print(kitty.ClearImages())
}
}
func resolveClaudeDir(dir string) string {
if dir == "" {
dir = os.Getenv("CLAUDE_CONFIG_DIR")
}
if dir == "" {
home, err := os.UserHomeDir()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
dir = home + "/.claude"
}
return dir
}