~mna/snow unlisted

ref: b80c93389bef70627bad6a5d2db7398350b0ef65 snow/cmd/internal/mainer/mainer.go -rw-r--r-- 1.8 KiB
b80c9338Martin Angers cmd/internal: add packages for command-line 1 year, 4 months 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
// Package mainer defines types relevant to command entrypoint
// implementation. A typical main entrypoint looks like this,
// assuming cmd is a struct which defines the command's flags
// and implements mainer.Mainer:
//
//   func main() {
//     var c cmd
//     os.Exit(int(c.Main(os.Args, mainer.CurrentStdio())))
//   }
//
package mainer

import (
	"context"
	"fmt"
	"io"
	"os"
	"os/signal"
)

// ExitCode is the type of a process exit code.
type ExitCode int

// List of pre-defined exit codes.
const (
	Success ExitCode = iota
	Failure
	InvalidArgs
)

// CurrentStdio returns the Stdio for the current process. Its Cwd
// field reflects the working directory at the time of the call.
func CurrentStdio() *Stdio {
	cwd, err := os.Getwd()
	if err != nil {
		panic(fmt.Sprintf("failed to get current working directory: %s", err))
	}
	return &Stdio{
		Cwd:    cwd,
		Stdin:  os.Stdin,
		Stdout: os.Stdout,
		Stderr: os.Stderr,
	}
}

// Stdio defines the OS abstraction for standard I/O.
type Stdio struct {
	// Cwd is the current working directory.
	Cwd string

	// Stdin is the standard input reader.
	Stdin io.Reader

	// Stdout is the standard output writer.
	Stdout io.Writer

	// Stderr is the standard error writer.
	Stderr io.Writer
}

// Mainer defines the method to implement for a type that
// implements a Main entrypoint of a command.
type Mainer interface {
	Main([]string, Stdio) ExitCode
}

// CancelOnSignal returns a context that is canceled when the process receives
// one of the specified signals.
func CancelOnSignal(ctx context.Context, signals ...os.Signal) context.Context {
	if len(signals) == 0 {
		return ctx
	}

	ctx, cancel := context.WithCancel(ctx)

	ch := make(chan os.Signal, 1)
	signal.Notify(ch, signals...)
	go func() {
		<-ch
		cancel()
	}()

	return ctx
}