-
-
Notifications
You must be signed in to change notification settings - Fork 243
/
Copy pathcli.py
1728 lines (1486 loc) · 62 KB
/
cli.py
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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
import itertools
import json
import operator
import os
from dateutil import tz
from functools import reduce, wraps
import arrow
import click
from click_didyoumean import DYMGroup
import watson as _watson
from .autocompletion import (
get_frames,
get_project_or_task_completion,
get_projects,
get_rename_name,
get_rename_types,
get_tags,
)
from .frames import Frame
from .utils import (
apply_weekday_offset,
build_csv,
confirm_project,
confirm_tags,
create_watson,
flatten_report_for_csv,
format_timedelta,
frames_to_csv,
frames_to_json,
get_frame_from_argument,
get_start_time_for_period,
options, safe_save,
sorted_groupby,
style,
parse_tags,
json_arrow_encoder,
)
class MutuallyExclusiveOption(click.Option):
def __init__(self, *args, **kwargs):
self.mutually_exclusive = set(kwargs.pop('mutually_exclusive', []))
super(MutuallyExclusiveOption, self).__init__(*args, **kwargs)
def handle_parse_result(self, ctx, opts, args):
if self.name in opts:
if self.mutually_exclusive.intersection(opts):
self._raise_exclusive_error()
if self.multiple and len(set(opts[self.name])) > 1:
self._raise_exclusive_error()
return super(MutuallyExclusiveOption, self).handle_parse_result(
ctx, opts, args
)
def _raise_exclusive_error(self):
# Use self.opts[-1] instead of self.name to handle options with a
# different internal name.
self.mutually_exclusive.add(self.opts[-1].strip('-'))
raise click.ClickException(
style(
'error',
'The following options are mutually exclusive: '
'{options}'.format(options=', '.join(
['`--{}`'.format(_) for _ in self.mutually_exclusive]))))
def local_tz_info() -> datetime.tzinfo:
"""Get the local time zone object, respects the TZ env variable."""
timezone = os.environ.get("TZ", None)
# If timezone is None or an empty string, gettz returns the local time
tzinfo = tz.gettz(timezone)
# gettz returns None if the timezone passed to gettz is invalid
if tzinfo is None:
raise click.ClickException(
f"Invalid timezone {timezone} specified, "
"please set the TZ environment variable with"
" a valid timezone."
)
return tzinfo
class DateTimeParamType(click.ParamType):
name = 'datetime'
def convert(self, value, param, ctx) -> arrow:
if value:
date = self._parse_multiformat(value)
if date is None:
raise click.UsageError(
"Could not match value '{}' to any supported date format"
.format(value)
)
# When we parse a date, we want to parse it in the timezone
# expected by the user, so that midnight is midnight in the local
# timezone, or respect the TZ environment variable not in UTC.
# Cf issue #16.
date = date.replace(tzinfo=local_tz_info())
# Add an offset to match the week beginning specified in the
# configuration
if param.name == "week":
week_start = ctx.obj.config.get(
"options", "week_start", "monday")
date = apply_weekday_offset(
start_time=date, week_start=week_start)
return date
def _parse_multiformat(self, value) -> arrow:
date = None
for fmt in (None, 'HH:mm:ss', 'HH:mm'):
try:
if fmt is None:
date = arrow.get(value)
else:
date = arrow.get(value, fmt)
date = arrow.now().replace(
hour=date.hour,
minute=date.minute,
second=date.second
)
break
except (ValueError, TypeError):
pass
return date
DateTime = DateTimeParamType()
def catch_watson_error(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except _watson.WatsonError as e:
raise click.ClickException(style('error', str(e)))
return wrapper
@click.group(cls=DYMGroup)
@click.version_option(version=_watson.__version__, prog_name='Watson')
@click.option('--color/--no-color', 'color', default=None,
help="(Don't) color output.")
@click.pass_context
def cli(ctx, color):
"""
Watson is a tool aimed at helping you monitoring your time.
You just have to tell Watson when you start working on your
project with the `start` command, and you can stop the timer
when you're done with the `stop` command.
"""
if color is not None:
ctx.color = True if color else False
# This is the main command group, needed by click in order
# to handle the subcommands
ctx.obj = create_watson()
@cli.command()
@click.argument('command', required=False)
@click.pass_context
def help(ctx, command):
"""
Display help information
"""
if not command:
click.echo(ctx.parent.get_help())
return
cmd = cli.get_command(ctx, command)
if not cmd:
raise click.ClickException("No such command: {}".format(command))
click.echo(cmd.get_help(ctx))
def _start(watson, project, tags, restart=False, start_at=None, gap=True):
"""
Start project with given list of tags and save status.
"""
current = watson.start(project, tags, restart=restart, start_at=start_at,
gap=gap,)
click.echo("Starting project {}{} at {}".format(
style('project', project),
(" " if current['tags'] else "") + style('tags', current['tags']),
style('time', "{:HH:mm}".format(current['start']))
))
watson.save()
@cli.command()
@click.option('--at', 'at_', type=DateTime, default=None,
cls=MutuallyExclusiveOption, mutually_exclusive=['gap_'],
help=('Start frame at this time. Must be in '
'(YYYY-MM-DDT)?HH:MM(:SS)? format.'))
@click.option('-g/-G', '--gap/--no-gap', 'gap_', is_flag=True, default=True,
cls=MutuallyExclusiveOption, mutually_exclusive=['at_'],
help=("(Don't) leave gap between end time of previous project "
"and start time of the current."))
@click.argument('args', nargs=-1,
shell_complete=get_project_or_task_completion)
@click.option('-c', '--confirm-new-project', is_flag=True, default=False,
help="Confirm addition of new project.")
@click.option('-b', '--confirm-new-tag', is_flag=True, default=False,
help="Confirm creation of new tag.")
@click.pass_obj
@click.pass_context
@catch_watson_error
def start(ctx, watson, confirm_new_project, confirm_new_tag, args, at_,
gap_=True):
"""
Start monitoring time for the given project.
You can add tags indicating more specifically what you are working on with
`+tag`.
If there is already a running project and the configuration option
`options.stop_on_start` is set to a true value (`1`, `on`, `true`, or
`yes`), it is stopped before the new project is started.
If `--at` option is given, the provided starting time is used. The
specified time must be after the end of the previous frame and must not be
in the future. If there is a current frame running, it will be stopped at
the provided time.
Example:
\b
$ watson start --at 13:37
Starting project apollo11 at 13:37
If the `--no-gap` flag is given, the start time of the new project is set
to the stop time of the most recently stopped project.
Example:
\b
$ watson start apollo11 +module +brakes --no-gap
Starting project apollo11 [module, brakes] at 16:34
"""
project = ' '.join(
itertools.takewhile(lambda s: not s.startswith('+'), args)
)
if not project:
raise click.ClickException("No project given.")
# Confirm creation of new project if that option is set
if (watson.config.getboolean('options', 'confirm_new_project') or
confirm_new_project):
confirm_project(project, watson.projects)
# Parse all the tags
tags = parse_tags(args)
# Confirm creation of new tag(s) if that option is set
if (watson.config.getboolean('options', 'confirm_new_tag') or
confirm_new_tag):
confirm_tags(tags, watson.tags)
if project and watson.is_started and not gap_:
current = watson.current
errmsg = ("Project '{}' is already started and '--no-gap' is passed. "
"Please stop manually.")
raise click.ClickException(
style(
'error', errmsg.format(current['project'])
)
)
if (project and watson.is_started and
watson.config.getboolean('options', 'stop_on_start')):
ctx.invoke(stop, at_=at_)
_start(watson, project, tags, start_at=at_, gap=gap_)
@cli.command(context_settings={'ignore_unknown_options': True})
@click.option('--at', 'at_', type=DateTime, default=None,
help=('Stop frame at this time. Must be in '
'(YYYY-MM-DDT)?HH:MM(:SS)? format.'))
@click.pass_obj
@catch_watson_error
def stop(watson, at_):
"""
Stop monitoring time for the current project.
If `--at` option is given, the provided stopping time is used. The
specified time must be after the beginning of the to-be-ended frame and must
not be in the future.
Example:
\b
$ watson stop --at 13:37
Stopping project apollo11, started an hour ago and stopped 30 minutes ago. (id: e9ccd52) # noqa: E501
"""
frame = watson.stop(stop_at=at_)
output_str = "Stopping project {}{}, started {} and stopped {}. (id: {})"
click.echo(output_str.format(
style('project', frame.project),
(" " if frame.tags else "") + style('tags', frame.tags),
style('time', frame.start.humanize()),
style('time', frame.stop.humanize()),
style('short_id', frame.id),
))
watson.save()
@cli.command(context_settings={'ignore_unknown_options': True})
@click.option('--at', 'at_', type=DateTime, default=None,
cls=MutuallyExclusiveOption, mutually_exclusive=['gap_'],
help=('Start frame at this time. Must be in '
'(YYYY-MM-DDT)?HH:MM(:SS)? format.'))
@click.option('-g/-G', '--gap/--no-gap', 'gap_', is_flag=True, default=True,
cls=MutuallyExclusiveOption, mutually_exclusive=['at_'],
help=("(Don't) leave gap between end time of previous project "
"and start time of the current."))
@click.option('-s/-S', '--stop/--no-stop', 'stop_', default=None,
help="(Don't) Stop an already running project.")
@click.argument('id', default='-1', shell_complete=get_frames)
@click.pass_obj
@click.pass_context
@catch_watson_error
def restart(ctx, watson, id, stop_, at_, gap_=True):
"""
Restart monitoring time for a previously stopped project.
By default, the project from the last frame, which was recorded, is
restarted, using the same tags as recorded in that frame. You can specify
the frame to use with an integer frame index argument or a frame ID. For
example, to restart the second-to-last frame, pass `-2` as the frame index.
Normally, if a project is currently started, Watson will print an error and
do nothing. If you set the configuration option `options.stop_on_restart`
to a true value (`1`, `on`, `true`, or `yes`), the current project, if any,
will be stopped before the new frame is started. You can pass the option
`-s` or `--stop` resp. `-S` or `--no-stop` to override the default or
configured behaviour.
If no previous frame exists or an invalid frame index or ID was given,
an error is printed and no further action taken.
Example:
\b
$ watson start apollo11 +module +brakes
Starting project apollo11 [module, brakes] at 16:34
$ watson stop
Stopping project apollo11, started a minute ago. (id: e7ccd52)
$ watson restart
Starting project apollo11 [module, brakes] at 16:36
If the `--no-gap` flag is given, the start time of the new project is set
to the stop time of the most recently stopped project.
"""
if not watson.frames and not watson.is_started:
raise click.ClickException(
style('error', "No frames recorded yet. It's time to create your "
"first one!"))
if watson.is_started and not gap_:
current = watson.current
errmsg = ("Project '{}' is already started and '--no-gap' is passed. "
"Please stop manually.")
raise click.ClickException(
style(
'error', errmsg.format(current['project'])
)
)
if watson.is_started:
if stop_ or (stop_ is None and
watson.config.getboolean('options', 'stop_on_restart')):
ctx.invoke(stop)
else:
# Raise error here, instead of in watson.start(), otherwise
# will give misleading error if running frame is the first one
raise click.ClickException("{} {} {}".format(
style('error', "Project already started:"),
style('project', watson.current['project']),
style('tags', watson.current['tags'])))
frame = get_frame_from_argument(watson, id)
_start(watson, frame.project, frame.tags, restart=True, start_at=at_,
gap=gap_)
@cli.command()
@click.pass_obj
@catch_watson_error
def cancel(watson):
"""
Cancel the last call to the start command. The time will
not be recorded.
"""
old = watson.cancel()
click.echo("Canceling the timer for project {}{}".format(
style('project', old['project']),
(" " if old['tags'] else "") + style('tags', old['tags'])
))
watson.save()
@cli.command()
@click.option('-p', '--project', is_flag=True,
help="only output project")
@click.option('-t', '--tags', is_flag=True,
help="only show tags")
@click.option('-e', '--elapsed', is_flag=True,
help="only show time elapsed")
@click.pass_obj
@catch_watson_error
def status(watson, project, tags, elapsed):
"""
Display when the current project was started and the time spent since.
You can configure how the date and time of when the project was started are
displayed by setting `options.date_format` and `options.time_format` in the
configuration. The syntax of these formatting strings and the supported
placeholders are the same as for the `strftime` method of Python's
`datetime.datetime` class.
Example:
\b
$ watson status
Project apollo11 [brakes] started seconds ago (2014-05-19 14:32:41+0100)
$ watson config options.date_format %d.%m.%Y
$ watson config options.time_format "at %I:%M %p"
$ watson status
Project apollo11 [brakes] started a minute ago (19.05.2014 at 02:32 PM)
"""
if not watson.is_started:
click.echo("No project started.")
return
current = watson.current
if project:
click.echo("{}".format(
style('project', current['project']),
))
return
if tags:
click.echo("{}".format(
style('tags', current['tags'])
))
return
if elapsed:
click.echo("{}".format(
style('time', current['start'].humanize())
))
return
datefmt = watson.config.get('options', 'date_format', '%Y.%m.%d')
timefmt = watson.config.get('options', 'time_format', '%H:%M:%S%z')
click.echo("Project {}{} started {} ({} {})".format(
style('project', current['project']),
(" " if current['tags'] else "") + style('tags', current['tags']),
style('time', current['start'].humanize()),
style('date', current['start'].strftime(datefmt)),
style('time', current['start'].strftime(timefmt))
))
_SHORTCUT_OPTIONS = ['all', 'year', 'month', 'luna', 'week', 'day']
_SHORTCUT_OPTIONS_VALUES = {
k: get_start_time_for_period(k) for k in _SHORTCUT_OPTIONS
}
@cli.command()
@click.option('-c/-C', '--current/--no-current', 'current', default=None,
help="(Don't) include currently running frame in report.")
@click.option('-f', '--from', 'from_', cls=MutuallyExclusiveOption,
type=DateTime, default=arrow.now().shift(days=-7),
mutually_exclusive=_SHORTCUT_OPTIONS,
help="The date from when the report should start. Defaults "
"to seven days ago.")
@click.option('-t', '--to', cls=MutuallyExclusiveOption, type=DateTime,
default=arrow.now(),
mutually_exclusive=_SHORTCUT_OPTIONS,
help="The date at which the report should stop (inclusive). "
"Defaults to tomorrow.")
@click.option('-y', '--year', cls=MutuallyExclusiveOption, type=DateTime,
flag_value=_SHORTCUT_OPTIONS_VALUES['year'],
mutually_exclusive=['day', 'week', 'luna', 'month', 'all'],
help='Reports activity for the current year.')
@click.option('-m', '--month', cls=MutuallyExclusiveOption, type=DateTime,
flag_value=_SHORTCUT_OPTIONS_VALUES['month'],
mutually_exclusive=['day', 'week', 'luna', 'year', 'all'],
help='Reports activity for the current month.')
@click.option('-l', '--luna', cls=MutuallyExclusiveOption, type=DateTime,
flag_value=_SHORTCUT_OPTIONS_VALUES['luna'],
mutually_exclusive=['day', 'week', 'month', 'year', 'all'],
help='Reports activity for the current moon cycle.')
@click.option('-w', '--week', cls=MutuallyExclusiveOption, type=DateTime,
flag_value=_SHORTCUT_OPTIONS_VALUES['week'],
mutually_exclusive=['day', 'month', 'luna', 'year', 'all'],
help='Reports activity for the current week.')
@click.option('-d', '--day', cls=MutuallyExclusiveOption, type=DateTime,
flag_value=_SHORTCUT_OPTIONS_VALUES['day'],
mutually_exclusive=['week', 'month', 'luna', 'year', 'all'],
help='Reports activity for the current day.')
@click.option('-a', '--all', cls=MutuallyExclusiveOption, type=DateTime,
flag_value=_SHORTCUT_OPTIONS_VALUES['all'],
mutually_exclusive=['day', 'week', 'month', 'luna', 'year'],
help='Reports all activities.')
@click.option('-p', '--project', 'projects', shell_complete=get_projects,
multiple=True,
help="Reports activity only for the given project. You can add "
"other projects by using this option several times.")
@click.option('-T', '--tag', 'tags', shell_complete=get_tags, multiple=True,
help="Reports activity only for frames containing the given "
"tag. You can add several tags by using this option multiple "
"times")
@click.option('--ignore-project', 'ignore_projects', multiple=True,
help="Reports activity for all projects but the given ones. You "
"can ignore several projects by using the option multiple "
"times. Any given project will be ignored")
@click.option('--ignore-tag', 'ignore_tags', multiple=True,
help="Reports activity for all tags but the given ones. You can "
"ignore several tags by using the option multiple times. Any "
"given tag will be ignored")
@click.option('-j', '--json', 'output_format', cls=MutuallyExclusiveOption,
flag_value='json', mutually_exclusive=['csv'],
help="Format output in JSON instead of plain text")
@click.option('-s', '--csv', 'output_format', cls=MutuallyExclusiveOption,
flag_value='csv', mutually_exclusive=['json'],
help="Format output in CSV instead of plain text")
@click.option('--plain', 'output_format', cls=MutuallyExclusiveOption,
flag_value='plain', mutually_exclusive=['json', 'csv'],
default=True, hidden=True,
help="Format output in plain text (default)")
@click.option('-g/-G', '--pager/--no-pager', 'pager', default=None,
help="(Don't) view output through a pager.")
@click.pass_obj
@catch_watson_error
def report(watson, current, from_, to, projects, tags, ignore_projects,
ignore_tags, year, month, week, day, luna, all, output_format,
pager, aggregated=False, include_partial_frames=True):
"""
Display a report of the time spent on each project.
If a project is given, the time spent on this project is printed.
Else, print the total for each root project.
By default, the time spent the last 7 days is printed. This timespan
can be controlled with the `--from` and `--to` arguments. The dates
must have the format `YEAR-MONTH-DAY`, like: `2014-05-19`.
You can also use special shortcut options for easier timespan control:
`--day` sets the report timespan to the current day (beginning at `00:00h`)
and `--year`, `--month` and `--week` to the current year, month, or week,
respectively.
The shortcut `--luna` sets the timespan to the current moon cycle with
the last full moon marking the start of the cycle.
You can limit the report to a project or a tag using the `--project`,
`--tag`, `--ignore-project` and `--ignore-tag` options. They can be
specified several times each to add or ignore multiple projects or
tags to the report.
If you are outputting to the terminal, you can selectively enable a pager
through the `--pager` option.
You can change the output format for the report from *plain text* to *JSON*
using the `--json` option or to *CSV* using the `--csv` option. Only one
of these two options can be used at once.
Example:
\b
$ watson report
Mon 05 May 2014 -> Mon 12 May 2014
\b
apollo11 - 13h 22m 20s
[brakes 7h 53m 18s]
[module 7h 41m 41s]
[reactor 8h 35m 50s]
[steering 10h 33m 37s]
[wheels 10h 11m 35s]
\b
hubble - 8h 54m 46s
[camera 8h 38m 17s]
[lens 5h 56m 22s]
[transmission 6h 27m 07s]
\b
voyager1 - 11h 45m 13s
[antenna 5h 53m 57s]
[generators 9h 04m 58s]
[probe 10h 14m 29s]
[sensors 10h 30m 26s]
\b
voyager2 - 16h 16m 09s
[antenna 7h 05m 50s]
[generators 12h 20m 29s]
[probe 12h 20m 29s]
[sensors 11h 23m 17s]
\b
Total: 43h 42m 20s
\b
$ watson report --from 2014-04-01 --to 2014-04-30 --project apollo11
Tue 01 April 2014 -> Wed 30 April 2014
\b
apollo11 - 13h 22m 20s
[brakes 7h 53m 18s]
[module 7h 41m 41s]
[reactor 8h 35m 50s]
[steering 10h 33m 37s]
[wheels 10h 11m 35s]
\b
$ watson report --json
{
"projects": [
{
"name": "watson",
"tags": [
{
"name": "export",
"time": 530.0
},
{
"name": "report",
"time": 530.0
}
],
"time": 530.0
}
],
"time": 530.0,
"timespan": {
"from": "2016-02-21T00:00:00-08:00",
"to": "2016-02-28T23:59:59.999999-08:00"
}
}
\b
$ watson report --from 2014-04-01 --to 2014-04-30 --project apollo11 --csv
from,to,project,tag,time
2014-04-01 00:00:00,2014-04-30 23:59:59,apollo11,,48140.0
2014-04-01 00:00:00,2014-04-30 23:59:59,apollo11,brakes,28421.0
2014-04-01 00:00:00,2014-04-30 23:59:59,apollo11,module,27701.0
2014-04-01 00:00:00,2014-04-30 23:59:59,apollo11,reactor,30950.0
2014-04-01 00:00:00,2014-04-30 23:59:59,apollo11,steering,38017.0
2014-04-01 00:00:00,2014-04-30 23:59:59,apollo11,wheels,36695.0
"""
# if the report is an aggregate report, add whitespace using this
# aggregate tab which will be prepended to the project name
if aggregated:
tab = ' '
else:
tab = ''
report = watson.report(from_, to, current, projects, tags,
ignore_projects, ignore_tags,
year=year, month=month, week=week, day=day,
luna=luna, all=all,
include_partial_frames=include_partial_frames)
if 'json' in output_format and not aggregated:
click.echo(json.dumps(report, indent=4, sort_keys=True,
default=json_arrow_encoder))
return
elif 'csv' in output_format and not aggregated:
click.echo(build_csv(flatten_report_for_csv(report)))
return
elif 'plain' not in output_format and aggregated:
return report
lines = []
# use the pager, or print directly to the terminal
if pager or (pager is None and
watson.config.getboolean('options', 'pager', True)):
def _print(line):
lines.append(line)
def _final_print(lines):
click.echo_via_pager('\n'.join(lines))
elif aggregated:
def _print(line):
lines.append(line)
def _final_print(lines):
pass
else:
def _print(line):
click.echo(line)
def _final_print(lines):
pass
# handle special title formatting for aggregate reports
if aggregated:
_print('{} - {}'.format(
style('date', '{:ddd DD MMMM YYYY}'.format(
report['timespan']['from']
)),
style('time', '{}'.format(format_timedelta(
datetime.timedelta(seconds=report['time'])
)))
))
else:
_print('{} -> {}\n'.format(
style('date', '{:ddd DD MMMM YYYY}'.format(
report['timespan']['from']
)),
style('date', '{:ddd DD MMMM YYYY}'.format(
report['timespan']['to']
))
))
projects = report['projects']
for project in projects:
_print('{tab}{project} - {time}'.format(
tab=tab,
time=style('time', format_timedelta(
datetime.timedelta(seconds=project['time'])
)),
project=style('project', project['name'])
))
tags = project['tags']
if tags:
longest_tag = max(len(tag) for tag in tags or [''])
for tag in tags:
_print('\t[{tag} {time}]'.format(
time=style('time', '{:>11}'.format(format_timedelta(
datetime.timedelta(seconds=tag['time'])
))),
tag=style('tag', '{:<{}}'.format(
tag['name'], longest_tag
)),
))
_print("")
# if this is a report invoked from `aggregate` return the lines; do not
# show total time
if aggregated:
return lines
_print('Total: {}'.format(
style('time', '{}'.format(format_timedelta(
datetime.timedelta(seconds=report['time'])
)))
))
_final_print(lines)
@cli.command()
@click.option('-c/-C', '--current/--no-current', 'current', default=None,
help="(Don't) include currently running frame in report.")
@click.option('-f', '--from', 'from_', cls=MutuallyExclusiveOption,
type=DateTime, default=arrow.now().shift(days=-7),
mutually_exclusive=_SHORTCUT_OPTIONS,
help="The date from when the report should start. Defaults "
"to seven days ago.")
@click.option('-t', '--to', cls=MutuallyExclusiveOption, type=DateTime,
default=arrow.now(),
mutually_exclusive=_SHORTCUT_OPTIONS,
help="The date at which the report should stop (inclusive). "
"Defaults to tomorrow.")
@click.option('-p', '--project', 'projects', shell_complete=get_projects,
multiple=True,
help="Reports activity only for the given project. You can add "
"other projects by using this option several times.")
@click.option('-T', '--tag', 'tags', shell_complete=get_tags, multiple=True,
help="Reports activity only for frames containing the given "
"tag. You can add several tags by using this option multiple "
"times")
@click.option('-j', '--json', 'output_format', cls=MutuallyExclusiveOption,
flag_value='json', mutually_exclusive=['csv'],
help="Format output in JSON instead of plain text")
@click.option('-s', '--csv', 'output_format', cls=MutuallyExclusiveOption,
flag_value='csv', mutually_exclusive=['json'],
help="Format output in CSV instead of plain text")
@click.option('--plain', 'output_format', cls=MutuallyExclusiveOption,
flag_value='plain', mutually_exclusive=['json', 'csv'],
default=True, hidden=True,
help="Format output in plain text (default)")
@click.option('-g/-G', '--pager/--no-pager', 'pager', default=None,
help="(Don't) view output through a pager.")
@click.pass_obj
@click.pass_context
@catch_watson_error
def aggregate(ctx, watson, current, from_, to, projects, tags, output_format,
pager):
"""
Display a report of the time spent on each project aggregated by day.
If a project is given, the time spent on this project is printed.
Else, print the total for each root project.
By default, the time spent the last 7 days is printed. This timespan
can be controlled with the `--from` and `--to` arguments. The dates
must have the format `YEAR-MONTH-DAY`, like: `2014-05-19`.
You can limit the report to a project or a tag using the `--project` and
`--tag` options. They can be specified several times each to add multiple
projects or tags to the report.
If you are outputting to the terminal, you can selectively enable a pager
through the `--pager` option.
You can change the output format from *plain text* to *JSON* using the
`--json` option or to *CSV* using the `--csv` option. Only one of these
two options can be used at once.
Example:
\b
$ watson aggregate
Wed 14 November 2018 - 5h 42m 22s
watson - 5h 42m 22s
[features 34m 06s]
[docs 5h 08m 16s]
\b
Thu 15 November 2018 - 00s
\b
Fri 16 November 2018 - 00s
\b
Sat 17 November 2018 - 00s
\b
Sun 18 November 2018 - 00s
\b
Mon 19 November 2018 - 5h 58m 52s
watson - 5h 58m 52s
[features 1h 12m 03s]
[docs 4h 46m 49s]
\b
Tue 20 November 2018 - 2h 50m 35s
watson - 2h 50m 35s
[features 15m 17s]
[docs 1h 37m 43s]
[website 57m 35s]
\b
Wed 21 November 2018 - 01m 17s
watson - 01m 17s
[docs 01m 17s]
\b
$ watson aggregate --csv
from,to,project,tag,time
2018-11-14 00:00:00,2018-11-14 23:59:59,watson,,20542.0
2018-11-14 00:00:00,2018-11-14 23:59:59,watson,features,2046.0
2018-11-14 00:00:00,2018-11-14 23:59:59,watson,docs,18496.0
2018-11-19 00:00:00,2018-11-19 23:59:59,watson,,21532.0
2018-11-19 00:00:00,2018-11-19 23:59:59,watson,features,4323.0
2018-11-19 00:00:00,2018-11-19 23:59:59,watson,docs,17209.0
2018-11-20 00:00:00,2018-11-20 23:59:59,watson,,10235.0
2018-11-20 00:00:00,2018-11-20 23:59:59,watson,features,917.0
2018-11-20 00:00:00,2018-11-20 23:59:59,watson,docs,5863.0
2018-11-20 00:00:00,2018-11-20 23:59:59,watson,website,3455.0
2018-11-21 00:00:00,2018-11-21 23:59:59,watson,,77.0
2018-11-21 00:00:00,2018-11-21 23:59:59,watson,docs,77.0
"""
delta = (to - from_).days
lines = []
for i in range(delta + 1):
offset = datetime.timedelta(days=i)
from_offset = from_ + offset
output = ctx.invoke(report, current=current, from_=from_offset,
to=from_offset, projects=projects, tags=tags,
output_format=output_format,
pager=pager, aggregated=True,
include_partial_frames=True)
if 'json' in output_format:
lines.append(output)
elif 'csv' in output_format:
lines.extend(flatten_report_for_csv(output))
else:
# if there is no activity for the day, append a newline
# this ensures even spacing throughout the report
if (len(output)) == 1:
output[0] += '\n'
lines.append('\n'.join(output))
if 'json' in output_format:
click.echo(json.dumps(lines, indent=4, sort_keys=True,
default=json_arrow_encoder))
elif 'csv' in output_format:
click.echo(build_csv(lines))
elif pager or (pager is None and
watson.config.getboolean('options', 'pager', True)):
click.echo_via_pager('\n\n'.join(lines))
else:
click.echo('\n\n'.join(lines))
@cli.command()
@click.option('-c/-C', '--current/--no-current', 'current', default=None,
help="(Don't) include currently running frame in output.")
@click.option('-r/-R', '--reverse/--no-reverse', 'reverse', default=None,
help="(Don't) reverse the order of the days in output.")
@click.option('-f', '--from', 'from_', type=DateTime,
default=arrow.now().shift(days=-7),
help="The date from when the log should start. Defaults "
"to seven days ago.")
@click.option('-t', '--to', type=DateTime, default=arrow.now(),
help="The date at which the log should stop (inclusive). "
"Defaults to tomorrow.")
@click.option('-y', '--year', cls=MutuallyExclusiveOption, type=DateTime,
flag_value=_SHORTCUT_OPTIONS_VALUES['year'],
mutually_exclusive=['day', 'week', 'month', 'all'],
help='Reports activity for the current year.')
@click.option('-m', '--month', cls=MutuallyExclusiveOption, type=DateTime,
flag_value=_SHORTCUT_OPTIONS_VALUES['month'],
mutually_exclusive=['day', 'week', 'year', 'all'],
help='Reports activity for the current month.')
@click.option('-l', '--luna', cls=MutuallyExclusiveOption, type=DateTime,
flag_value=_SHORTCUT_OPTIONS_VALUES['luna'],
mutually_exclusive=['day', 'week', 'month', 'year', 'all'],
help='Reports activity for the current moon cycle.')
@click.option('-w', '--week', cls=MutuallyExclusiveOption, type=DateTime,
flag_value=_SHORTCUT_OPTIONS_VALUES['week'],
mutually_exclusive=['day', 'month', 'year', 'all'],
help='Reports activity for the current week.')
@click.option('-d', '--day', cls=MutuallyExclusiveOption, type=DateTime,
flag_value=_SHORTCUT_OPTIONS_VALUES['day'],
mutually_exclusive=['week', 'month', 'year', 'all'],
help='Reports activity for the current day.')
@click.option('-a', '--all', cls=MutuallyExclusiveOption, type=DateTime,
flag_value=_SHORTCUT_OPTIONS_VALUES['all'],
mutually_exclusive=['day', 'week', 'month', 'year'],
help='Reports all activities.')
@click.option('-p', '--project', 'projects', shell_complete=get_projects,
multiple=True,
help="Logs activity only for the given project. You can add "
"other projects by using this option several times.")
@click.option('-T', '--tag', 'tags', shell_complete=get_tags, multiple=True,
help="Logs activity only for frames containing the given "
"tag. You can add several tags by using this option multiple "
"times")
@click.option('--ignore-project', 'ignore_projects', multiple=True,
help="Logs activity for all projects but the given ones. You "
"can ignore several projects by using the option multiple "
"times. Any given project will be ignored")
@click.option('--ignore-tag', 'ignore_tags', multiple=True,
help="Logs activity for all tags but the given ones. You can "
"ignore several tags by using the option multiple times. Any "
"given tag will be ignored")
@click.option('-j', '--json', 'output_format', cls=MutuallyExclusiveOption,
flag_value='json', mutually_exclusive=['csv'],
help="Format output in JSON instead of plain text")
@click.option('-s', '--csv', 'output_format', cls=MutuallyExclusiveOption,
flag_value='csv', mutually_exclusive=['json'],
help="Format output in CSV instead of plain text")
@click.option('--plain', 'output_format', cls=MutuallyExclusiveOption,
flag_value='plain', mutually_exclusive=['json', 'csv'],
default=True, hidden=True,
help="Format output in plain text (default)")
@click.option('-g/-G', '--pager/--no-pager', 'pager', default=None,
help="(Don't) view output through a pager.")
@click.pass_obj
@catch_watson_error
def log(watson, current, reverse, from_, to, projects, tags, ignore_projects,
ignore_tags, year, month, week, day, luna, all, output_format, pager):
"""
Display each recorded session during the given timespan.
By default, the sessions from the last 7 days are printed. This timespan
can be controlled with the `--from` and `--to` arguments. The dates
must have the format `YEAR-MONTH-DAY`, like: `2014-05-19`.
You can also use special shortcut options for easier timespan control:
`--day` sets the log timespan to the current day (beginning at `00:00h`)
and `--year`, `--month` and `--week` to the current year, month, or week,
respectively.
The shortcut `--luna` sets the timespan to the current moon cycle with
the last full moon marking the start of the cycle.
If you are outputting to the terminal, you can selectively enable a pager
through the `--pager` option.
You can limit the log to a project or a tag using the `--project`,
`--tag`, `--ignore-project` and `--ignore-tag` options. They can be
specified several times each to add or ignore multiple projects or
tags in the log.
You can change the output format from *plain text* to *JSON* using the
`--json` option or to *CSV* using the `--csv` option. Only one of these
two options can be used at once.