/
timeentries.go
351 lines (294 loc) · 8.49 KB
/
timeentries.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
package cmd
import (
"fmt"
"strconv"
"time"
"github.com/jinzhu/now"
"github.com/mightymatth/arcli/config"
"github.com/mightymatth/arcli/client"
"github.com/jedib0t/go-pretty/table"
"github.com/mightymatth/arcli/utils"
"github.com/spf13/cobra"
)
var (
limit int
spentOn string
hours float32
activity string
comments string
)
var timeNow = now.EndOfDay()
func newTimeEntriesCmd() *cobra.Command {
c := &cobra.Command{
Use: "log",
Aliases: []string{"l", "entries"},
Short: "Time entries on projects and issues",
}
c.AddCommand(newTimeEntriesListCmd())
c.AddCommand(newTimeEntriesIssueCmd())
c.AddCommand(newTimeEntriesProjectCmd())
c.AddCommand(newTimeEntriesUpdateCmd())
c.AddCommand(newTimeEntriesDeleteCmd())
return c
}
func newTimeEntriesListCmd() *cobra.Command {
c := &cobra.Command{
Use: "list",
Aliases: []string{"ls", "all"},
Short: "List user time entries",
Run: timeEntriesListFunc,
}
c.Flags().IntVarP(&limit, "limit", "l", 10,
"Limit number of results")
return c
}
func timeEntriesListFunc(cmd *cobra.Command, _ []string) {
limit := cmd.Flags().Lookup("limit").Value.String()
queryParams := fmt.Sprintf("limit=%s&user_id=me", limit)
logs, err := RClient.GetTimeEntries(queryParams)
if err != nil {
fmt.Println("Cannot get time entries:", err)
return
}
t := utils.NewTable()
t.AppendHeader(table.Row{"ID", "Project", "Issue ID",
"Activity", "Hours", "Spent on", "Comment"})
for _, log := range logs {
t.AppendRow(table.Row{log.ID, log.Project.Name, log.Issue.String(),
log.Activity.Name, log.Hours, relativeDateString(log.SpentOn),
log.Comments})
}
t.Render()
}
func newTimeEntriesIssueCmd() *cobra.Command {
c := &cobra.Command{
Use: "issue [id]",
Args: validIssueArgs(),
Aliases: []string{"i"},
Short: "Add time entry to issue.",
Run: timeEntriesAddFunc(false),
}
c.Flags().StringVarP(&spentOn, "date", "d", "today",
"The date the time was spent ('today', 'yesterday', '2020-01-15')")
c.Flags().Float32VarP(&hours, "hours", "t", 0,
"The number of spent hours")
c.Flags().StringVarP(&activity, "activity", "a", "",
"The name of activity for spent time (this overrides default config value)")
c.Flags().StringVarP(&comments, "message", "m", "",
"Short comment")
_ = c.MarkFlagRequired("hours")
return c
}
func newTimeEntriesProjectCmd() *cobra.Command {
c := &cobra.Command{
Use: "project [id]",
Args: validProjectArgs(),
Aliases: []string{"p"},
Short: "Add time entry to project",
Run: timeEntriesAddFunc(true),
}
c.Flags().StringVarP(&spentOn, "date", "d", "today",
"The date the time was spent ('today', 'yesterday', '2020-01-15')")
c.Flags().Float32VarP(&hours, "hours", "t", 0,
"The number of spent hours")
c.Flags().StringVarP(&activity, "activity", "a", "",
"The name of activity for spent time (this overrides default config value)")
c.Flags().StringVarP(&comments, "message", "m", "",
"Short comment")
_ = c.MarkFlagRequired("hours")
return c
}
func timeEntriesAddFunc(isProject bool) func(cmd *cobra.Command, args []string) {
return func(cmd *cobra.Command, args []string) {
id, _ := strconv.ParseInt(args[0], 10, 64)
activities, err := RClient.GetActivities()
if err != nil {
fmt.Println("Cannot get time entry activities")
return
}
if activity == "" {
activity = config.Defaults()[string(config.Activity)]
if activity == "" {
fmt.Println("Provide activity either by flag or setting default.")
return
}
}
activityID, exists := activities.Valid(activity)
if !exists {
fmt.Printf("Invalid activity (allowed ones: [%v])",
utils.PrintWithDelimiter(activities.Names()))
return
}
spentOnTime, err := spentOnParse(spentOn)
if err != nil {
fmt.Printf("Cannot parse date value: %v", err)
return
}
var entryPost *client.TimeEntryPost
if isProject {
entryPost = &client.TimeEntryPost{
ProjectID: int(id),
SpentOn: *client.NewDateTime(*spentOnTime),
Hours: hours,
ActivityID: int(activityID),
Comments: comments,
}
} else {
entryPost = &client.TimeEntryPost{
IssueID: int(id),
SpentOn: *client.NewDateTime(*spentOnTime),
Hours: hours,
ActivityID: int(activityID),
Comments: comments,
}
}
entry, err := RClient.AddTimeEntry(*entryPost)
if err != nil {
fmt.Printf("Cannot create time entry: %v\n", err)
return
}
fmt.Println("Time entry created!")
entry.PrintTable()
}
}
func newTimeEntriesUpdateCmd() *cobra.Command {
c := &cobra.Command{
Use: "update [id]",
Args: validTimeEntryArgs(),
Aliases: []string{"u", "edit", "modify"},
Short: "Update time entry",
Run: timeEntriesUpdateFunc(),
}
c.Flags().StringVarP(&spentOn, "date", "d", "today",
"The date the time was spent ('today', 'yesterday', '2020-01-15')")
c.Flags().Float32VarP(&hours, "hours", "t", 0,
"The number of spent hours")
c.Flags().StringVarP(&activity, "activity", "a", "",
"The name of activity for spent time (this overrides default config value)")
c.Flags().StringVarP(&comments, "message", "m", "",
"Short comment")
return c
}
func timeEntriesUpdateFunc() func(cmd *cobra.Command, args []string) {
return func(cmd *cobra.Command, args []string) {
entryID, _ := strconv.ParseInt(args[0], 10, 64)
var entryUpdate client.TimeEntryPost
if activity != "" {
activities, err := RClient.GetActivities()
if err != nil {
fmt.Println("Cannot get time entry activities")
return
}
activityID, exists := activities.Valid(activity)
if !exists {
fmt.Printf("Invalid activity (allowed ones: [%v])",
utils.PrintWithDelimiter(activities.Names()))
return
}
entryUpdate.ActivityID = int(activityID)
}
if spentOn != "" {
spentOnTime, err := spentOnParse(spentOn)
if err != nil {
fmt.Printf("Cannot parse date value: %v", err)
return
}
entryUpdate.SpentOn = *client.NewDateTime(*spentOnTime)
}
if cmd.Flags().Changed("message") {
if comments == "" {
comments = " "
}
entryUpdate.Comments = comments
}
if hours != 0 {
entryUpdate.Hours = hours
}
err := RClient.UpdateTimeEntry(int(entryID), entryUpdate)
if err != nil {
fmt.Printf("Cannot update time entry: %v\n", err)
return
}
fmt.Println("Time entry updated!")
updatedEntry, err := RClient.GetTimeEntry(int(entryID))
if err != nil {
fmt.Printf("Time entry with ID %d cannot be fetched: %v", entryID, err)
}
updatedEntry.PrintTable()
}
}
func newTimeEntriesDeleteCmd() *cobra.Command {
c := &cobra.Command{
Use: "delete [id...]",
Args: validTimeEntryArgs(),
Aliases: []string{"remove", "rm", "del"},
Short: "Delete time entry",
Run: timeEntriesDeleteFunc,
}
return c
}
func relativeDateString(dateTime client.DateTime) string {
durationDays := int(timeNow.Sub(dateTime.Time).Hours() / 24)
date := dateTime.Time.Format(client.DayDateFormat)
switch {
case durationDays < 0:
return date
case durationDays == 0:
return fmt.Sprintf("today (%v)", date)
case durationDays == 1:
return fmt.Sprintf("yesterday (%v)", date)
default:
return fmt.Sprintf("%v days ago (%v)", durationDays, date)
}
}
func validTimeEntryArgs() cobra.PositionalArgs {
return func(cmd *cobra.Command, args []string) error {
err := cobra.MinimumNArgs(1)(cmd, args)
if err != nil {
return err
}
for _, arg := range args {
_, err = strconv.ParseInt(arg, 10, 64)
if err != nil {
return fmt.Errorf("time entry id must be integer, but given %v", arg)
}
}
return nil
}
}
func timeEntriesDeleteFunc(_ *cobra.Command, args []string) {
for _, arg := range args {
entryID, _ := strconv.ParseInt(arg, 10, 64)
err := RClient.DeleteTimeEntry(int(entryID))
if err != nil {
fmt.Println("Cannot delete time entry:", err)
return
}
fmt.Printf("Time entry with id %v successfully deleted.\n", arg)
}
}
func spentOnModify(spentOn string) (string, error) {
var modified string
switch spentOn {
case "today":
modified = timeNow.Format(client.DateTimeFormat)
case "yesterday":
modified = timeNow.AddDate(0, 0, -1).Format(client.DateTimeFormat)
default:
_, err := time.Parse(client.DateTimeFormat, spentOn)
if err != nil {
return "", fmt.Errorf("invalid date format (use '%v' instead)",
client.DateTimeFormat)
}
modified = spentOn
}
return modified, nil
}
func spentOnParse(spentOn string) (*time.Time, error) {
modified, err := spentOnModify(spentOn)
if err != nil {
return nil, err
}
spentOnTime, _ := time.Parse(client.DateTimeFormat, modified)
return &spentOnTime, nil
}