-
Notifications
You must be signed in to change notification settings - Fork 1
/
root.go
482 lines (386 loc) · 13.7 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
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
package cmd
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"os/exec"
"regexp"
"strings"
"time"
"github.com/gabor-boros/minutes/internal/pkg/client/toggl"
"github.com/gabor-boros/minutes/internal/pkg/client/timewarrior"
"github.com/gabor-boros/minutes/internal/cmd/utils"
"github.com/gabor-boros/minutes/internal/pkg/client/clockify"
"github.com/gabor-boros/minutes/internal/pkg/client/tempo"
"github.com/jedib0t/go-pretty/v6/progress"
"github.com/jedib0t/go-pretty/v6/table"
"github.com/gabor-boros/minutes/internal/pkg/client"
"github.com/gabor-boros/minutes/internal/pkg/worklog"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
const (
program string = "minutes"
defaultDateFormat string = "2006-01-02 15:04:05"
)
var (
configFile string
envPrefix string
version string
commit string
date string
sources = []string{"clockify", "tempo", "timewarrior", "toggl"}
targets = []string{"tempo"}
ErrNoSourceImplementation = errors.New("no source implementation found")
ErrNoTargetImplementation = errors.New("no target implementation found")
rootCmd = &cobra.Command{
Use: program,
Short: "Sync worklogs between multiple time trackers, invoicing, and bookkeeping software.",
Long: `
Minutes is a CLI tool for synchronizing work logs between multiple time
trackers, invoicing, and bookkeeping software to make entrepreneurs'
daily work easier.
Every source and destination comes with their specific flags. Before using any
flags, check the related documentation.
Minutes comes with absolutely NO WARRANTY; for more information, visit the
project's home page.
Project home page: https://gabor-boros.github.io/minutes
Report bugs at: https://github.com/gabor-boros/minutes/issues
Report security issues to: gabor.brs@gmail.com`,
Run: runRootCmd,
}
)
func init() {
envPrefix = strings.ToUpper(program)
cobra.OnInitialize(initConfig)
initCommonFlags()
initClockifyFlags()
initTempoFlags()
initTimewarriorFlags()
initTogglFlags()
}
func initConfig() {
if configFile != "" {
viper.SetConfigName(configFile)
} else {
homeDir, err := os.UserHomeDir()
cobra.CheckErr(err)
configDir, err := os.UserConfigDir()
cobra.CheckErr(err)
viper.AddConfigPath(homeDir)
viper.AddConfigPath(configDir)
viper.SetConfigName("." + program)
viper.SetConfigType("toml")
}
viper.SetEnvPrefix(envPrefix)
viper.AutomaticEnv()
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed(), configFile)
} else {
cobra.CheckErr(err)
}
// Bind flags to config value
cobra.CheckErr(viper.BindPFlags(rootCmd.Flags()))
}
func initCommonFlags() {
rootCmd.PersistentFlags().StringVar(&configFile, "config", "", fmt.Sprintf("config file (default is $HOME/.%s.yaml)", program))
rootCmd.Flags().StringP("start", "", "", "set the start date (defaults to 00:00:00)")
rootCmd.Flags().StringP("end", "", "", "set the end date (defaults to now)")
rootCmd.Flags().StringP("date-format", "", defaultDateFormat, "set start and end date format (in Go style)")
rootCmd.Flags().StringP("source-user", "", "", "set the source user ID")
rootCmd.Flags().StringP("source", "s", "", fmt.Sprintf("set the source of the sync %v", sources))
rootCmd.Flags().StringP("target-user", "", "", "set the source user ID")
rootCmd.Flags().StringP("target", "t", "", fmt.Sprintf("set the target of the sync %v", targets))
rootCmd.Flags().StringSliceP("table-sort-by", "", []string{utils.ColumnStart, utils.ColumnProject, utils.ColumnTask, utils.ColumnSummary}, fmt.Sprintf("sort table by column %v", utils.Columns))
rootCmd.Flags().StringSliceP("table-hide-column", "", []string{}, fmt.Sprintf("hide table column %v", utils.HideableColumns))
rootCmd.Flags().BoolP("tags-as-tasks", "", false, "treat tags matching the value of tags-as-tasks-regex as tasks")
rootCmd.Flags().StringP("tags-as-tasks-regex", "", "", "regex of the task pattern")
rootCmd.Flags().BoolP("round-to-closest-minute", "", false, "round time to closest minute")
rootCmd.Flags().BoolP("force-billed-duration", "", false, "treat every second spent as billed")
rootCmd.Flags().BoolP("dry-run", "", false, "fetch entries, but do not sync them")
rootCmd.Flags().BoolP("version", "", false, "show command version")
}
func initClockifyFlags() {
rootCmd.Flags().StringP("clockify-url", "", "https://api.clockify.me", "set the base URL")
rootCmd.Flags().StringP("clockify-api-key", "", "", "set the API key")
rootCmd.Flags().StringP("clockify-workspace", "", "", "set the workspace ID")
}
func initTempoFlags() {
rootCmd.Flags().StringP("tempo-url", "", "", "set the base URL")
rootCmd.Flags().StringP("tempo-username", "", "", "set the login user ID")
rootCmd.Flags().StringP("tempo-password", "", "", "set the login password")
}
func initTimewarriorFlags() {
rootCmd.Flags().StringP("timewarrior-command", "", "timew", "set the executable name")
rootCmd.Flags().StringSliceP("timewarrior-arguments", "", []string{}, "set additional arguments")
rootCmd.Flags().StringP("timewarrior-unbillable-tag", "", "unbillable", "set the unbillable tag")
rootCmd.Flags().StringP("timewarrior-client-tag-regex", "", "", "regex of client tag pattern")
rootCmd.Flags().StringP("timewarrior-project-tag-regex", "", "", "regex of project tag pattern")
}
func initTogglFlags() {
rootCmd.Flags().StringP("toggl-url", "", "https://api.track.toggl.com", "set the base URL")
rootCmd.Flags().StringP("toggl-api-key", "", "", "set the API key")
rootCmd.Flags().IntP("toggl-workspace", "", 0, "set the workspace ID")
}
func validateFlags() {
source := viper.GetString("source")
target := viper.GetString("target")
if source == target {
cobra.CheckErr("sync source cannot match the target")
}
if !utils.IsSliceContains(source, sources) {
cobra.CheckErr(fmt.Sprintf("\"%s\" is not part of the supported sources %v\n", source, sources))
}
if !utils.IsSliceContains(target, targets) {
cobra.CheckErr(fmt.Sprintf("\"%s\" is not part of the supported targets %v\n", target, targets))
}
if viper.GetBool("tags-as-tasks") {
tasksAsTagsRegex := viper.GetString("tags-as-tasks-regex")
if tasksAsTagsRegex == "" {
cobra.CheckErr("tags-as-tasks-regex cannot be empty if tags-as-tasks is set")
}
_, err := regexp.Compile(tasksAsTagsRegex)
cobra.CheckErr(err)
}
for _, sortBy := range viper.GetStringSlice("table-sort-by") {
column := sortBy
if strings.HasPrefix(column, "-") {
column = sortBy[1:]
}
if !utils.IsSliceContains(column, utils.Columns) {
cobra.CheckErr(fmt.Sprintf("\"%s\" is not part of the sortable columns %v\n", column, utils.Columns))
}
}
for _, column := range viper.GetStringSlice("table-hide-column") {
if !utils.IsSliceContains(column, utils.HideableColumns) {
cobra.CheckErr(fmt.Sprintf("\"%s\" is not part of the hideable columns %v\n", column, utils.HideableColumns))
}
}
switch source {
case "timewarrior":
if viper.GetString("timewarrior-command") == "" {
cobra.CheckErr("timewarrior command must be set")
}
if viper.GetString("timewarrior-unbillable-tag") == "" {
cobra.CheckErr("timewarrior unbillable tag must be set")
}
if viper.GetString("timewarrior-client-tag-regex") == "" {
cobra.CheckErr("timewarrior client tag regex must be set")
}
if viper.GetString("timewarrior-project-tag-regex") == "" {
cobra.CheckErr("timewarrior project tag regex must be set")
}
}
}
func getClientOpts(urlFlag string, usernameFlag string, passwordFlag string, tokenFlag string, tokenHeader string) (*client.BaseClientOpts, error) {
opts := &client.BaseClientOpts{
HTTPClientOpts: client.HTTPClientOpts{
HTTPClient: http.DefaultClient,
TokenHeader: tokenHeader,
},
TagsAsTasks: viper.GetBool("tags-as-tasks"),
TagsAsTasksRegex: viper.GetString("tags-as-tasks-regex"),
}
baseURL, err := url.Parse(viper.GetString(urlFlag))
if err != nil {
return opts, err
}
if usernameFlag != "" {
opts.Username = viper.GetString(usernameFlag)
}
if passwordFlag != "" {
opts.Password = viper.GetString(passwordFlag)
}
if tokenFlag != "" {
opts.Token = viper.GetString(tokenFlag)
}
opts.BaseURL = baseURL.String()
return opts, nil
}
func getFetcher() (client.Fetcher, error) {
switch viper.GetString("source") {
case "clockify":
opts, err := getClientOpts(
"clockify-url",
"",
"",
"clockify-api-key",
"X-Api-Key",
)
if err != nil {
return nil, err
}
return clockify.NewClient(&clockify.ClientOpts{
BaseClientOpts: *opts,
Workspace: viper.GetString("clockify-workspace"),
}), nil
case "tempo":
opts, err := getClientOpts(
"tempo-url",
"tempo-username",
"tempo-password",
"",
"",
)
if err != nil {
return nil, err
}
return tempo.NewClient(&tempo.ClientOpts{
BaseClientOpts: *opts,
}), nil
case "timewarrior":
opts := &client.BaseClientOpts{
TagsAsTasks: viper.GetBool("tags-as-tasks"),
TagsAsTasksRegex: viper.GetString("tags-as-tasks-regex"),
}
return timewarrior.NewClient(&timewarrior.ClientOpts{
BaseClientOpts: *opts,
Command: viper.GetString("timewarrior-command"),
CommandArguments: viper.GetStringSlice("timewarrior-arguments"),
CommandCtxExecutor: exec.CommandContext,
UnbillableTag: viper.GetString("timewarrior-unbillable-tag"),
ClientTagRegex: viper.GetString("timewarrior-client-tag-regex"),
ProjectTagRegex: viper.GetString("timewarrior-project-tag-regex"),
})
case "toggl":
opts, err := getClientOpts(
"toggl-url",
"toggl-api-key",
"",
"",
"",
)
// Toggl requires basic auth with the token set as the username and
// "api_token" set for password as a fix value to access their APIs
opts.Password = "api_token"
if err != nil {
return nil, err
}
return toggl.NewClient(&toggl.ClientOpts{
BaseClientOpts: *opts,
Workspace: viper.GetInt("toggl-workspace"),
}), nil
default:
return nil, ErrNoSourceImplementation
}
}
func getUploader() (client.Uploader, error) {
switch viper.GetString("target") {
case "tempo":
opts, err := getClientOpts(
"tempo-url",
"tempo-username",
"tempo-password",
"",
"",
)
if err != nil {
return nil, err
}
return tempo.NewClient(&tempo.ClientOpts{
BaseClientOpts: *opts,
}), nil
default:
return nil, ErrNoTargetImplementation
}
}
func runRootCmd(_ *cobra.Command, _ []string) {
var err error
if viper.GetBool("version") {
fmt.Printf("%s version %s, commit %s (%s)\n", program, version, commit[:8], date)
os.Exit(0)
}
validateFlags()
dateFormat := viper.GetString("date-format")
start, err := utils.GetTime(viper.GetString("start"), dateFormat)
cobra.CheckErr(err)
rawEnd := viper.GetString("end")
end, err := utils.GetTime(rawEnd, dateFormat)
cobra.CheckErr(err)
// No end date was set, hence we are setting the end date to next day midnight
if rawEnd == "" {
end = end.Add(time.Hour * 24)
}
fetcher, err := getFetcher()
cobra.CheckErr(err)
uploader, err := getUploader()
cobra.CheckErr(err)
entries, err := fetcher.FetchEntries(context.Background(), &client.FetchOpts{
End: end,
Start: start,
User: viper.GetString("source-user"),
})
cobra.CheckErr(err)
wl := worklog.NewWorklog(entries)
completeEntries := wl.CompleteEntries()
incompleteEntries := wl.IncompleteEntries()
columnTruncates := map[string]int{}
err = viper.UnmarshalKey("table-column-truncates", &columnTruncates)
cobra.CheckErr(err)
tablePrinter := utils.NewTablePrinter(&utils.TablePrinterOpts{
BasePrinterOpts: utils.BasePrinterOpts{
Output: os.Stdout,
AutoIndex: true,
Title: fmt.Sprintf("Worklog entries (%s - %s)", start.Local().String(), end.Local().String()),
SortBy: viper.GetStringSlice("table-sort-by"),
HiddenColumns: viper.GetStringSlice("table-hide-column"),
},
Style: table.StyleLight,
ColumnConfig: utils.ParseColumnConfigs(
"table-column-config.%s",
viper.GetStringSlice("table-hide-column"),
),
ColumnTruncates: columnTruncates,
})
err = tablePrinter.Print(completeEntries, incompleteEntries)
cobra.CheckErr(err)
if strings.ToLower(utils.Prompt("Continue? [y/n]: ")) != "y" {
fmt.Println("User interruption. Aborting.")
os.Exit(0)
}
// In worst case, the maximum number of errors will match the number of entries
uploadErrChan := make(chan error, len(completeEntries))
fmt.Printf("\nUploading worklog entries:\n\n")
if !viper.GetBool("dry-run") {
progressUpdateFrequency := progress.DefaultUpdateFrequency
progressWriter := utils.NewProgressWriter(progressUpdateFrequency)
// Intentionally called as a goroutine
go progressWriter.Render()
uploader.UploadEntries(context.Background(), completeEntries, uploadErrChan, &client.UploadOpts{
RoundToClosestMinute: viper.GetBool("round-to-closest-minute"),
TreatDurationAsBilled: viper.GetBool("force-billed-duration"),
CreateMissingResources: false,
User: viper.GetString("target-user"),
ProgressWriter: progressWriter,
})
// Wait for at least one tracker to appear and while the rendering is in progress,
// wait for the remaining updates to render.
time.Sleep(time.Second)
for progressWriter.IsRenderInProgress() {
time.Sleep(progressUpdateFrequency)
}
}
var uploadErrors []error
for i := 0; i < len(completeEntries); i++ {
if err := <-uploadErrChan; err != nil {
uploadErrors = append(uploadErrors, err)
}
}
if errCount := len(uploadErrors); errCount != 0 {
fmt.Printf("\nFailed to upload %d worklog entries!\n\n", errCount)
for _, err := range uploadErrors {
fmt.Println(err)
}
os.Exit(1)
}
fmt.Printf("\nSuccessfully uploaded %d worklog entries!\n", len(completeEntries))
}
func Execute(buildVersion string, buildCommit string, buildDate string) {
version = buildVersion
commit = buildCommit
date = buildDate
cobra.CheckErr(rootCmd.Execute())
}