~mkhl/xplor

ref: be5b77024950f8fed4c7910775e152f743db81df xplor/xplor.go -rw-r--r-- 8.6 KiB View raw
be5b7702 — Martin Kühl Fix handling deeply nested entries 1 year, 5 days ago
                                                                                
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
// 2010 - Mathieu Lonjaret
// 2018 - Martin Kühl

// The xplor program is an acme files explorer, tree style.
package main

import (
	"bytes"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	"9fans.net/go/acme"
	"9fans.net/go/plan9"
	"9fans.net/go/plumb"
)

const (
	this     = "xplor"
	tag      = "Get All Up Win Xplor "
	tab      = "\t"
	flagFile = " "
	flagLess = "▸"
	flagMore = "▾"
)

var (
	PLAN9 = os.Getenv("PLAN9")
	all   = flag.Bool("a", false, "Include directory entries whose names begin with a dot (.)")
	open  = map[string]bool{}
	win   *acme.Win
	root  string
)

func usage() {
	fmt.Fprintf(os.Stderr, "usage: %s [options] [path]\n", this)
	flag.PrintDefaults()
	os.Exit(2)
}

func main() {
	log.SetFlags(0)
	flag.Usage = usage
	flag.Parse()
	if err := setup(); err != nil {
		log.Fatal(err)
	}
	defer win.CloseFiles()
	for e := range win.EventChan() {
		if err := handle(e); err != nil {
			log.Print(err)
		}
	}
}

// Setup

func setup() error {
	if err := findRoot(); err != nil {
		return err
	}
	return openWindow()
}

func findRoot() error {
	switch flag.NArg() {
	case 0: // start at .
		var err error
		root, err = os.Getwd()
		return err
	case 1: // start at path
		var err error
		root = filepath.Clean(flag.Arg(0))
		if !filepath.IsAbs(root) {
			root, err = filepath.Abs(root)
			if err != nil {
				return err
			}
		}
		info, err := os.Stat(root)
		if err != nil {
			return err
		}
		if !info.IsDir() {
			return fmt.Errorf("%s: Not a directory", root)
		}
		return nil
	default:
		usage()
		return nil
	}
}

func openWindow() error {
	var err error
	win, err = acme.New()
	if err != nil {
		return err
	}
	if err := win.Fprintf("tag", "%s", tag); err != nil {
		return err
	}
	if err := win.Ctl("dump %s", this); err != nil {
		return err
	}
	if err := win.Ctl("dumpdir %s", root); err != nil {
		return err
	}
	return draw()
}

// Drawing Structure

func draw() error {
	if err := win.Name("%s-%s/", this, root); err != nil {
		return err
	}
	var b bytes.Buffer
	if err := printRoot(&b); err != nil {
		return err
	}
	if _, err := win.Write("data", b.Bytes()); err != nil {
		return err
	}
	if err := win.Ctl("clean"); err != nil {
		return err
	}
	return focus(root)
}

func redraw() error {
	win.Clear()
	return draw()
}

func redrawDir(path, addr string, depth int) error {
	if open[path] {
		return insertDir(path, addr, depth)
	} else {
		return removeDir(path, addr, depth)
	}
}

// Directory Listing

func printRoot(w io.Writer) error {
	if err := printDir(w, root, 0); err != nil {
		return err
	}
	_, err := io.WriteString(w, "\n") // so acme can write after the last entry
	return err
}

func printDir(w io.Writer, dir string, depth int) error {
	infos, err := ioutil.ReadDir(dir)
	if err != nil {
		return err
	}
	tabs := strings.Repeat(tab, depth)
	for _, info := range infos {
		name := info.Name()
		if strings.HasPrefix(name, ".") && !*all {
			continue
		}
		path := filepath.Join(dir, name)
		flag := flagFile
		if info.IsDir() {
			flag = flagLess
			if open[path] {
				flag = flagMore
			}
		}
		if _, err := fmt.Fprintf(w, "%s %s%s\n", flag, tabs, name); err != nil {
			return err
		}
		if flag == flagMore {
			if err := printDir(w, path, depth+1); err != nil {
				return err
			}
		}
	}
	return nil
}

func insertDir(path, addr string, depth int) error {
	name := filepath.Base(path)
	tabs := strings.Repeat(tab, depth)
	if err := win.Addr("%s-+", addr); err != nil {
		return err
	}
	var b bytes.Buffer
	if _, err := fmt.Fprintf(&b, "%s %s%s\n", flagMore, tabs, name); err != nil {
		return err
	}
	if err := printDir(&b, path, depth+1); err != nil {
		return err
	}
	_, err := win.Write("data", b.Bytes())
	return err
}

func removeDir(path, addr string, depth int) error {
	name := filepath.Base(path)
	var end strings.Builder // next line with at most depth tabs
	end.WriteString("^$")
	for i := 0; i <= depth; i++ {
		tabs := strings.Repeat(tab, i)
		fmt.Fprintf(&end, "|^..%s[^%s]", tabs, tab)
	}
	if err := win.Addr("%s-/^/+/^/,%s+/%s/-/^/", addr, addr, end.String()); err != nil {
		return err
	}
	tabs := strings.Repeat(tab, depth)
	return win.Fprintf("data", "%s %s%s\n", flagLess, tabs, name)
}

// Buffer Interaction

func toggleAll() error {
	*all = !*all
	return redraw()
}

func goUp() error {
	root = filepath.Join(root, "..")
	return redraw()
}

// Line Interaction

func look(addr string) error {
	path, depth, err := abspath(addr)
	if err != nil {
		return err
	}
	info, err := os.Stat(path)
	if err != nil {
		return err
	}
	if !info.IsDir() {
		return send(path)
	}
	open[path] = !open[path]
	if err := redrawDir(path, addr, depth); err != nil {
		return err
	}
	return focus(path)
}

func focus(path string) error {
	path, err := filepath.Rel(root, path)
	if err != nil {
		return err
	}
	var b strings.Builder
	b.WriteString("#0")
	for depth, name := range split(path) {
		tabs := strings.Repeat(tab, depth)
		fmt.Fprintf(&b, "+/^..%s%s/", tabs, name)
	}
	if err := win.Addr("%s", b.String()); err != nil {
		return err
	}
	return win.Ctl("dot=addr\nshow")
}

func print(addr string) error {
	path, _, err := abspath(addr)
	if err != nil {
		return err
	}
	log.Print(path)
	return nil
}

// Parsing Structure

// Determine entry name, depth
func entry(format string, args ...interface{}) (string, int, error) {
	fail := func(err error) (string, int, error) {
		return "", 0, err
	}
	if err := win.Addr(format, args...); err != nil {
		return fail(err)
	}
	buf, err := win.ReadAll("xdata")
	if err != nil {
		return fail(err)
	}
	line := strings.TrimSuffix(string(buf), "\n")
	if !strings.Contains(line, " ") {
		return fail(nil)
	}
	line = strings.SplitN(line, " ", 2)[1]
	name := strings.TrimLeft(line, tab)
	depth := (len(line) - len(name)) / len(tab)
	return name, depth, nil
}

// Determine absolute path, depth
func abspath(addr string) (string, int, error) {
	fail := func(err error) (string, int, error) {
		return "", 0, err
	}
	dir, depth, err := entry("%s-+", addr) // line containing addr
	if err != nil {
		return fail(err)
	}
	if dir == "" {
		return fail(nil)
	}
	for level := depth; level > 0; level-- {
		tabs := strings.Repeat(tab, level-1)
		parent, _, err := entry("%s-/^..%s[^%s]/-+", addr, tabs, tab) // line at depth before addr
		if err != nil {
			return fail(err)
		}
		dir = filepath.Join(parent, dir)
	}
	return filepath.Join(root, dir), depth, nil
}

// Determine components of path
func split(path string) []string {
	var part string
	parts := make([]string, 0)
	for path != "" && path != "." {
		path, part = filepath.Split(path)
		path = filepath.Clean(path)
		parts = append([]string{part}, parts...)
	}
	return parts
}

// System Interaction

func send(path string) error {
	port, err := plumb.Open("send", plan9.OWRITE)
	if err != nil {
		return err
	}
	defer port.Close()
	msg := &plumb.Message{
		Src:  this,
		Dst:  "",
		Dir:  root,
		Type: "text",
		Data: []byte(path),
	}
	return msg.Send(port)
}

func run(exe, dir string) error {
	cmd := exec.Command(exe)
	cmd.Dir = dir
	return cmd.Start()
}

// Event Handling

func handle(e *acme.Event) error {
	switch e.C2 {
	// exec
	// - tag
	case 'x':
		switch string(e.Text) {
		case "Del":
			return win.Del(true)
		case "Get":
			return redraw()
		case "All":
			return toggleAll()
		case "Up":
			return goUp()
		case "Win":
			exe := filepath.Join(PLAN9, "bin", "win")
			dir, err := loc(e)
			if err != nil {
				return err
			}
			return run(exe, dir)
		case "Xplor":
			exe := this
			dir, err := loc(e)
			if err != nil {
				return err
			}
			return run(exe, dir)
		default:
			return win.WriteEvent(e)
		}
	// - body
	case 'X':
		if isComplex(e) {
			return win.WriteEvent(e)
		}
		return print(q(e))
	// look
	// - tag
	case 'l':
		return win.WriteEvent(e)
	// - body
	case 'L':
		if isComplex(e) {
			return win.WriteEvent(e)
		}
		return look(q(e))
	default:
		return nil
	}
}

func isComplex(e *acme.Event) bool {
	if e.OrigQ0 != e.OrigQ1 {
		// user has selected text
		return true
	}
	if e.Flag&8 != 0 {
		// user has chorded argument
		return true
	}
	return false
}

func q(e *acme.Event) string {
	return fmt.Sprintf("#%d", e.OrigQ0)
}

func loc(e *acme.Event) (string, error) {
	fail := func(err error) (string, error) {
		return "", err
	}
	if e.Flag&8 == 0 {
		return fail(nil)
	}
	loc := string(e.Loc)
	if loc == "" {
		return fail(nil)
	}
	prefix := fmt.Sprintf("%s-%s:", this, root)
	if !strings.HasPrefix(loc, prefix) {
		return fail(nil)
	}
	loc = strings.TrimPrefix(loc, prefix)
	addrs := strings.SplitN(loc, ",", 2)
	dir, _, err := abspath(addrs[0])
	if err != nil {
		return fail(err)
	}
	info, err := os.Stat(dir)
	if err != nil {
		return fail(err)
	}
	if info.IsDir() {
		return dir, nil
	}
	return filepath.Dir(dir), nil
}