Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
394 lines (361 loc) · 10.9 KB
/
Copy pathmain.go
File metadata and controls
394 lines (361 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
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
package main
import (
"bufio"
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"github.com/alecthomas/kong"
"github.com/josephschmitt/pj/internal/cache"
"github.com/josephschmitt/pj/internal/config"
"github.com/josephschmitt/pj/internal/discover"
"github.com/josephschmitt/pj/internal/icons"
)
var version = "dev"
type LabelsFlag string
func (l LabelsFlag) IsBool() bool { return true }
func (l *LabelsFlag) Decode(ctx *kong.DecodeContext) error {
token := ctx.Scan.Peek()
if token.IsValue() {
ctx.Scan.Pop()
val := token.String()
switch val {
case "label", "display":
*l = LabelsFlag(val)
default:
return fmt.Errorf("--labels must be 'label' or 'display', got %q", val)
}
} else {
*l = "label"
}
return nil
}
type CLI struct {
Config string `short:"c" help:"Config file path" type:"path"`
Path []string `short:"p" help:"Add search path (repeatable)"`
Marker []string `short:"m" help:"Add project marker (repeatable)"`
Exclude []string `short:"e" help:"Exclude pattern (repeatable)"`
MaxDepth int `short:"d" help:"Maximum search depth"`
NoIgnore bool `help:"Don't respect .gitignore and .ignore files"`
NoNested bool `help:"Don't search for projects inside other projects"`
Worktrees bool `help:"Discover git worktrees from parent repos, even outside search paths"`
NoWorktrees bool `help:"Exclude git worktrees from results" name:"no-worktrees"`
Icons bool `help:"Show marker-based icons"`
Strip bool `help:"Strip icons from output"`
IconMap []string `help:"Override icon mapping (MARKER:ICON)"`
Ansi bool `short:"a" help:"Colorize icons with ANSI codes"`
ColorMap []string `help:"Override icon color (MARKER:COLOR)"`
Labels LabelsFlag `short:"l" help:"Show marker label in output (label or display)"`
Format string `short:"f" help:"Custom output format (%p=path, %P=full-path, %n=name, %m=marker, %i=icon, %l=label, %L=display-label, %c=color, %w=worktree-parent)" default:""`
Shorten bool `short:"s" help:"Shorten home directory to ~ in output paths"`
NoCache bool `help:"Skip cache, force fresh search"`
ClearCache bool `help:"Clear cache and exit"`
Sort string `help:"Sort order: alpha, priority, label (default: priority)" default:"priority" enum:"alpha,priority,label"`
SortDirection string `help:"Sort direction: asc, desc (default: desc for priority, asc for alpha/label)" default:"" enum:",asc,desc" name:"sort-direction"`
JSON bool `short:"j" help:"Output results in JSON format"`
Verbose bool `short:"v" help:"Enable debug output"`
Version bool `short:"V" help:"Show version"`
}
func shortenHome(path, homeDir string) string {
if homeDir == "" {
return path
}
if path == homeDir {
return "~"
}
if strings.HasPrefix(path, homeDir+string(os.PathSeparator)) {
return "~" + path[len(homeDir):]
}
return path
}
func stdinIsPiped() bool {
stat, err := os.Stdin.Stat()
if err != nil {
return false
}
return (stat.Mode() & os.ModeCharDevice) == 0
}
func readPathsFromStdin(verbose bool) []string {
var paths []string
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
path := strings.TrimSpace(scanner.Text())
if path == "" {
continue
}
if strings.HasPrefix(path, "~") {
if home, err := os.UserHomeDir(); err == nil {
path = filepath.Join(home, path[1:])
}
}
if _, err := os.Stat(path); err != nil {
if verbose {
fmt.Fprintf(os.Stderr, "warning: skipping invalid path: %s\n", path)
}
continue
}
paths = append(paths, path)
}
return paths
}
func formatOutput(format string, values map[string]string) string {
const sentinel = "\x00PCT\x00"
result := strings.ReplaceAll(format, "%%", sentinel)
// Replace %P before %p to avoid %P being partially matched as %p + "P"
for _, placeholder := range []string{"%P", "%p", "%n", "%m", "%i", "%L", "%l", "%c", "%w"} {
if val, ok := values[placeholder]; ok {
result = strings.ReplaceAll(result, placeholder, val)
}
}
result = strings.ReplaceAll(result, sentinel, "%")
return result
}
func sortProjects(projects []discover.Project, sortBy, direction string, mapper *icons.Mapper) {
if direction == "" {
if sortBy == "priority" {
direction = "desc"
} else {
direction = "asc"
}
}
desc := direction == "desc"
sort.SliceStable(projects, func(i, j int) bool {
switch sortBy {
case "priority":
if projects[i].Priority != projects[j].Priority {
if desc {
return projects[i].Priority > projects[j].Priority
}
return projects[i].Priority < projects[j].Priority
}
return projects[i].Path < projects[j].Path
case "label":
labelI := mapper.GetLabel(projects[i].Marker)
labelJ := mapper.GetLabel(projects[j].Marker)
if labelI != labelJ {
if desc {
return labelI > labelJ
}
return labelI < labelJ
}
return projects[i].Path < projects[j].Path
default: // "alpha"
if desc {
return projects[i].Path > projects[j].Path
}
return projects[i].Path < projects[j].Path
}
})
}
func main() {
var cli CLI
ctx := kong.Parse(&cli,
kong.Name("pj"),
kong.Description("Fast project directory finder"),
kong.UsageOnError(),
)
if cli.Version {
fmt.Println("pj version", version)
os.Exit(0)
}
cfg, err := config.LoadWithVerbose(cli.Config, cli.Verbose)
if err != nil {
fmt.Fprintf(os.Stderr, "Error loading config: %v\n", err)
os.Exit(1)
}
if err := cfg.MergeFlags(&cli); err != nil {
fmt.Fprintf(os.Stderr, "Error merging config: %v\n", err)
os.Exit(1)
}
if cli.Worktrees && cli.NoWorktrees {
fmt.Fprintf(os.Stderr, "Error: --worktrees and --no-worktrees are mutually exclusive\n")
os.Exit(1)
}
stdinMode := false
if stdinIsPiped() {
stdinPaths := readPathsFromStdin(cli.Verbose)
if len(stdinPaths) > 0 {
cfg.SearchPaths = stdinPaths
stdinMode = true
}
}
if cli.Verbose {
fmt.Fprintf(os.Stderr, "Config: %+v\n", cfg)
}
homeDir := ""
if cli.Shorten {
homeDir, _ = os.UserHomeDir()
}
iconMapper := icons.NewMapper(cfg.GetIcons(), cfg.GetColors(), cfg.GetLabels(), cfg.GetDisplayLabels())
if len(cli.IconMap) > 0 {
for _, mapping := range cli.IconMap {
parts := strings.SplitN(mapping, ":", 2)
if len(parts) == 2 {
iconMapper.Set(parts[0], parts[1])
}
}
}
if len(cli.ColorMap) > 0 {
for _, mapping := range cli.ColorMap {
parts := strings.SplitN(mapping, ":", 2)
if len(parts) == 2 {
iconMapper.SetColor(parts[0], parts[1])
}
}
}
cacheManager := cache.New(cfg, cli.Verbose)
if cli.ClearCache {
if err := cacheManager.Clear(); err != nil {
fmt.Fprintf(os.Stderr, "Error clearing cache: %v\n", err)
os.Exit(1)
}
if cli.Verbose {
fmt.Fprintf(os.Stderr, "Cache cleared\n")
}
os.Exit(0)
}
var projects []discover.Project
if !cli.NoCache && !stdinMode {
cached, err := cacheManager.Get()
if err == nil && cached != nil {
if cli.Verbose {
fmt.Fprintf(os.Stderr, "Using cached results (%d projects)\n", len(cached))
}
projects = cached
} else if cli.Verbose && err != nil {
fmt.Fprintf(os.Stderr, "Cache miss: %v\n", err)
}
}
if projects == nil {
discoverer := discover.New(cfg, cli.Verbose)
projects, err = discoverer.Discover()
if err != nil {
fmt.Fprintf(os.Stderr, "Error discovering projects: %v\n", err)
os.Exit(1)
}
if cli.Verbose {
fmt.Fprintf(os.Stderr, "Discovered %d projects\n", len(projects))
}
if !stdinMode {
if err := cacheManager.Set(projects); err != nil && cli.Verbose {
fmt.Fprintf(os.Stderr, "Warning: failed to cache results: %v\n", err)
}
}
}
sortProjects(projects, cli.Sort, cli.SortDirection, iconMapper)
if cli.JSON {
type projectJSON struct {
Path string `json:"path"`
DisplayPath string `json:"displayPath,omitempty"`
Name string `json:"name"`
Marker string `json:"marker"`
MarkerLabel string `json:"markerLabel"`
MarkerDisplayLabel string `json:"markerDisplayLabel,omitempty"`
Icon string `json:"icon,omitempty"`
AnsiIcon string `json:"ansiIcon,omitempty"`
Color string `json:"color,omitempty"`
IsWorktree bool `json:"isWorktree,omitempty"`
WorktreeParent string `json:"worktreeParent,omitempty"`
}
type outputJSON struct {
Projects []projectJSON `json:"projects"`
}
jsonProjects := make([]projectJSON, len(projects))
for i, p := range projects {
icon := ""
ansiIcon := ""
color := ""
if cli.Icons {
icon = iconMapper.Get(p.Marker)
color = iconMapper.GetColor(p.Marker)
if cli.Ansi {
ansiIcon = iconMapper.Format(p.Marker, true)
}
}
displayPath := ""
if cli.Shorten {
displayPath = shortenHome(p.Path, homeDir)
}
displayLabel := iconMapper.GetDisplayLabel(p.Marker)
if p.IsWorktree && displayLabel != "" {
displayLabel += " (worktree)"
}
jsonProjects[i] = projectJSON{
Path: p.Path,
DisplayPath: displayPath,
Name: filepath.Base(p.Path),
Marker: p.Marker,
MarkerLabel: iconMapper.GetLabel(p.Marker),
MarkerDisplayLabel: displayLabel,
Icon: icon,
AnsiIcon: ansiIcon,
Color: color,
IsWorktree: p.IsWorktree,
WorktreeParent: p.WorktreeParent,
}
}
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
if err := enc.Encode(outputJSON{Projects: jsonProjects}); err != nil {
fmt.Fprintf(os.Stderr, "Error encoding JSON: %v\n", err)
os.Exit(1)
}
} else if cli.Format != "" {
for _, p := range projects {
icon := ""
if cli.Icons {
icon = iconMapper.Format(p.Marker, cli.Ansi)
}
displayPath := p.Path
if cli.Shorten {
displayPath = shortenHome(p.Path, homeDir)
}
displayLabel := iconMapper.GetDisplayLabel(p.Marker)
if p.IsWorktree && displayLabel != "" {
displayLabel += " (worktree)"
}
values := map[string]string{
"%p": displayPath,
"%P": p.Path,
"%n": filepath.Base(p.Path),
"%m": p.Marker,
"%i": icon,
"%l": icons.FormatLabel(iconMapper.GetLabel(p.Marker), cli.Ansi),
"%L": icons.FormatLabel(displayLabel, cli.Ansi),
"%c": iconMapper.GetColor(p.Marker),
"%w": p.WorktreeParent,
}
fmt.Println(formatOutput(cli.Format, values))
}
} else {
for _, p := range projects {
output := p.Path
if cli.Shorten {
output = shortenHome(output, homeDir)
}
if cli.Labels != "" {
label := ""
switch string(cli.Labels) {
case "label":
label = iconMapper.GetLabel(p.Marker)
case "display":
label = iconMapper.GetDisplayLabel(p.Marker)
}
if p.IsWorktree && label != "" {
label += " (worktree)"
}
if label != "" {
output = fmt.Sprintf("%s %s", icons.FormatLabel(label, cli.Ansi), output)
}
}
if cli.Icons && !cli.Strip {
icon := iconMapper.Format(p.Marker, cli.Ansi)
output = fmt.Sprintf("%s %s", icon, output)
}
fmt.Println(output)
}
}
ctx.Exit(0)
}