/
root.go
214 lines (168 loc) · 5.37 KB
/
root.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
package cmd
import (
"context"
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/empiricaly/empirica"
cloudcmd "github.com/empiricaly/empirica/cmds/empirica/cmd/cloud"
"github.com/empiricaly/empirica/internal/settings"
logger "github.com/empiricaly/empirica/internal/utils/log"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
func defineRoot() (*cobra.Command, *bool, error) {
// usingConfigFile tracks if the config comes from a file.
isUsingConfigFile := false
usingConfigFile := &isUsingConfigFile
// cmd represents the base command when called without any subcommands.
cmd := &cobra.Command{
Use: "empirica",
Short: "empirica is an engine for multiplayer interactive experiments",
// Long: ``,
SilenceUsage: true,
SilenceErrors: true,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return root(cmd, args, usingConfigFile)
},
}
// HACK: conflicting args between 2 calls, same flags. cobra/viper "bug"?
if len(os.Args) < 2 || os.Args[1] != "serve" {
if err := empirica.ConfigFlags(cmd); err != nil {
return nil, nil, errors.Wrap(err, "define flags")
}
if err := viper.BindPFlags(cmd.Flags()); err != nil {
return nil, nil, errors.Wrap(err, "bind root flags")
}
}
cfgDesc := fmt.Sprintf("config file (default is %s/empirica.toml)", settings.EmpiricaDir)
cmd.PersistentFlags().String("config", "", cfgDesc)
if err := viper.BindPFlags(cmd.PersistentFlags()); err != nil {
return nil, nil, errors.Wrap(err, "bind root persistent flags")
}
return cmd, usingConfigFile, nil
}
const closeMaxCuration = time.Second * 5
func root(_ *cobra.Command, _ []string, usingConfigFile *bool) error {
ctx := initContext()
if err := settings.InstallVoltaIfNeeded(ctx); err != nil {
return errors.Wrap(err, "check node")
}
dir, err := os.Getwd()
if err != nil {
return errors.Wrap(err, "get current dir")
}
if err := settings.Check("", dir); err != nil {
if errors.Is(err, settings.ErrEmpiricaDirMissing) {
fmt.Fprintf(os.Stderr, `You do not seem to be in an Empirica project (%s directory not found). You can
create a new project with:
empirica create myproject
(this will create a new directory named 'myproject' in the current directory)
`, settings.EmpiricaDir)
os.Exit(1)
}
return errors.Wrap(err, "check empirica dir")
}
conf := getConfig(true)
t, err := empirica.Start(ctx, conf, *usingConfigFile)
if err != nil {
return errors.Wrap(err, "failed to start")
}
<-ctx.Done()
// Give the closing a few seconds to cleanup
ctx, cancel := context.WithTimeout(context.Background(), closeMaxCuration)
defer cancel()
t.Close(ctx)
log.Debug().Msg("empirica: stopped")
return nil
}
func failedStart(err error) {
if err != nil {
log.Fatal().Err(err).Msg("empirica: failed to start")
}
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
settings.InitShared()
rootCmd, usingConfigFile, err := defineRoot()
if err != nil {
failedStart(err)
}
failedStart(addCreateCommand(rootCmd))
failedStart(addBundleCommand(rootCmd))
failedStart(addServeCommand(rootCmd))
failedStart(addSetupCommand(rootCmd))
failedStart(addNodeCommand(rootCmd))
failedStart(addNPMCommand(rootCmd))
failedStart(addUpgradeCommand(rootCmd))
failedStart(addVersionCommand(rootCmd))
failedStart(addTajribaCommand(rootCmd))
failedStart(addExportCommand(rootCmd))
failedStart(addPathsCommand(rootCmd))
failedStart(addUtilsCommands(rootCmd))
failedStart(cloudcmd.AddCloudCommand(rootCmd))
cobra.OnInitialize(initConfig(rootCmd, usingConfigFile))
if err := rootCmd.Execute(); err != nil {
failedStart(err)
}
}
// initConfig reads in config file and ENV variables if set.
func initConfig(rootCmd *cobra.Command, usingConfigFile *bool) func() {
return func() {
cfgFile, err := rootCmd.PersistentFlags().GetString("config")
if err != nil {
log.Fatal().Err(err).Msg("empirica: failed to parse config file flag")
}
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
viper.AddConfigPath(fmt.Sprintf("./%s", settings.EmpiricaDir))
viper.SetConfigName("empirica")
}
viper.SetEnvPrefix("empirica")
viper.AutomaticEnv()
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
*usingConfigFile = true
}
conf := getConfig()
if err := logger.Init(conf.Log); err != nil {
log.Fatal().Err(err).Msg("empirica: failed to init logging")
}
}
}
func getConfig(validate ...bool) *empirica.Config {
conf := new(empirica.Config)
if err := viper.Unmarshal(conf); err != nil {
log.Fatal().Err(err).Msg("could not parse configuration")
}
if len(validate) > 0 && validate[0] {
if err := conf.Validate(); err != nil {
log.Fatal().Err(err).Msg("invalid config")
}
}
return conf
}
func initContext() context.Context {
ctx, cancel := context.WithCancel(context.Background())
go func() {
s := make(chan os.Signal, 1)
signal.Notify(s, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGHUP)
<-s
cancel()
s = make(chan os.Signal, 1)
signal.Notify(s, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
<-s
log.Fatal().Msg("empirica: force quit")
}()
return ctx
}