-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreport.swift
executable file
·743 lines (611 loc) · 27 KB
/
report.swift
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
#!/usr/bin/swift
import Foundation
let appSemaphore = DispatchSemaphore(value: 0)
func finishApp() { appSemaphore.signal() }
struct Config: Decodable {
let apiKey: String
let workspaceID: String?
let projectID: String?
}
final class App {
static var config: Config = {
guard let configJson = try? Data(contentsOf: URL(fileURLWithPath: "config.json")),
let config = try? decoder.decode(Config.self, from: configJson) else {
exit(code: .apiKeyMissing)
}
return config
}()
}
let session = URLSession.shared
let baseURL = URL(string: "https://api.clockify.me/api/v1")!
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
enum ExitCode {
case unconfirmedReport
case apiKeyMissing
case workspaceRequestFailure(Error)
case workspaceNotFound(name: String)
case workspaceNotSpecified
case projectRequestFailure(Error)
case projectNotFound(name: String)
case projectNotSpecified
case addEntryRequestFailed(Error)
var code: Int32 {
switch self {
case .unconfirmedReport: return 0
case .apiKeyMissing: return 1
case .workspaceRequestFailure: return 2
case .workspaceNotFound: return 3
case .workspaceNotSpecified: return 4
case .projectRequestFailure: return 5
case .projectNotFound: return 6
case .projectNotSpecified: return 7
case .addEntryRequestFailed: return 8
}
}
var message: String? {
switch self {
case .unconfirmedReport:
return "Did not confirm, discarding."
case .apiKeyMissing:
return "No apiKey found in config.json file. Make sure your Clockify API Key is specified in a config.json file (you need to create one first if it doesnt exist yet). See attached example-config.json file to learn about the JSON structure and available config fields."
case .workspaceRequestFailure(let error):
return "An error occurred: \(error). Aborting."
case .workspaceNotFound(let name):
return "Workspace named '\(name)' not found. Use --workspaces to see available workspaces. Aborting."
case .workspaceNotSpecified:
return "Workspace not specified. Aborting."
case .projectRequestFailure(let error):
return "An error occurred: \(error). Aborting."
case .projectNotFound(let name):
return "Project named '\(name)' not found. Use --projects to see available projects (if workspace the project is in is not specified explicitly, it will use the default one). Aborting."
case .projectNotSpecified:
return "Project not specified. Aborting."
case .addEntryRequestFailed(let error):
return "An error occurred: \(error). Aborting."
}
}
}
func exit(code: ExitCode) -> Never {
code.message.flatMap { print($0) }
Foundation.exit(code.code)
}
let baseHeaders: [String: String] = ["X-Api-Key": App.config.apiKey,
"Content-Type": "application/json"]
let arguments: [Argument] = {
guard CommandLine.arguments.count > 1 else { return [] }
print(CommandLine.arguments[1...])
return CommandLine.arguments[1...]
.compactMap { Argument($0) }
}()
enum Endpoint {
case getWorkspaces
case getProjects(workspaceID: String)
case addEntry(workspaceID: String)
var path: String {
switch self {
case .getWorkspaces:
return "/workspaces"
case .getProjects(let workspaceID):
return "/workspaces/\(workspaceID)/projects"
case .addEntry(let workspaceID):
return "/workspaces/\(workspaceID)/time-entries"
}
}
}
enum HTTPMethod: String {
case post = "POST"
case get = "GET"
}
protocol CommandAction {
func perform()
}
struct Argument {
enum Key: CaseIterable {
case workspaceName
case workspaceID
case projectName
case projectID
case skipWeekends
var matchingNames: Set<String> {
switch self {
case .workspaceName: return ["-wname", "--workspace", "--workspace-name"]
case .workspaceID: return ["-wid", "--workspaceid", "--workspace-id"]
case .projectName: return ["-pname", "--project", "--project-name"]
case .projectID: return ["-pid", "--projectid", "--project-id"]
case .skipWeekends: return ["-sw", "--skip-weekends"]
}
}
}
let key: Key
let value: String
}
extension Argument {
init?(_ string: String) {
var components = string.components(separatedBy: "=")
let keyString = components.removeFirst()
let value = components.joined(separator: "=")
guard let key = Key.allCases.first(where: { $0.matchingNames.contains(keyString) }) else {
return nil
}
self = Argument(key: key, value: value)
}
}
extension CommandAction {
func getWorkspaceID(completion: @escaping (String) -> Void) {
if let id = arguments.first(where: { $0.key == .workspaceID })?.value {
print("Using provided workspace ID: \(id)")
completion(id)
} else if let name = arguments.first(where: { $0.key == .workspaceName })?.value {
Networking.get(.getWorkspaces, responseType: [Responses.GetWorkspaces].self, description: "Querying available workspaces...") { result in
switch result {
case .success(let workspaces):
if let id = workspaces.first(where: { $0.name.caseInsensitiveCompare(name) == .orderedSame })?.id {
print("Found workspace \(name) with ID \(id)")
completion(id)
} else {
exit(code: .workspaceNotFound(name: name))
}
case .failure(let error):
exit(code: .workspaceRequestFailure(error))
}
}
} else if let defaultWorkspaceID = App.config.workspaceID {
print("Using workspace ID from config file: \(defaultWorkspaceID)")
completion(defaultWorkspaceID)
} else {
exit(code: .workspaceNotSpecified)
}
}
func getProjectID(inWorkspaceWithID id: String, completion: @escaping (String) -> Void) {
if let id = arguments.first(where: { $0.key == .projectID })?.value {
print("Using provided project ID: \(id)")
completion(id)
} else if let name = arguments.first(where: { $0.key == .projectName })?.value {
Networking.get(.getProjects(workspaceID: id), responseType: [Responses.GetProjects].self, description: "Querying available projects...") { result in
switch result {
case .success(let projects):
if let id = projects.first(where: { $0.name.caseInsensitiveCompare(name) == .orderedSame })?.id {
print("Found project \(name) with ID \(id)")
completion(id)
} else {
exit(code: .projectNotFound(name: name))
}
case .failure(let error):
exit(code: .projectRequestFailure(error))
}
}
} else if let defaultProjectID = App.config.projectID {
print("Using project ID from config file: \(defaultProjectID)")
completion(defaultProjectID)
} else {
exit(code: .projectNotSpecified)
}
}
}
final class CommandHandler {
enum Command: CaseIterable {
case workspaces
case projects
case report
case help
var matchingArgs: Set<String> {
switch self {
case .workspaces: return ["-w", "--workspaces"]
case .projects: return ["-p", "--projects"]
case .report: return ["-r", "--report"]
case .help: return ["-h", "help", "-help", "--help"]
}
}
func getAction(arguments: [String]) -> CommandAction {
switch self {
case .workspaces: return GetWorkspacesAction()
case .projects: return GetProjectsAction()
case .report: return ReportAction(arguments: arguments)
case .help: return HelpAction()
}
}
}
static func getAction() -> CommandAction {
let args = CommandLine.arguments
guard args.count > 1 else {
return HelpAction()
}
let params = Array(args[1...])
let paramIndex: Int? = params
.firstIndex { param in
Command.allCases.contains { command in
command.matchingArgs.contains(param)
}
}
guard let paramIndex = paramIndex else {
return HelpAction()
}
let param = params[paramIndex]
let command = Command.allCases.first { command in
command.matchingArgs.contains(param)
}
let action = command?.getAction(arguments: Array(params[paramIndex...])) ?? HelpAction()
return action
}
}
final class GetWorkspacesAction: CommandAction {
func perform() {
Networking.get(.getWorkspaces, responseType: [Responses.GetWorkspaces].self, description: "Querying available workspaces...") { result in
switch result {
case .success(let workspaces):
print("Available workspaces: \(workspaces)")
case .failure(let error):
print("An error occurred: \(error)")
}
finishApp()
}
}
}
final class GetProjectsAction: CommandAction {
func perform() {
getWorkspaceID { workspaceID in
self.perform(inWorkspaceID: workspaceID)
}
}
private func perform(inWorkspaceID workspaceID: String) {
Networking.get(.getProjects(workspaceID: workspaceID), responseType: [Responses.GetProjects].self, description: "Querying available projects...") { result in
switch result {
case .success(let projects):
print("Available projects: \(projects)")
case .failure(let error):
print("An error occurred: \(error)")
}
finishApp()
}
}
}
final class HelpAction: CommandAction {
func perform() {
func getArgNames(for key: Argument.Key) -> String {
key.matchingNames.joined(separator: ", ")
}
print("""
Usage:
./report.swift <command> [parameters]
IMPORTANT: Provide your Clockify API key in a "config.json" file!
See example-config.json for an example.
Available commands:
* Help: -h, help, -help, --help
* Query available workspaces: -w, --workspaces
* Query available projects: -p, --projects
* Report time: -r, --report
Description:
Report time using `-r` or `--report` command.
Example:
./report.swift -r 9-18 "Remote work"
Report "Remote work" today from 9 AM to 6 PM. Workspace and project must be already specified in config.json file.
./report.swift -r 9:30-18:40 03.06-05.06 -sw Meetings
Report "Meetings" from 9:30 AM to 6:40 PM on 03.06 until 05.06, skipping saturdays&sundays, this year. Workspace and project must be already specified in config.json file.
./report.swift --workspace=myWorkspace --project=myProject -r 10-18:20 "Busy as hell"
Report "Busy as hell" today from 10:00 AM to 6:20 PM in "myWorkspace" workspace & in project named "myProject"
Parameters:
<time> (required)
Must be provided immediately after the command. Minutes are optional. The time must be in 24h format
[date or date range] (optional) (default: today)
Specify date of the report. Can also take a form of date range, separated with "-", e.g. 24.05-29.05
<message> (required)
Must be provided as the last parameter. Does not need quotes if it does not contain spaces.
Configuration parameters:
[\(getArgNames(for: .workspaceID))]
Specify workspace ID in key=value format.
[\(getArgNames(for: .workspaceName))]
Specify workspace name in key=value format.
[\(getArgNames(for: .projectID))]
Specify project ID in key=value format.
[\(getArgNames(for: .projectName))]
Specify project name in key=value format.
[\(getArgNames(for: .skipWeekends))]
Skip saturdays & sundays when reporting.
""")
finishApp()
}
}
struct TimeRange: CustomStringConvertible {
let dateRanges: [(from: Date, to: Date)]
var description: String {
let ranges = dateRanges
.map { (dateFrom, dateTo) -> String in
"\(dateFrom)-\(dateTo)"
}
.joined(separator: ", ")
return "<Ranges: \(ranges)>"
}
private static let currentDateComps = Calendar.current.dateComponents([.year, .month, .day], from: Date())
init?(from arguments: [String]) {
guard arguments.count >= 3 else { return nil }
// [0] is command name
let timeString = arguments[1]
let dateString = arguments[2]
let rangeStrings = timeString.components(separatedBy: "-")
guard rangeStrings.count == 2 else { return nil }
let timeFromString = rangeStrings[0]
let timeToString = rangeStrings[1]
let dateStrings = dateString.components(separatedBy: "-")
let dateFromString: String
let dateToString: String
if dateStrings.count == 2 {
dateFromString = dateStrings[0]
dateToString = dateStrings[1]
} else {
dateFromString = dateString
dateToString = dateString
}
let dateRange = Self.parseDateRange(from: dateFromString, to: dateToString)
guard let timeFrom = Self.parseTime(timeFromString),
let timeTo = Self.parseTime(timeToString) else {
return nil
}
guard let startDate = Calendar.current.date(from: dateRange.from),
let endDate = Calendar.current.date(from: dateRange.to) else { return nil }
var dateRanges = [(from: Date, to: Date)]()
var currentDate = startDate
while currentDate <= endDate {
let comps = Calendar.current.dateComponents([.year, .month, .day], from: currentDate)
let fromComps = DateComponents(year: comps.year, month: comps.month, day: comps.day, hour: timeFrom.hour, minute: timeFrom.minute, second: 0, nanosecond: 0)
let toComps = DateComponents(year: comps.year, month: comps.month, day: comps.day, hour: timeTo.hour, minute: timeTo.minute, second: 0, nanosecond: 0)
guard let dateFrom = Calendar.current.date(from: fromComps),
let dateTo = Calendar.current.date(from: toComps) else { return nil }
dateRanges.append((from: dateFrom, to: dateTo))
guard let nextDate = Calendar.current.date(byAdding: .day, value: 1, to: currentDate) else {
break
}
currentDate = nextDate
}
self.dateRanges = dateRanges
}
private static func parseTime(_ timeString: String) -> (hour: Int, minute: Int)? {
let df = DateFormatter()
let format = DateFormatter.dateFormat(fromTemplate: "HHmm", options: 0, locale: .current)
df.dateFormat = format
if let date = df.date(from: timeString) {
let comps = Calendar.current.dateComponents([.hour, .minute], from: date)
return (hour: comps.hour!, minute: comps.minute!)
} else {
let format = DateFormatter.dateFormat(fromTemplate: "HH", options: 0, locale: .current)
df.dateFormat = format
if let date = df.date(from: timeString) {
let comps = Calendar.current.dateComponents([.hour], from: date)
return (hour: comps.hour!, minute: 0)
} else {
return nil
}
}
}
private static func parseDateRange(from fromString: String, to toString: String) -> (from: DateComponents, to: DateComponents) {
let dateFromComps = Self.parseDate(fromString)
let dateToComps = Self.parseDate(toString)
let dateFromComps2 = (year: dateFromComps.year ?? dateToComps.year ?? currentDateComps.year!,
month: dateFromComps.month ?? dateToComps.month ?? currentDateComps.month!,
day: dateFromComps.day ?? currentDateComps.day!)
let dateToComps2 = (year: dateToComps.year ?? currentDateComps.year!,
month: dateToComps.month ?? currentDateComps.month!,
day: dateToComps.day ?? currentDateComps.day!)
let dateDayFromComps = DateComponents(year: dateFromComps2.year, month: dateFromComps2.month, day: dateFromComps2.day, hour: 0, minute: 0, second: 0, nanosecond: 0)
let dateDayToComps = DateComponents(year: dateToComps2.year, month: dateToComps2.month, day: dateToComps2.day, hour: 0, minute: 0, second: 0, nanosecond: 0)
return (from: dateDayFromComps, to: dateDayToComps)
}
private static func parseDate(_ dateString: String) -> (year: Int?, month: Int?, day: Int?) {
let df = DateFormatter()
let format = DateFormatter.dateFormat(fromTemplate: "ddMM", options: 0, locale: .current)
df.dateFormat = format
if let day = Int(dateString) {
return (year: nil, month: nil, day: day)
} else if let simpleDate = df.date(from: dateString) {
let comps = Calendar.current.dateComponents([.month, .day], from: simpleDate)
return (year: nil, month: comps.month!, day: comps.day!)
} else {
let format = DateFormatter.dateFormat(fromTemplate: "ddMMyyyy", options: 0, locale: .current)
df.dateFormat = format
if let fullDate = df.date(from: dateString) {
let comps = Calendar.current.dateComponents([.year, .month, .day], from: fullDate)
return (year: comps.year!, month: comps.month!, day: comps.day!)
} else {
return (year: nil, month: nil, day: nil)
}
}
}
}
final class ReportAction: CommandAction {
let arguments: [String]
init(arguments: [String]) {
self.arguments = arguments
}
func perform() {
guard let timeRange = TimeRange(from: arguments),
let message = arguments.last else {
print("Invalid time or message. Type --help for usage description.")
return
}
getWorkspaceID { workspaceID in
self.getProjectID(inWorkspaceWithID: workspaceID) { projectID in
self.perform(withWorkspaceID: workspaceID,
projectID: projectID,
timeRange: timeRange,
message: message)
}
}
}
private func perform(withWorkspaceID id: String, projectID: String, timeRange: TimeRange, message: String) {
guard
let firstDateRange = timeRange.dateRanges.first,
let lastDateRange = timeRange.dateRanges.last
else {
print("No dates specified, aborting.")
exit(1)
}
let fmt = DateFormatter()
fmt.dateStyle = .none
fmt.timeStyle = .short
let timeFromString = fmt.string(from: firstDateRange.from)
let timeToString = fmt.string(from: lastDateRange.to)
fmt.dateStyle = .medium
fmt.timeStyle = .none
let dateFromString = fmt.string(from: firstDateRange.from)
var dateString: String
if Calendar.current.isDate(firstDateRange.from, inSameDayAs: lastDateRange.to) {
dateString = dateFromString
} else {
let dateToString = fmt.string(from: lastDateRange.to)
dateString = "\(dateFromString) - \(dateToString)"
}
let skipWeekends = arguments.contains(where: { Argument.Key.skipWeekends.matchingNames.contains($0) })
if skipWeekends {
dateString += " (skip weekends)"
}
print("""
Summary:
- From: \(timeFromString)
- To: \(timeToString)
- Dates: \(dateString)
- Message: \(message)
""")
print("Type 'y' to report.")
let confirm = readLine()
guard confirm?.caseInsensitiveCompare("y") == .orderedSame else {
exit(code: .unconfirmedReport)
}
let requests = timeRange.dateRanges.compactMap { dateFrom, dateTo -> Requests.AddTimeEntry? in
let weekday = Calendar.current.dateComponents([.weekday], from: dateFrom).weekday
let isWeekend = [1, 7].contains(weekday)
if isWeekend && skipWeekends {
print("Skipping \(dateFrom) - weekend.")
return nil
} else {
return Requests.AddTimeEntry(start: dateFrom,
end: dateTo,
description: message,
projectId: projectID)
}
}
var sentCount = 0
var sendError: Error?
print("Sending reports...")
requests.forEach { request in
Networking.post(.addEntry(workspaceID: id), data: request) { error in
sentCount += 1
if error != nil {
sendError = error
}
}
}
while sentCount != requests.count {}
if let error = sendError {
exit(code: .addEntryRequestFailed(error))
} else {
print("Reports sent successfully.")
finishApp()
}
}
}
enum Requests {
struct AddTimeEntry: Codable {
let start: Date
let end: Date
let description: String
let projectId: String
}
}
enum Responses {
struct GetWorkspaces: Decodable, CustomStringConvertible {
let id: String
let name: String
var description: String {
return "[Workspace \(id)] \(name)"
}
}
struct GetProjects: Decodable, CustomStringConvertible {
let id: String
let name: String
var description: String {
return "[Project \(id)] \(name)"
}
}
}
final class Networking {
static func post<T: Encodable>(_ endpoint: Endpoint, headers: [String: String] = [:], data: T, description: String? = nil, completion: @escaping (Error?) -> Void) {
let body: Data
do {
body = try encoder.encode(data)
} catch {
completion(error)
return
}
// if let string = String(data: body, encoding: .utf8) {
// print("Sending JSON: \(string)")
// }
sendRequest(endpoint, method: .post, headers: headers, body: body, description: description) { result in
switch result {
case .success:
completion(nil)
case .failure(let error):
completion(error)
}
}
}
static func get<T: Decodable>(_ endpoint: Endpoint, headers: [String: String] = [:], responseType: T.Type, description: String? = nil, completion: @escaping (Result<T, Error>) -> Void) {
sendRequest(endpoint, method: .get, headers: headers, description: description) { result in
switch result {
case .success(let data):
if let data = data {
do {
let result = try decoder.decode(T.self, from: data)
completion(.success(result))
} catch {
completion(.failure(error))
}
} else {
let err = NSError(domain: "report", code: 1, userInfo: [NSLocalizedDescriptionKey: "Data missing in response"])
completion(.failure(err as Error))
}
case .failure(let error):
completion(.failure(error))
}
}
}
static func get(_ endpoint: Endpoint, headers: [String: String] = [:], description: String? = nil, completion: ((Error?) -> Void)? = nil) {
sendRequest(endpoint, method: .get, headers: headers, description: description) { result in
switch result {
case .success:
completion?(nil)
case .failure(let error):
completion?(error)
}
}
}
private static func sendRequest(_ endpoint: Endpoint, method: HTTPMethod = .get, headers: [String: String] = [:], body: Data? = nil, description: String? = nil, completion: @escaping (Result<Data?, Error>) -> Void) {
let url = baseURL.appendingPathComponent(endpoint.path)
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
request.httpBody = body
baseHeaders.forEach { request.setValue($0.value, forHTTPHeaderField: $0.key) }
headers.forEach { request.setValue($0.value, forHTTPHeaderField: $0.key) }
let task = session.dataTask(with: request) { data, response, error in
if let error = error {
completion(.failure(error))
} else if let resp = response as? HTTPURLResponse, 200...299 ~= resp.statusCode {
completion(.success(data))
} else if let data = data, let apiErrorString = String(data: data, encoding: .utf8) {
print("API error: \(apiErrorString)")
} else {
print("Unknown API error")
}
}
task.resume()
if let description = description {
print(description)
}
}
}
DispatchQueue.global(qos: .userInitiated).async {
let action = CommandHandler.getAction()
action.perform()
}
appSemaphore.wait()