-
Notifications
You must be signed in to change notification settings - Fork 33
/
util.go
681 lines (554 loc) · 14.8 KB
/
util.go
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
package cmd
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"text/template"
"time"
log "github.com/Sirupsen/logrus"
"github.com/fatih/color"
"github.com/sahib/brig/client"
"github.com/sahib/brig/cmd/pwd"
"github.com/sahib/brig/defaults"
"github.com/sahib/brig/util/pwutil"
"github.com/sahib/brig/util/registry"
"github.com/urfave/cli"
)
var (
// backend delivers overly descriptive error messages including
// the string below. Simply filter this info:
rpcErrPattern = regexp.MustCompile(`\s*server/capnp/local_api.capnp.*rpc exception:\s*`)
)
// ExitCode is an error that maps the error interface to a specific error
// message and a unix exit code
type ExitCode struct {
Code int
Message string
}
func (err ExitCode) Error() string {
return err.Message
}
func getRepoEntryFromRegistry(ctx *cli.Context, port int64) (*registry.Entry, error) {
reg, err := registry.Open()
if err != nil {
return nil, err
}
entries, err := reg.List()
if err != nil {
return nil, err
}
// Shortcut: If there's only one repo, always connect to that.
if len(entries) == 1 {
return entries[0], nil
}
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
// Scan three times.
// First: Check if we're in some repo:
for _, entry := range entries {
if entry.Path == cwd {
logVerbose(ctx, "Found path via current working dir: %s", cwd)
return entry, nil
}
}
// Second: Check if we have a matching port.
// This is only used if the port was explicitly set
// (and we did not guess).
for _, entry := range entries {
if entry.Port == port {
logVerbose(ctx, "Found path via port (%d): %s", port, entry.Path)
return entry, nil
}
}
// Third: Check for defaults:
for _, entry := range entries {
if entry.IsDefault {
logVerbose(ctx, "Found path via is_default %s", entry.Path)
return entry, nil
}
}
return nil, fmt.Errorf("no suitable registry entry found")
}
func mustAbsPath(path string) string {
absPath, err := filepath.Abs(path)
if err != nil {
fmt.Printf("Failed to get absolute repo path: %v", err)
os.Exit(1)
}
return absPath
}
func yesify(val bool) string {
if val {
return color.GreenString("yes")
}
return color.RedString("no")
}
func checkmarkify(val bool) string {
if val {
return color.GreenString("✔")
}
return ""
}
// guessRepoFolder tries to find the repository path
// by using a number of sources.
// This helper may call exit when it fails to get the path.
func guessRepoFolder(ctx *cli.Context, lookupGlobal bool) string {
if argPath := ctx.GlobalString("repo"); argPath != "" {
return mustAbsPath(argPath)
}
if lookupGlobal {
port := int64(-1)
if ctx.GlobalIsSet("port") {
port = ctx.GlobalInt64("port")
}
entry, err := getRepoEntryFromRegistry(ctx, port)
if err == nil {
return mustAbsPath(entry.Path)
}
fmt.Printf("Failed to get path from registry: %v\n", err)
}
cwdPath, err := os.Getwd()
if err != nil {
fmt.Printf("Failed to get current working dir: %v; aborting.", err)
os.Exit(1)
}
return mustAbsPath(cwdPath)
}
func guessNextFreePort(ctx *cli.Context) (int, error) {
if ctx.GlobalIsSet("port") {
return ctx.GlobalInt("port"), nil
}
reg, err := registry.Open()
if err != nil {
return 0, err
}
entries, err := reg.List()
if err != nil {
return 0, err
}
maxPort := 0
if len(entries) == 0 {
// Use the default value.
maxPort = ctx.GlobalInt("port")
} else {
for _, entry := range entries {
if int(entry.Port) > maxPort {
maxPort = int(entry.Port)
}
}
// Always start checking with at least
// the next higher port.
maxPort++
}
maxAttempts := 1000
for off := 0; off <= maxAttempts; off++ {
conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%d", maxPort+off))
if err != nil {
return maxPort + off, nil
}
conn.Close()
}
return 0, fmt.Errorf(
"failed to find next free port after %d attempts",
maxAttempts,
)
}
func guessPort(ctx *cli.Context) int {
if ctx.GlobalIsSet("port") {
return ctx.GlobalInt("port")
}
entry, err := getRepoEntryFromRegistry(ctx, -1)
if err == nil && entry.Port > 0 {
logVerbose(ctx, "found port from global registry: %d", entry.Port)
return int(entry.Port)
}
port := ctx.GlobalInt("port")
logVerbose(ctx, "using port from global --port option: %d", port)
return port
}
func readPasswordFromArgs(basePath string, ctx *cli.Context) string {
if ctx.Bool("no-password") {
return "no-password"
}
if pwHelper := ctx.String("pw-helper"); pwHelper != "" {
password, err := pwutil.ReadPasswordFromHelper(basePath, pwHelper)
if err == nil {
return password
}
logVerbose(ctx, "failed to read password from '%s': %v\n", pwHelper, err)
}
// Note: the "--no-password" switch of init is handled by
// setting a password command that echoes a static password.
for curr := ctx; curr != nil; {
if password := curr.String("password"); password != "" {
return password
}
curr = curr.Parent()
}
return ""
}
func readPassword(ctx *cli.Context, repoPath string) (string, error) {
isInitialized, err := repoIsInitialized(repoPath)
if err != nil {
return "", err
}
if !isInitialized {
logVerbose(ctx, "repository is not initialized, skipping password entry")
return "", nil
}
// Try to read the password from -x or fallback to the default
// password if requested by the --no-pass switch.
if password := readPasswordFromArgs(repoPath, ctx); password != "" {
return password, nil
}
// Read the password from stdin:
password, err := pwd.PromptPassword()
if err != nil {
return "", err
}
return password, nil
}
func prefixSlash(s string) string {
if !strings.HasPrefix(s, "/") {
return "/" + s
}
return s
}
type cmdHandlerWithClient func(ctx *cli.Context, ctl *client.Client) error
func getExecutablePath() (string, error) {
// NOTE: This might not work on other platforms.
// In this case we fall back to LookPath().
exePath, err := os.Readlink("/proc/self/exe")
if err != nil {
return exec.LookPath("brig")
}
return filepath.Clean(exePath), nil
}
func startDaemon(ctx *cli.Context, repoPath string, port int) (*client.Client, error) {
exePath, err := getExecutablePath()
if err != nil {
return nil, err
}
logVerbose(ctx, "using executable path: %s", exePath)
// If a password helper is configured, we should not ask the password right here.
askPassword := true
cfg, err := defaults.OpenMigratedConfig(filepath.Join(repoPath, "config.yml"))
if err != nil {
logVerbose(ctx, "failed to open config for guessing password method: %v", err)
} else {
if cfg.String("repo.password_command") != "" {
askPassword = false
}
}
bindHost := ctx.GlobalString("bind")
logVerbose(
ctx,
"No Daemon running at %s:%d. Starting daemon from binary: %s",
bindHost,
port,
exePath,
)
daemonArgs := []string{
"--repo", repoPath,
"--port", strconv.FormatInt(int64(port), 10),
"--bind", bindHost,
"daemon", "launch",
}
argString := fmt.Sprintf("'%s'", strings.Join(daemonArgs, "' '"))
logVerbose(ctx, "Starting daemon as: %s %s", exePath, argString)
proc := exec.Command(exePath, daemonArgs...)
if askPassword {
logVerbose(ctx, "asking password since no password command was given")
pwd, err := readPassword(ctx, repoPath)
if err != nil {
return nil, err
}
if len(pwd) != 0 {
proc.Env = append(proc.Env, fmt.Sprintf("BRIG_PASSWORD=%s", pwd))
}
}
if err := proc.Start(); err != nil {
log.Infof("Failed to start the daemon: %v", err)
return nil, err
}
// This will likely suffice for most cases:
time.Sleep(300 * time.Millisecond)
warningPrinted := false
for i := 0; i < 25; i++ {
ctl, err := client.Dial(context.Background(), port)
if err != nil {
// Only print this warning once...
if !warningPrinted && i >= 10 {
log.Warnf("Waiting for daemon to bootup... :/")
warningPrinted = true
}
time.Sleep(50 * time.Millisecond)
continue
}
return ctl, nil
}
return nil, fmt.Errorf("Daemon could not be started or took to long. Wrong password maybe?")
}
func guessNextRepoFolder(ctx *cli.Context) string {
absify := func(path string) string {
absPath, err := filepath.Abs(path)
if err != nil {
// Better stop, before we do something stupid:
log.Errorf("failed to get absolute path: %s", path)
os.Exit(1)
}
return absPath
}
if folder := ctx.Args().Get(1); len(folder) > 0 {
return absify(folder)
}
if folder := ctx.GlobalString("repo"); len(folder) > 0 {
return absify(folder)
}
folder, err := os.Getwd()
if err != nil {
log.Warningf("failed to get current working dir: %s", folder)
return "."
}
return folder
}
func withDaemonAlways(handler cmdHandlerWithClient) cli.ActionFunc {
return withExit(func(ctx *cli.Context) error {
port, err := guessNextFreePort(ctx)
if err != nil {
return err
}
logVerbose(ctx, "using port %d for starting a new daemon.", port)
folder := guessNextRepoFolder(ctx)
logVerbose(ctx, "using path %s for new daemon.", folder)
// Start the server & pass the password:
ctl, err := startDaemon(ctx, folder, port)
if err != nil {
return ExitCode{
DaemonNotResponding,
fmt.Sprintf("Unable to start daemon: %v", err),
}
}
// Run the actual handler:
return handler(ctx, ctl)
})
}
func withDaemon(handler cmdHandlerWithClient, startNew bool) cli.ActionFunc {
// If not, make sure we start a new one:
return withExit(func(ctx *cli.Context) error {
port := guessPort(ctx)
if startNew {
logVerbose(ctx, "using port %d to check for running daemon.", port)
} else {
logVerbose(ctx, "using port %d to connect to old daemon.", port)
}
// Check if the daemon is running:
ctl, err := client.Dial(context.Background(), port)
if err == nil {
defer ctl.Close()
return handler(ctx, ctl)
}
if !startNew {
// Daemon was not running and we may not start a new one.
return ExitCode{DaemonNotResponding, "Daemon not running"}
}
// Start the server & pass the password:
folder := guessRepoFolder(ctx, true)
logVerbose(ctx, "starting new daemon in background, on folder '%s'", folder)
ctl, err = startDaemon(ctx, folder, port)
if err != nil {
return ExitCode{
DaemonNotResponding,
fmt.Sprintf("Unable to start daemon: %v", err),
}
}
// Run the actual handler:
defer ctl.Close()
return handler(ctx, ctl)
})
}
type checkFunc func(ctx *cli.Context) int
func withArgCheck(checker checkFunc, handler cli.ActionFunc) cli.ActionFunc {
return func(ctx *cli.Context) error {
if checker(ctx) != Success {
os.Exit(BadArgs)
}
return handler(ctx)
}
}
func prettyPrintError(err error) string {
return rpcErrPattern.ReplaceAllString(err.Error(), " ")
}
func withExit(handler cli.ActionFunc) cli.ActionFunc {
return func(ctx *cli.Context) error {
if err := handler(ctx); err != nil {
log.Error(prettyPrintError(err))
cerr, ok := err.(ExitCode)
if !ok {
os.Exit(UnknownError)
}
os.Exit(cerr.Code)
}
os.Exit(Success)
return nil
}
}
func needAtLeast(min int) checkFunc {
return func(ctx *cli.Context) int {
if ctx.NArg() < min {
if min == 1 {
log.Warningf("Need at least %d argument.", min)
} else {
log.Warningf("Need at least %d arguments.", min)
}
if err := cli.ShowCommandHelp(ctx, ctx.Command.Name); err != nil {
log.Warningf("Failed to display --help: %v", err)
}
return BadArgs
}
return Success
}
}
func repoIsInitialized(dir string) (bool, error) {
fd, err := os.Open(dir)
if err != nil && os.IsNotExist(err) {
return false, nil
}
if err != nil {
return false, err
}
names, err := fd.Readdirnames(-1)
if err != nil {
return false, err
}
return len(names) >= 1, nil
}
// tempFileWithSuffix works the same as ioutil.TempFile(),
// but allows for the addition of a suffix to the filepath.
// This has the nice side effect that some editors can recognize
// the filetype based on the ending and provide you syntax highlighting.
// (this is used in edit() below)
func tempFileWithSuffix(dir, prefix, suffix string) (f *os.File, err error) {
if dir == "" {
dir = os.TempDir()
}
for i := 0; i < 10000; i++ {
mid := strconv.Itoa(rand.Int())
name := filepath.Join(dir, prefix+mid+suffix)
f, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
if os.IsExist(err) {
continue
}
break
}
return
}
// editToPath opens up $EDITOR with `data` and saves the edited data
// to a temporary path that is then returned.
func editToPath(data []byte, suffix string) (string, error) {
editor := os.Getenv("EDITOR")
if editor == "" {
// It makes my heart bleed, but assume that vi is too hard
// for the majority I've met & that might use brig.
editor = "nano"
}
fd, err := tempFileWithSuffix("", "brig-cmd-buffer-", suffix)
if err != nil {
return "", err
}
doDelete := false
// Make sure it gets cleaned up.
defer func() {
if doDelete {
if err := os.Remove(fd.Name()); err != nil {
fmt.Printf("Failed to remove temp file: %v\n", err)
}
}
if err := fd.Close(); err != nil {
fmt.Printf("Failed to close file: %v\n", err)
}
}()
if _, err := fd.Write(data); err != nil {
return "", err
}
// Launch editor and hook it up with all necessary fds:
cmd := exec.Command(editor, fd.Name())
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
doDelete = true
return "", fmt.Errorf("Running $EDITOR (%s) failed: %v", editor, err)
}
if _, err := fd.Seek(0, io.SeekStart); err != nil {
doDelete = true
return "", err
}
return fd.Name(), nil
}
// edit opens up $EDITOR with `data` and returns the edited data.
func edit(data []byte, suffix string) ([]byte, error) {
tempPath, err := editToPath(data, suffix)
if err != nil {
return nil, err
}
defer func() {
if err := os.Remove(tempPath); err != nil {
fmt.Printf("Failed to remove temp file: %v\n", err)
}
}()
newData, err := ioutil.ReadFile(tempPath)
if err != nil {
return nil, err
}
// Some editors might add a trailing newline:
return bytes.TrimRight(newData, "\n"), nil
}
// parseDuration tries to convert the string `s` to
// a duration in seconds (+ fractions).
// It uses time.ParseDuration() internally, but allows
// whole numbers which are counted as seconds.
func parseDuration(s string) (float64, error) {
sec, err := strconv.ParseFloat(s, 64)
if err == nil {
return sec, nil
}
dur, err := time.ParseDuration(s)
if err != nil {
return 0.0, err
}
return float64(dur) / float64(time.Second), nil
}
func readFormatTemplate(ctx *cli.Context) (*template.Template, error) {
if ctx.IsSet("format") {
source := ctx.String("format") + "\n"
tmpl, err := template.New("format").Parse(source)
if err != nil {
return nil, err
}
return tmpl, nil
}
return nil, nil
}
func pinStateToSymbol(isPinned, isExplicit bool) string {
if isPinned {
colorFn := color.CyanString
if isExplicit {
colorFn = color.MagentaString
}
return colorFn("🖈")
}
return ""
}