forked from mattpolzin/Sprintly-GitHub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsprintly
executable file
·1331 lines (1091 loc) · 56 KB
/
sprintly
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
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys, os, locale, urllib, urllib2, json, subprocess, re, string, logging, os, tempfile, traceback
from curses import setupterm, tigetstr, tigetnum, tparm
from time import time
from argparse import ArgumentParser
from subprocess import call
if os.name == 'nt': import ctypes, struct
try:
import tre
FUZ0 = tre.Fuzzyness(maxerr = 0)
FUZ1 = tre.Fuzzyness(maxerr = 1)
FUZ2 = tre.Fuzzyness(maxerr = 2)
except ImportError:
FUZ = None
print 'Fuzzy regex not available, search will not work'
# force utf-8 encoding
reload(sys)
sys.setdefaultencoding('utf-8')
if os.name == 'nt': import uniconsole
logging.basicConfig()
logger = logging.getLogger(__name__)
# constants
CONFIG_VERSION = '2.1'
SPRINTLY_NAME = 'sprintly'
SPRINTLY_DIR = '/usr/local/bin/' if os.name != 'nt' else os.environ.get("PYTHONHOME") + '/Scripts/'
SPRINTLY_SOURCE_URL = 'https://raw.github.com/bumboarder6/Sprintly-GitHub/master/sprintly'
# non-editable constants
SPRINTLY_PATH = SPRINTLY_DIR + SPRINTLY_NAME
# tty colors
DEFAULT = '\x1b[39m'
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, LIGHT_GREY = [('\x1b[%dm' % (30 + i)) for i in range(8)]
GREY, BRIGHT_RED, BRIGHT_GREEN, BRIGHT_YELLOW, BRIGHT_BLUE, BRIGHT_MAGENTA, BRIGHT_CYAN, WHITE = [('\x1b[%dm' % (90 + i)) for i in range(8)]
RESET, NORMAL, BOLD, DIM, UNDERLINE, INVERT, HIDDEN = [('\x1b[%dm' % i) for i in (0, 22, 1, 2, 4, 7, 8)]
ATTRS = {
'DEFAULT': DEFAULT,
'BLACK': BLACK, 'RED': RED, 'GREEN': GREEN, 'YELLOW': YELLOW, 'BLUE': BLUE, 'MAGENTA': MAGENTA, 'CYAN': CYAN, 'LIGHT_GREY': LIGHT_GREY,
'GREY': GREY, 'BRIGHT_RED': BRIGHT_RED, 'BRIGHT_GREEN': BRIGHT_GREEN, 'BRIGHT_YELLOW': BRIGHT_YELLOW, 'BRIGHT_BLUE': BRIGHT_BLUE, 'BRIGHT_MAGENTA': BRIGHT_MAGENTA, 'BRIGHT_CYAN': BRIGHT_CYAN, 'WHITE': WHITE,
'RESET': RESET, 'NORMAL': NORMAL, 'BOLD': BOLD, 'DIM': DIM, 'UNDERLINE': UNDERLINE, 'INVERT': INVERT, 'HIDDEN': HIDDEN
}
ITEM_COLORS = {
'story': 'GREEN',
'task': 'GREY',
'defect': 'RED',
'test': 'CYAN'
}
ITEM_STATUSES = {
'someday': 'Someday',
'backlog': "Backlog",
'in-progress': "In Progress",
'completed': "Completed",
'accepted': "Accepted",
}
ITEM_SCORES = {
'~': 'No Score',
'S': 'Small Matter',
'M': 'Eh Kinda Hard',
'L': 'Breakin a sweat',
'XL': 'WTF'
}
EDITOR = os.environ.get('EDITOR', 'emacs')
INIT_MSG = '# Please enter your %s below, any commented lines will be removed'
def messageFromEditor(usage, replace=False):
""" Spawns an editor with the init message in it then returns the contents
after it is finished and saved, returns None if there was an empty file """
tmp = tempfile.NamedTemporaryFile(suffix=".tmp", delete=False)
if not replace:
tmp.write(INIT_MSG % (usage,))
else:
tmp.write(usage)
tmp.flush()
name = tmp.name
tmp.close()
call([EDITOR, name])
tmp = open(name, 'r')
data = tmp.read()
tmp.close()
os.remove(name)
return re.sub('^\s*#.*?$', '', data, flags=re.M | re.I).strip()
def getHighlightedStr(data, regex):
""" Highlights the matches of the pattern in the string by
coloring them bright green then it returns the string,
assumes regex is a (pattern, and fuz object)"""
pat = regex[0]
fuz = regex[1]
new_data = ''
match = pat.search(data, fuz)
while match:
group = match.groups()[0]
new_data += data[:group[0]] + '${GREEN}' + data[group[0]:group[1]] + '${DEFAULT}'
data = data[group[1]:]
match = pat.search(data, fuz)
return new_data + data
class SprintlyTool:
"""
A command line tool for displaying your stories, tasks, tests, and defects
from Sprint.ly.
"""
def __init__(self, term_stream=sys.stdout):
"""
Initialize instance variables.
"""
# Set up terminal
if os.name != 'nt': locale.setlocale(locale.LC_ALL, '')
self._encoding = locale.getpreferredencoding()
self._term = term_stream or sys.__stdout__
self._is_tty = False
self._has_color = False
self._cols = 80
if hasattr(term_stream, "isatty") and term_stream.isatty():
try:
if os.name != 'nt':
setupterm()
self._has_color = (tigetnum('colors') > 2)
self._cols = tigetnum('cols')
else:
self._has_color = True
self._cols = _get_terminal_size_windows()[0] - 1
self._is_tty = True
except:
pass
else:
try:
(_, columns) = os.popen('stty size', 'r').read().split()
self._cols = int(columns)
except:
pass
self._config = {}
self._sprintlyDirectoryPath = None
self._sprintlyConfigPath = None
self.parser = None
def run(self, scr=None):
"""
Application flow.
"""
# self.cprint('${BLACK} Black ${RED} RED ${GREEN} GREEN ${YELLOW} YELLOW ${BLUE} BLUE ${MAGENTA} MAGENTA ${CYAN} CYAN ${LIGHT_GREY} LIGHT_GREY ${GREY} GREY ${BRIGHT_RED} BRIGHT_RED ${BRIGHT_GREEN} BRIGHT_GREEN ${BRIGHT_YELLOW} BRIGHT_YELLOW ${BRIGHT_BLUE} BRIGHT_BLUE ${BRIGHT_MAGENTA} BRIGHT_MAGENTA ${BRIGHT_CYAN} BRIGHT_CYAN ${WHITE} WHITE')
try:
self.initialize()
if len(sys.argv) == 1:
self._items_action()
return
match = re.match('^-(\d+)$', sys.argv[1])
if len(sys.argv) > 1 and match:
sys.argv.insert(1, 'item')
sys.argv[2] = match.group(1)
description = 'By default, your Sprint.ly items will be shown.'
parser = ArgumentParser(description=description)
subparsers = parser.add_subparsers(dest='action_name')
install_p = subparsers.add_parser('install', help='install this tool.')
install_p.set_defaults(func=self._installAndInit)
update_p = subparsers.add_parser('update', help='update this tool.')
update_p.set_defaults(func=self._updateAndInit)
update_config_p = subparsers.add_parser('update-config', help='edit configuration.')
update_config_p.set_defaults(func=self._initAndUpdateConfig)
users_p = subparsers.add_parser('users', help='Get/set user information. Lists users by default.')
users_p.set_defaults(func=self._users_action)
users_p.add_argument('-p', '--product', action='store_true', help='List users by the product they work on.')
users_p_arg_group = users_p.add_mutually_exclusive_group()
users_p_arg_group.add_argument('-l', '--list', action='store_true', help='List users.')
items_p = subparsers.add_parser('items', help='Lists your items by default')
items_p.set_defaults(func=self._items_action)
items_p.add_argument('-c', '--completed', action='store_true', help='List completed tasks as well. Default is to only list backlog/in-progress')
items_p.add_argument('-s', '--someday', action='store_true', help='List someday (or triage) tasks as well. Default is to only list backlog/in-progress')
items_p.add_argument('-b', '--omit-backlog', dest='omit_backlog', action='store_true', help='Do not show backlog items.')
items_p.add_argument('-i', '--omit-in-progress', dest='omit_in_progress', action='store_true', help='Do not show in-progress items.')
items_p_arg_group = items_p.add_mutually_exclusive_group()
items_p_arg_group.add_argument('-u', '--user', default=None, help='Specify a user. Defaults to you. Matches against email.')
items_p_arg_group.add_argument('-z', '--unassigned', action='store_true', help='Specify that only unassigned items should be listed.')
items_p_arg_group.add_argument('-y', '--anyone', action='store_true', help='Specify that items assigned to anyone should be listed.')
search_p = subparsers.add_parser('search', help='Search for matching items')
search_p.set_defaults(func=self._search_action)
search_p.add_argument('query', metavar='query', type=str, help='The regular expression to search sprintly items for')
search_p.add_argument('-c', '--completed', action='store_true', help='Search completed tasks as well. Default is to only search backlog/in-progress')
search_p.add_argument('-s', '--someday', action='store_true', help='Search someday (or triage) tasks as well. Default is to only search backlog/in-progress')
search_p.add_argument('-b', '--omit-backlog', dest='omit_backlog', action='store_true', help='Do not search backlog items.')
search_p.add_argument('-a', '--search-all', dest='searchAll', action='store_true', help='Shortcut for -c -s')
search_p.add_argument('-m', '--search-comments', dest='searchComments', action='store_true', help='Optionally comment fields')
item_p = subparsers.add_parser('item', help='Display Item Specifics or Edit an item')
item_p.set_defaults(func=self._item_action, new=False)
item_p.add_argument('itemID', metavar='ID', type=int, help='The ID of the item to list or edit')
item_p.add_argument('-s', '--status', type=str, help='The new status to set this item to', choices=ITEM_STATUSES.keys())
item_p.add_argument('-z', '--size', type=str, help='The approximate size of the item', choices=ITEM_SCORES.keys())
item_p.add_argument('-t', '--title', type=str, help='The new title to set for this item')
item_p.add_argument('-u', '--user', type=str, help='The user to assign this item to (email matched)')
item_p.add_argument('-d', '--description', nargs='?', type=str, default=False, const=True, help='Starts an editor for you to insert a description')
item_p.add_argument('-g', '--tags', type=str, help='comma delimited tags to attach to the item')
item_p.add_argument('-p', '--parent', type=int, help='The parent story to add this to')
item_p.add_argument('-r', '--remove', action='store_true', help='REMOVES THE ITEM')
item_p.add_argument('-c', '--comment', nargs='?', type=str, default=False, const=True, help='Adds a new comment to the item')
add_p = subparsers.add_parser('add', help='Add a new item to sprintly')
add_p.set_defaults(func=self._item_action, new=True, itemID=None, comment=False)
add_p.add_argument('type', metavar='type', type=str, help='The new item type to add', choices=ITEM_COLORS.keys())
add_p.add_argument('title', metavar='title', type=str, help='The new title to set for this item (for stories, this is the "what")')
add_p.add_argument('-d', '--description', nargs='?', type=str, default=False, const=True, help='Starts an editor for you to insert a description')
add_p.add_argument('-s', '--status', type=str, help='The new status to set this item to', choices=ITEM_STATUSES.keys())
add_p.add_argument('-z', '--size', type=str, help='The approximate size of the item', choices=ITEM_SCORES.keys())
add_p.add_argument('-u', '--user', type=str, help='The user to assign this item to (email matched)')
add_p.add_argument('-g', '--tags', type=str, help='comma delimited tags to attach to the item')
add_p.add_argument('-p', '--parent', type=int, help='The parent story to add this to (non stories only)')
add_p.add_argument('--who', type=str, help='Required for stories, who is requesting this')
add_p.add_argument('--why', type=str, help='Required for stories, why is this story important')
start_p = subparsers.add_parser('start', help='Start a task (equiv. to "sprintly item <item id> -s in-progress -u <your id>").')
start_p.set_defaults(func=self._item_action, new=False, remove=False, description=False, size=None, title=None, tags=None,
parent=None, status='in-progress', user=self._this_user())
start_p.add_argument('itemID', metavar='ID', type=int, help='The ID of the item to start.')
start_p.add_argument('-c', '--comment', nargs='?', type=str, default=False, const=True, help='Adds a new comment to the item')
stop_p = subparsers.add_parser('stop', help='Move a task to your backlog (equiv. to "sprintly item <item id> -s backlog -u <your id>").')
stop_p.set_defaults(func=self._item_action, new=False, remove=False, description=False, size=None, title=None, tags=None,
parent=None, status='backlog', user=self._this_user())
stop_p.add_argument('itemID', metavar='ID', type=int, help='The ID of the item to put in your backlog.')
stop_p.add_argument('-c', '--comment', action='store_true', help='Adds a new comment to the item')
complete_p = subparsers.add_parser('complete', help='Move a task to completed.')
complete_p.set_defaults(func=self._item_action, new=False, remove=False, description=False, size=None, title=None, tags=None,
parent=None, status='completed', user=self._this_user())
complete_p.add_argument('itemID', metavar='ID', type=int, help='The ID of the item to move to completed (equiv. to "sprintly item <item id> -s completed -u <your id>").')
complete_p.add_argument('-c', '--comment', nargs='?', type=str, default=False, const=True, help='Adds a new comment to the item')
today_p = subparsers.add_parser('today', help='Show comma separated list of task numbers in progress.');
today_p.set_defaults(func=self._today_action);
self.parser = parser
args = parser.parse_args()
args.func(args)
except Exception as e:
die('Fatal Error: %s', e)
def _initAndUpdateConfig(self, args):
self.updateConfig()
def _installAndInit(self, args):
self._installOrUpdateAndInit(False)
def _updateAndInit(self, args):
self._installOrUpdateAndInit(True)
def _installOrUpdateAndInit(self, update):
try:
self.install(update)
except SprintlyException:
type = 'install'
if update:
type = 'update'
self.cprint('Unable to %s. Try running again with sudo.' % (type), attr=RED)
return
self.initialize()
def _users_action(self, args):
# default to listing users
self.listSprintlyUsers(args.product)
def _items_action(self, args=None):
if args:
if args.unassigned:
args.user = None
elif args.user is None:
args.user = self._this_user()
self.listSprintlyItems(args.user, not args.omit_backlog,
not args.omit_in_progress, args.completed,
args.someday, args.anyone)
return
# default action, list this user's items:
self.listSprintlyItems(self._this_user())
def _search_action(self, args):
self.searchSprintlyItems(args.query, not args.omit_backlog, args.completed, args.someday, False, args.searchAll, args.searchComments)
def _item_action(self, args):
pid = str(self._config['product']['id'])
if args.itemID:
itemID = str(args.itemID)
item = self.sprintlyAPICall('products/' + pid + '/items/' + itemID + '.json')
if item.get('code') and item['code'] != 200:
self.cprint('This Item doesnt appear to exist')
return
else:
itemID = None
item = None
if itemID and args.remove:
if not itemID:
self.cprint("Can't delete something that hasn't been created")
return
if self.sprintlyAPICall('products/' + pid + '/items/' + itemID + '.json', delete=True):
self.cprint('Successfully Removed Item ' + itemID)
else:
self.cprint('Failed to remove item ' + itemID)
return
updates = []
if args.status:
if args.status not in ITEM_STATUSES.keys():
self.parser.print_help()
return
updates.append(('status', args.status))
if args.size:
if args.size not in ITEM_SCORES.keys():
self.parser.print_help()
return
updates.append(('score', args.size))
if args.title:
updates.append(('title', args.title))
if args.user:
userID = self.getUserByEmail(args.user)
if userID:
updates.append(('assigned_to', userID))
if type(args.description) in (str, unicode):
updates.append(('description', args.description))
elif args.description == True:
if item and item['description'].strip():
description = messageFromEditor(item['description'], replace=True)
else:
description = messageFromEditor('Description')
if not description:
self.cprint('No Description Entered')
else:
updates.append(('description', description))
if args.tags:
updates.append(('tags', args.tags))
if args.parent:
updates.append(('parent', args.parent))
if not itemID:
if args.type not in ('defect', 'test', 'task', 'story'):
self.cprint('Unsupported type for a new item')
self.parser.print_help()
return
updates.append(('type', args.type))
if args.type == 'story':
if not all([args.who, args.title, args.why]):
self.cprint('Missing Required Parameters For Story Type')
self.parser.print_help()
return
updates.append(('who', args.who))
updates.append(('what', args.title))
# need to remove title:
updates.remove(('title', args.title))
updates.append(('why', args.why))
resp = self.sprintlyAPICall('products/' + pid + '/items.json', updates)
if not resp:
self.cprint("Couldn't create the new item, check internet connection")
return
itemID = str(resp['number'])
else:
self.sprintlyAPICall('products/' + pid + '/items/' + itemID + '.json', updates)
if args.comment or type(args.comment) in (str, unicode):
if args.comment == True:
comment = messageFromEditor('Comment')
else:
comment = args.comment
if not comment:
self.cprint('No Comment entered')
return
if self.sprintlyAPICall('products/' + pid + '/items/' + itemID + '/comments.json', [('body', comment)]):
self.cprint('Successfully Commented on Item ' + itemID)
else:
self.cprint('Failed to comment, check internet connection')
return
item = self.sprintlyAPICall('products/' + pid + '/items/' + itemID + '.json')
#print item
color = ITEM_COLORS.get(item['type'])
printItem = '''${%s}#%d${DEFAULT} (%s):${BOLD} %s${RESET}'''
printAssignedTo = '''${DEFAULT}\tAssigned To: ${BOLD}%s${RESET}\n\tScore: ${BOLD}%s${RESET}\n'''
if not item['assigned_to']:
assigned_to = 'Unassigned'
else:
assigned_to = item['assigned_to']['first_name'] + ' ' + item['assigned_to']['last_name']
self.cprint(printItem % (
color, item['number'], ITEM_STATUSES[item['status']], item['title']
), trim=False)
self.cprint(printAssignedTo % (
assigned_to, ITEM_SCORES[item['score']]
))
if len(item['description']):
self.cprint('${UNDERLINE}${MAGENTA}Description:${RESET}${DEFAULT}')
self.cprint('\t' + item['description'] + '\n', trim=False)
if item['type'] == 'story':
children = self.sprintlyAPICall('products/' + pid + '/items/' + itemID + '/children.json')
if len (children) > 0:
self.cprint('${UNDERLINE}${MAGENTA}Children:${RESET}${DEFAULT}')
products = [{'id': pid, 'items': children, 'name': 'Vadio'}]
self.printItems(products, False)
comments = self.sprintlyAPICall('products/' + pid + '/items/' + itemID + '/comments.json')
if len(comments) > 0:
self.cprint('${UNDERLINE}${MAGENTA}Comments:${RESET}${DEFAULT}')
for comment in comments:
name = comment['created_by']['first_name'] + ' ' + comment['created_by']['last_name']
self.cprint('${DIM}%s${RESET}: %s' % (name, comment['body']), trim=False)
def _today_action(self, args):
products = self.getSprintlyItems(userId=self._this_user(),
listBacklogItems=False,
listInProgress=True,
listCompletedItems=False,
listSomedayItems=False,
getProductsFromServer=False,
limit=100, listAll=False)
for product in products:
if 'items' in product:
flat_filtered = []
colors = []
for item in product['items']:
if item['assigned_to']['id'] == self._this_user():
flat_filtered += [item['number']]
colors += [ITEM_COLORS.get(item['type'])]
if 'children' in item:
flat_filtered += map(lambda x: x['number'], item['children'])
colors += map(lambda x: ITEM_COLORS.get(x['type']), item['children'])
items = zip(colors, flat_filtered)
itemNumbers = map(lambda x: '${BOLD}${%s}#%d${RESET}' % tuple(x), items)
items = ', '.join(itemNumbers)
self.cprint(items)
def install(self, update):
"""
Install this tool at SPRINTLY_PATH. If another file already
exists with the same name, user will be prompted to replace the file.
"""
print 'Grabbing TRE fuzzy regex package...'
call(['wget', 'http://laurikari.net/tre/tre-0.8.0.tar.gz'])
call(['wget', 'https://raw.github.com/laurikari/tre/master/python/tre-python.c'])
call(['tar', '-xzvf', 'tre-0.8.0.tar.gz'])
call(['mv', 'tre-python.c', './tre-0.8.0/python/'])
os.chdir('./tre-0.8.0')
call('./configure')
call('make')
call(['sudo', 'make', 'install'])
os.chdir('./python')
call(['sudo', 'python', 'setup.py', 'install'])
os.chdir('../../')
call(['sudo', 'rm', '-rf', './tre-0.8.0'])
print 'Downloading latest version of sprintly from GitHub...'
# get the file
try:
response = urllib2.urlopen(SPRINTLY_SOURCE_URL)
sprintly_file_contents = response.read()
except Exception:
raise SprintlyException('Unable to obtain sprintly from %s' % SPRINTLY_SOURCE_URL)
# verify nothing exists at the target path
target = SPRINTLY_PATH
if os.name == 'nt': target += '.py'
if os.path.isfile(target):
overwrite = raw_input(self.render('${BRIGHT_YELLOW}A file already exists at %s.${RESET} Overwrite file? ' % target, trim=False))
while overwrite != 'y' and overwrite != 'n':
overwrite = raw_input('Please enter y/n: ')
if overwrite == 'n':
self.cprint('Unable to install. Please install manually.', attr=RED)
return
# remove existing file
print 'Deleting %s...' % target
try:
os.unlink(target)
except Exception:
raise SprintlyException('Unable to remove %s' % target)
# copy file to target
try:
if not os.path.isdir(SPRINTLY_DIR):
os.makedirs(SPRINTLY_DIR)
target_file = open(target, 'w')
target_file.write(sprintly_file_contents)
target_file.close()
except Exception:
raise SprintlyException('Unable to save file to %s' % target)
# ensure it is executable
try:
subprocess.call(['chmod', '+x', target])
except Exception:
raise SprintlyException('Unable to make %s executable.' % target)
# done!
self.cprint('Successfully installed sprintly to %s' % target, attr=GREEN)
# if this is not an update, install
if not update:
print ''
self.cprint('That\'s all! Type \'sprintly\' and hit enter to get started.', attr=BRIGHT_MAGENTA)
print ''
def initialize(self):
"""
Ultimate goal is to get the user and key from the config file.
If the config file cannot be found, a config file will be
created via prompts displayed to the user. A cache file will
also be created during this step.
"""
# get the users home directory
home = os.path.expanduser('~')
if home == '~':
raise SprintlyException('Unable to expand home directory.')
# set the sprintly directory path (create if it doesn't exist)
self._sprintlyDirectoryPath = os.path.join(home, '.sprintly')
if not os.path.isdir(self._sprintlyDirectoryPath):
os.mkdir(self._sprintlyDirectoryPath, 0700)
if not os.path.isdir(self._sprintlyDirectoryPath):
raise SprintlyException('Unable to create folder at %s' % self._sprintlyDirectoryPath)
# set the sprintly config path (create if it doesn't exist)
self._sprintlyConfigPath = os.path.join(self._sprintlyDirectoryPath, 'sprintly.config')
if not os.path.isfile(self._sprintlyConfigPath):
self.createSprintlyConfig()
# load config values
self.loadFromConfig()
def createSprintlyConfig(self, update=False):
"""
Create the Sprint.ly config. Prompt user for all necessary values.
When 'update' is set to True and an existing value is present for
a given configuration item, allow user to keep old value.
Note: if update is True, this must be called after initialize. Failure
to do so wil result in a new config being created, as the values in
self._config will not yet be set.
"""
if not update:
print 'Creating config...'
else:
print 'Updating config... Press enter to accept default value shown in brackets.'
# set version
self._config['version'] = CONFIG_VERSION
# used to simplify prompting user with optional default
def getConfigItem(message, default=None):
if default:
item = raw_input(self.render('%s [${YELLOW}%s${RESET}]: ' % (message, default), trim=False)) or default
else:
item = raw_input('%s: ' % message)
return item
# prompt for user
name = 'user'
message = 'Enter Sprint.ly username (email)'
if update and name in self._config:
self._config[name] = getConfigItem(message, self._config[name])
else:
self._config[name] = getConfigItem(message)
# prompt for key
name = 'key'
message = 'Enter Sprint.ly API Key'
if update and name in self._config:
self._config[name] = getConfigItem(message, self._config[name])
else:
self._config[name] = getConfigItem(message)
# try and use API with these values to determine validity
response = self.sprintlyAPICall('user/whoami.json')
if not response or 'code' in response:
raise SprintlyException('Invalid credentials. Unable to authenticate with Sprint.ly.')
if response['email'] != self._config['user']:
raise SprintlyException('Invalid credentials. Please ensure you are using your own API Key.')
# add user id to config
self._config['id'] = response['id']
# get a list of products and prompt user for default product if more than 1
products = self.sprintlyAPICall('products.json')
if not products:
raise SprintlyException('Unable to get product list.')
productMap = {}
for product in products:
productId = str(product['id'])
productMap[productId] = product
productCount = len(productMap)
if productCount == 0:
raise SprintlyException('It appears that you have no products associated with your Sprint.ly account. Please add at least one and then try again.')
elif productCount == 1:
self._config['product'] = productMap.values()[0]
else:
# prompt user for a product until they enter one found in the map
productList = ', '.join(['%d - %s' % (p['id'], p['name']) for p in productMap.values()])
defaultProductId = '0'
while defaultProductId not in productMap.keys():
message = 'Enter default Sprint.ly product id (%s)' % productList
if update and 'product' in self._config:
defaultProductId = getConfigItem(message, str(self._config['product']['id']))
else:
defaultProductId = getConfigItem(message)
self._config['product'] = productMap[defaultProductId]
# write config file if all is good
serialized_config = json.dumps(self._config)
try:
config_file = open(self._sprintlyConfigPath, 'w')
config_file.write(serialized_config)
config_file.close()
if not update:
self.cprint('Configuration successfully created.', attr=GREEN)
else:
self.cprint('Configuration successfully updated.', attr=GREEN)
except:
raise SprintlyException('Unable to write configuration to disk at %s' % self._sprintlyConfigPath)
def loadFromConfig(self):
"""
Load user and key from the config file. Validate here that the version
of this config is readable by this version of the tool.
"""
try:
config_file = open(self._sprintlyConfigPath, 'r')
serialized_config = config_file.readline()
config_file.close()
self._config = json.loads(serialized_config)
except:
raise SprintlyException('Unable to read credentials from disk at %s' % self._sprintlyConfigPath)
# validate version
if 'version' not in self._config or self._config['version'] != CONFIG_VERSION:
self.cprint('Your configuration needs to be updated. You will now be prompted to update it.', attr=YELLOW)
self.updateConfig()
def updateConfig(self):
"""
Prompt user to update configuration settings.
Defaults will be original config values if present.
"""
self.createSprintlyConfig(True)
def listSprintlyUsers(self, byProducts=False):
"""
Lists all Sprint.ly users by product.
"""
data = self.getSprintlyUsers(byProducts)
if not byProducts:
self.printUserArray(data)
return
self.printUsersByProducts(data)
def printUsersByProducts(self, products):
"""
List users by the product they work on.
"""
for product in products:
users = product['users']
productId = str(product['id'])
productName = product['name']
printProduct = '${DEFAULT}Product: ${BOLD}${BRIGHT_BLUE}' + productName + '${NORMAL}${GREY} (https://sprint.ly/product/' + productId + '/)'
self.cprint(printProduct)
for user in users:
printUser = '${NORMAL} ' + str(user['id']) + ': ${BOLD}${LIGHT_BLUE}' + user['first_name'] + ' ' + user['last_name'] + ' ${NORMAL}${GREY}(' + user['email'] + ')'
self.cprint(printUser)
self.cprint('')
def printUserArray(self, users):
"""
List all users from all products.
"""
for user_id in users:
user = users[user_id]
printUser = '${NORMAL}' + str(user['id']) + ': ${BOLD}${LIGHT_BLUE}' + user['first_name'] + ' ' + user['last_name'] + ' ${NORMAL}${GREY}(' + user['email'] + ')'
self.cprint(printUser)
self.cprint('')
def listSprintlyItems(self, userId = None, listBacklogItems=True,
listInProgress=True, listCompletedItems=False,
listSomedayItems=False, listAll=False):
"""
Lists all items for the current user from the Sprint.ly API.
listAll refers to all users, not all statuses.
"""
data = self.getSprintlyItems(userId, listBacklogItems, listInProgress,
listCompletedItems, listSomedayItems, False,
limit=2000, listAll=listAll)
self.printItems(data)
def printItems(self, products, shouldPrintHeader=True, regex=None):
"""
Print a list of Sprint.ly items.
"""
statusTree = {
'someday': {},
'backlog': {},
'in-progress': {},
'completed': {},
'accepted': {},
}
# An order that puts least viewed at the top and most viewed close
# to the bottom close to the command line
order = ['accepted', 'someday', 'completed', 'backlog', 'in-progress']
for product in products:
if 'items' in product:
for item in product['items']:
# If the item has children, place it under child status
# instead of parent status. The parent will be listed under
# its own status along with any children w/ same status
productNotInTree = not product['id'] in statusTree[item['status']]
parentItem = 'children' in item
notParentItem = not parentItem
if notParentItem:
# Straight forward, just add to status of parent
if productNotInTree:
statusTree[item['status']][product['id']] = [item]
else:
statusTree[item['status']][product['id']].append(item)
else:
# If it has children, it should be placed under the
# status of the children.
children = item['children']
first_child = children[0]
childStatus = first_child['status']
if not product['id'] in statusTree[childStatus]:
statusTree[childStatus][product['id']] = []
statusTree[childStatus][product['id']].append(item)
for key in order:
status = statusTree[key]
if not len(status):
continue
self.cprint(ITEM_STATUSES[key], attr=[BRIGHT_MAGENTA, UNDERLINE])
for product_id in status:
items = status[product_id]
name = items[0]['product']['name']
productId = str(items[0]['product']['id'])
if shouldPrintHeader:
printProduct = '${DEFAULT}Product: ${BOLD}${BRIGHT_BLUE}' + name + '${NORMAL}${GREY} (https://sprint.ly/product/' + productId + '/)'
self.cprint(printProduct)
for item in items:
if not item['assigned_to']:
assigned_to = '(Unassigned)'
else:
assigned_to = '(' + item['assigned_to']['first_name'] + ' ' + item['assigned_to']['last_name'] + ')'
attr = None
if item['status'] != key:
attr = DIM
color = ITEM_COLORS.get(item['type'])
title = item['title']
if regex:
title = getHighlightedStr(title, regex)
printItem = '${%s}%-6s${DEFAULT} %18s: ${DEFAULT}%s' % (
color, '#' + str(item['number']), assigned_to, title
)
self.cprint(printItem, attr=attr)
if 'children' in item:
for child in item['children']:
attr = None
childColor = ITEM_COLORS.get(child['type'])
title = child['title']
if regex:
title = getHighlightedStr(title, regex)
if not child['assigned_to']:
assigned_to = '(Unassigned)'
else:
assigned_to = '(' + child['assigned_to']['first_name'] + ' ' + child['assigned_to']['last_name'] + ')'
printChild = u'${%s} %-6s${DEFAULT} %18s: ${DEFAULT}%s' % (
childColor, '#' + str(child['number']), assigned_to, title
)
self.cprint(printChild, attr=attr)
self.cprint('')
def searchSprintlyItems(self, query, backlog=True, completed=False, someday=False, fromServer=False, searchAny=False, searchComments=False):
""" Searches sprintly for items that match in the description or title
TODO Optionally will search comments as well for results
"""
products = self.getSprintlyProducts(fromServer)
t_data = []
pat = tre.compile(query, tre.EXTENDED | tre.ICASE)
fuz = None
if len(query) < 4:
fuz = FUZ0
elif len(query) < 8:
fuz = FUZ1
else:
fuz = FUZ2
def filterList(item):
if pat.search(str(item['title']), fuz) or pat.search(str(item['description']), fuz):
return True
if item.get('children'):
for cItem in item['children']:
if pat.search(str(cItem['title']), fuz) or pat.search(str(cItem['description']), fuz):
return True
return False
t_data.append(self._getSprintlyItemsCore(None, status='in-progress', assoc=True, getProductsFromServer=fromServer, listAll=True))
if backlog or searchAny:
t_data.append(self._getSprintlyItemsCore(None, status='backlog', assoc=True, getProductsFromServer=fromServer, listAll=True))
if completed or searchAny:
t_data.append(self._getSprintlyItemsCore(None, status='completed', assoc=True, getProductsFromServer=fromServer, listAll=True))
if someday or searchAny:
t_data.append(self._getSprintlyItemsCore(None, status='someday', assoc=True, getProductsFromServer=fromServer, listAll=True))
for product in products:
if 'items' not in product:
product['items'] = []
for product in products:
for data in t_data:
if not data or not str(product['id']) in data:
continue
product['items'] = product['items'] + filter(filterList, data[str(product['id'])]['items'])
self.printItems(products, regex=(pat, fuz))
def getSprintlyItems(self, userId=None, listBacklogItems=True, listInProgress=True,
listCompletedItems=False, listSomedayItems=False,
getProductsFromServer=False, limit=100, listAll=False):
"""
Get all Sprint.ly items. By default gets unassigned items, but can
also retrieve for other users when given a user ID.
listAll refers to all users, not all statuses.
"""
if userId:
userId = self.getUserByEmail(userId)
products = self.getSprintlyProducts(getProductsFromServer)
t_data = []
if not userId:
print '\033[91m'
print 'No user selected. Showing unassigned. (user: "' + str(userId) + '")'
print '\033[0m'
if listInProgress:
t_data.append(self._getSprintlyItemsCore(userId, status='in-progress',
limit=limit, assoc=True,
getProductsFromServer=getProductsFromServer,
listAll=listAll))
if listBacklogItems:
t_data.append(self._getSprintlyItemsCore(userId, status='backlog',
limit=limit, assoc=True,
getProductsFromServer=getProductsFromServer,
listAll=listAll))
if listCompletedItems:
t_data.append(self._getSprintlyItemsCore(userId, status='completed',
limit=limit, assoc=True,
getProductsFromServer=getProductsFromServer,
listAll=listAll))
if listSomedayItems:
t_data.append(self._getSprintlyItemsCore(userId, status='someday',
limit=limit, assoc=True,
getProductsFromServer=getProductsFromServer,
listAll=listAll))
for product in products:
for data in t_data:
if data:
if str(product['id']) in data:
if 'items' not in product:
product['items'] = []
product['items'] = product['items'] + data[str(product['id'])]['items']
return products
def _getSprintlyItemsCore(self, userId=None, status=None, limit=100, getProductsFromServer=False, assoc=False, listAll=False):
"""
Get Sprint.ly items. By default, just in-progress and backlog items are
listed. Specify a status to limit to that status. pass assoc=True to
get an associative array back linking product IDs to products, rather
than the default array of products.
"""
if status != None:
status = '&status=' + status
else:
status = ''
data = None
if assoc:
data = {}
else:
data = []
products = self.getSprintlyProducts(getProductsFromServer)
try:
assigned_to = ''
if not listAll:
assigned_to = '&assigned_to=' + str(userId)
if not userId:
assigned_to = '&assigned_to=0'
# iterate over products
for product in products:
productName = product['name']
productId = str(product['id'])
items = []
offset = 0
while True:
itemsPartial = self.sprintlyAPICall('products/' + productId + '/items.json?children=1' + assigned_to + status + '&limit=' + str(limit) + '&offset=' + str(offset))
# if we get nothing, an empty list, an error, quit