forked from ktr0731/evans
/
cli.go
78 lines (64 loc) · 1.74 KB
/
cli.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
package cli
import (
"context"
"fmt"
"io"
"os"
"time"
"github.com/ktr0731/evans/adapter/cui"
"github.com/ktr0731/evans/config"
"github.com/ktr0731/evans/di"
"github.com/ktr0731/evans/usecase"
"github.com/ktr0731/evans/usecase/port"
isatty "github.com/mattn/go-isatty"
)
// TODO: define cli mode scoped config
var DefaultReader io.Reader = os.Stdin
type LaunchError struct {
err error
}
func (e *LaunchError) Error() string {
return fmt.Sprintf("failed to launch CLI mode: %s", e.err)
}
// Run is a main entrypoint for CLI mode.
// cli package will executes Run if Evans is launched as CLI mode.
//
// Run returns below errors (Clients should unwrap returned error with errors.Cause):
// - os.PathError
// - Provided `file` is missing.
// - It is returned only when `file` is not empty.
// - ErrLaunchFailed
// - Precondition error to launch CLI mode.
// - TODO: Describe more error specification.
//
func Run(cfg *config.Config, ui cui.UI, file, call string) error {
in := DefaultReader
if file != "" {
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
in = f
}
p, err := di.NewCLIInteractorParams(cfg, in)
if err != nil {
return &LaunchError{err}
}
closeCtx, closeCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer closeCancel()
defer p.Cleanup(closeCtx)
interactor := usecase.NewInteractor(p)
res, err := interactor.Call(&port.CallParams{RPCName: call})
if err != nil {
return err
}
if _, err := io.Copy(ui.Writer(), res); err != nil {
return err
}
return nil
}
// IsCLIMode returns whether Evans was launched as CLI mode or not.
func IsCLIMode(file string) bool {
return (!isatty.IsTerminal(os.Stdin.Fd()) && !isatty.IsCygwinTerminal(os.Stdin.Fd())) || file != ""
}