Bugfix - fix value assignment for BTCLI-12 master
[pbt_cli.git] / pbt_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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
#!/usr/bin/env python
 
import urllib2
import json
import re
import time
 
import math
import sys, readline, os,stat,requests
import random
import hashlib
 
 
 
BASEDIR="https://projects.bentasker.co.uk/jira_projects"
AUTH=False
ADDITIONAL_HEADERS=False
DISKCACHE='/tmp/pbtcli.cache'
CACHE_TTL=900 # 15 mins
 
# I use this settings file to gain access to the non-public copy of my projects
if os.path.isfile(os.path.expanduser("~/.pbtcli.settings")):
    with open(os.path.expanduser("~/.pbtcli.settings"),'r') as f:
        for x in f:
            x = x.rstrip()
            if not x:
                continue
            
            # The lines are keyvalue pairs
            cfgline = x.split("=")
            if cfgline[0] == "BASEDIR":
                BASEDIR=cfgline[1]
 
            if cfgline[0] == "CACHE_TTL":
                CACHE_TTL=int(cfgline[1])
 
            if cfgline[0] == "DISKCACHE":
                DISKCACHE=cfgline[1]
                
            if cfgline[0] == "AUTH":
                AUTH='='.join(cfgline[1:])
 
            if cfgline[0] == "ADD_HEADER":
                if not ADDITIONAL_HEADERS:
                    ADDITIONAL_HEADERS = []
                    
                h = {
                        'name' : cfgline[1],
                        'value' : '='.join(cfgline[2:]),
                    }
                ADDITIONAL_HEADERS.append(h)
 
PROJURLS={}
ISSUEURLS={}
PROJDATA={}
 
 
class MemCache(dict):
    ''' A rudimentary in-memory cache with several storage areas and classes.
    By default, the permstorage area will get flushed once an hour
    
    Filched and amended from my RequestRouter project
    
    '''
    
    def __init__(self):
        self.storage = {}
        self.lastpurge = int(time.time())
        self.disabled = False
        self.config = {}
        self.config['doSelfPurge'] = False # Disabled as entries have their own TTL
        self.config['defaultTTL'] = 900 # 15 mins
        self.config['amOffline'] = False # Disable Offline mode by default
        self.config['LRUTarget'] = 0.25 # Percentage reduction target for LRUs
        
        # Seed hashes to try and avoid deliberate hash collisions
        self.seed = random.getrandbits(32)
 
 
    def setItem(self,key,val,ttl=False):
        ''' Store an item in a specific area
        '''
        
        if self.disabled:
            return  
        
        if not ttl:
            # Use the default TTL
            ttl = self.config['defaultTTL']
        
        keyh = self.genKeyHash(key)
        now = int(time.time())
        self.storage[keyh] = { "Value": val, "SetAt": now, "TTL" : ttl, "Origkey" : key, "Last-Use": now}
 
 
    def getItem(self, key):
        ''' Retrieve an item. Will check each storage area for an entry with the specified key
        '''
        
        if self.disabled:
            return  False        
        
        keyh = self.genKeyHash(key)
        
        if keyh not in self.storage:
            return False
        
        # Check whether the ttl has expired
        if (int(time.time()) - self.storage[keyh]["TTL"]) > self.storage[keyh]["SetAt"]:
            # TTL has expired. Invalidate the object and return false
            # only if we're not currently offline though.
            if not self.config['amOffline']:
                self.invalidate(key)
                return False
        
        self.storage[keyh]["Last-Use"] = int(time.time())
        return self.storage[keyh]["Value"]
 
 
    def invalidate(self,key):
        ''' Invalidate an item within the cache
        '''
        key = self.genKeyHash(key)
        
        if key not in self.storage:
            return
        
        del self.storage[key]
    
    
    def genKeyHash(self,key):
        ''' Convert the supplied key into a hash
        
            We combine it with a seed to help make hash collision attempts harder on public facing infrastructure.
            Probably overkill, but better to have it and not need it
            
        '''
        return hashlib.sha256("%s%s" % (self.seed,key)).hexdigest()
    
    
    def __getitem__(self,val):
        ''' Magic method so that the temporary store can be accessed as if this class were a dict
        '''
        return self.getItem(val)
    
    def __setitem__(self,key,val):
        ''' Magic method so that the temporary store can be accessed as if this class were a dict
        '''
        return self.setItem(key,val)
    
            
    def flush(self):
        ''' Flush the temporary storage area and response cache
        
        Restore anything that's been 'pre' cached
        '''
        del self.storage
        self.storage = {}
        
        # Generate a new seed so it's harder to predict hashes
        self.seed = random.getrandbits(32)
        self.lastpurge = int(time.time())
        
        # Write the updated (and now empty) cache to disk so we don't end up reusing later
        self.writeToDiskCache()
 
        
    def selfpurge(self):
        ''' Sledgehammer for a nail. Periodically purge the permanent storage to make
        sure we don't absorb too much memory
        '''
        
        if 'doSelfPurge' in self.config and not self.config['doSelfPurge']:
            return
        
        if (int(time.time()) - self.config['defaultTTL']) > self.lastpurge:
            self.flush()
 
 
    def LRU(self):
        ''' Run a Least Recently Used flush on the cache storage
        '''
        
        items = {}
        
        # Iterate over items in the cache, pulling out the cache key and when the item was last used
        for keyh in self.storage:
            items[keyh] = self.storage[keyh]['Last-Use']
            
        # Now we want to sort our dict from smallest timestamp (i.e. least recently used) to highest
        ordered = sorted(items.items(), key=lambda x: x[1])
 
        # That gives us a list of tuples (key,timestamp). We want to clear the first 25% (ish)
        numitems = len(items)
        toclear = math.ceil(numitems * self.config['LRUTarget'])
        x = 0
        
        while x < toclear:
            entry = ordered[x][0]
            del self.storage[entry]           
            x = x + 1
 
        return x
 
 
 
    def writeToDiskCache(self):
        ''' Write a copy of the current cache out to disk
        '''
        
        if "DiskCache" in self.config and self.config['DiskCache']:
            p = {
                    'storage' : self.storage,
                    'lastpurge' : self.lastpurge,
                    'seed' : self.seed
                }
            
            cachejson = json.dumps(p)
            f = open(self.config['DiskCache'],'w')
            f.write(cachejson)
            f.close()
 
            
    def loadFromDiskCache(self):
        ''' Load previously cached values from disk (if present)
        '''
        
        if "DiskCache" in self.config and self.config['DiskCache'] and os.path.isfile(self.config['DiskCache']):
            f = open(self.config['DiskCache'],'r')
            cache = json.load(f)
            f.close()
            self.storage = cache['storage']
            self.lastpurge = cache['lastpurge']
            self.seed = cache['seed']
            
 
 
    def setConfig(self,var,value):
        ''' Set an internal config option
        '''
        self.config[var] = value
 
 
 
 
 
def getJSON(url):
    #print "Fetching %s" % (url,)
    
    # Check whether we have it in cache
    resp = CACHE.getItem(url)
    if resp:
        return json.loads(resp)
    
    
    if CACHE.config['amOffline']:
        print "Item not in cache and we're offline"
        return False
    
    request = urllib2.Request(url)
    
    if AUTH:
        request.add_header("Authorization","Basic %s" % (AUTH,))
    
    if ADDITIONAL_HEADERS:
        for header in ADDITIONAL_HEADERS:
            request.add_header(header['name'],header['value'])
    
    
    response = urllib2.urlopen(request)
    jsonstr = response.read()
    #print jsonstr
    
    CACHE.setItem(url,jsonstr)
    
    return json.loads(jsonstr)
 
 
 
def doTestRequest():
    ''' Place a test request to work out whether we've got connectivity or not 
    '''
    url = "%s/manifest.json" % (BASEDIR,)
    
    request = urllib2.Request(url)
    
    if AUTH:
        request.add_header("Authorization","Basic %s" % (AUTH,))
    
    if ADDITIONAL_HEADERS:
        for header in ADDITIONAL_HEADERS:
            request.add_header(header['name'],header['value'])
    
    try:
        response = urllib2.urlopen(request,timeout=5)
        jsonstr = response.read()
        
        # Check we actually got json back
        # Basically checking for captive portals. Though shouldn't be an issue given we're using HTTPS
        # but also helps if there's an issue with the server
 
        s = json.loads(jsonstr)
        return True
    
    except:
        return False
 
 
 
 
 
# See https://snippets.bentasker.co.uk/page-1705192300-Make-ASCII-Table-Python.html
def make_table(columns, data):
    """Create an ASCII table and return it as a string.
 
    Pass a list of strings to use as columns in the table and a list of
    dicts. The strings in 'columns' will be used as the keys to the dicts in
    'data.'
 
    """
    # Calculate how wide each cell needs to be
    cell_widths = {}
    for c in columns:
        lens = []
        values = [lens.append(len(str(d.get(c, "")))) for d in data]
        lens.append(len(c))
        lens.sort()
        cell_widths[c] = max(lens)
 
    # Used for formatting rows of data
    row_template = "|" + " {} |" * len(columns)
 
    # CONSTRUCT THE TABLE
 
    # The top row with the column titles
    justified_column_heads = [c.ljust(cell_widths[c]) for c in columns]
    header = row_template.format(*justified_column_heads)
    # The second row contains separators
    sep = "|" + "-" * (len(header) - 2) + "|"
    end = "-" * len(header)
    # Rows of data
    rows = []
 
    for d in data:
        fields = [str(d.get(c, "")).ljust(cell_widths[c]) for c in columns]
        row = row_template.format(*fields)
        rows.append(row)
    rows.append(end)
    return "\n".join([header, sep] + rows)
 
 
 
def listprojects():
    """ List the projects available
    """
    
    plist = getJSON("%s/manifest.json" % (BASEDIR,))
    
    if not plist:
        print "Error"
        return
    
    print """Projects:
            
            """
    
    
    if "items" not in plist:
        print "No projects returned"
        return False
    
    Cols=['Key','Name']
    rows=[]
    for project in plist["items"]:
        entry = {
            'Key' : project['Key'],
            'Name' : project['Name'],
            'Description' : project['Description']
            }
        rows.append(entry)
        if project['Key'] not in PROJURLS:
            PROJURLS[project['Key']] = project['href']
    
    print make_table(Cols,rows)
    
 
 
def stripTags(str):
    ''' Strip out HTML tags and return just the plain text
    '''
    return re.sub('<[^<]+?>', '', str)
 
 
def buildIssueTable(issues,isstype=False,issstatus=False, titleContains=False):
    ''' Print a table of issues
    
        Args:
        
            isstype - False to disable filter. Otherwise list containing issuetypes to display
            issstatus - False to disable filter. Otherwise list containing issuetypes to display
    
    
    '''
    Cols = ['Key','Type','Priority','Summary','Status','Resolution','Created','Assigned To']
    rows = []
    
       
    if isstype or issstatus:
        print "Filtering by Issue type = %s and Status = %s and Title contains '%s'\n\n" % (isstype,issstatus,titleContains)
        
 
    # Prevent case-sensitivity issues with filters
    if isstype:
        isstype = [e.lower() for e in isstype]
 
    if issstatus:
        issstatus = [e.lower() for e in issstatus]
 
    if titleContains:
        titleContains = titleContains.lower()
        
    for issue in issues:
        
        # Check whether we're filtering by issue type
        if isstype and issue['IssueType'].lower() not in isstype:
            continue
        
        if issstatus and issue['Status'].lower() not in issstatus:
            continue
        
        if titleContains and titleContains not in issue['Name'].lower():
            continue
        
        entry = {
            'Key' : issue['Key'],
            'Type' : issue['IssueType'],
            'Priority' : issue['Priority'],
            'Summary' : issue['Name'],
            'Status' : issue['Status'],
            'Resolution' : issue['Resolution'],
            'Created' : time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(issue['Created'])),
            'Assigned To' : issue['assigneee']
        }
        rows.append(entry)
        
        if issue['Key'] not in ISSUEURLS:
            ISSUEURLS[issue['Key']] = issue['href']
        
    
    return make_table(Cols,rows)
    
 
def fetchProject(proj):
    ''' Fetch the JSON for a project, and return it
    '''
    if proj not in PROJURLS:
        url = "%s/browse/%s.json" % (BASEDIR,proj)
    else:
        url = PROJURLS[proj]
 
    plist = getJSON(url)
    if not plist:
        print "Error"
        return
    
    # Do some cachey-cachey
    if proj not in PROJDATA:
        PROJDATA[proj] = {}
    
    
    # Cache version URLs. We can't trivially calculate these
    #
    # Could be moved into the memcache, but it's not trivial to do, so leaving as a TODO for now
    if len(plist['versions']) > 0 and "versions" not in PROJDATA[proj]:
        PROJDATA[proj]['versions'] = {}
        for ver in plist['versions']:
            PROJDATA[proj]['versions'][ver['Name']] = ver['href']
    
    # Cache component URLs. We can't trivially calculate those either
    if len(plist['components']) > 0 and "components" not in PROJDATA[proj]:
        PROJDATA[proj]['components'] = {}
        for comp in plist['components']:
            PROJDATA[proj]['components'][comp['Name']] = comp['href']
        
    
    
    
    return plist
 
 
 
def listProject(proj,isstype=False,issstatus=False,titleContains=False):
    """ Print details about the specified project
    """
 
    plist = fetchProject(proj)
    if not plist:
        print "Error"
        return
    
    CACHE.setItem('Navi-curproject',proj, ttl=99999999)
    
    print "%s: %s\n\n%s\n\n" % (plist['Key'],plist['Name'],stripTags(plist['Description']))
    
    print buildIssueTable(plist['issues'],isstype,issstatus,titleContains)
 
 
 
def listProjectComponent(proj,comp,isstype=False,issstatus=False,titleContains=False):
    ''' List issues for a specific project component
    
        Args:
        
        proj - the project key (E.g. GPXIN)
        comp - The component name (e.g. Experimental Features)
    
    
    '''
    
    if proj not in PROJDATA or "components" not in PROJDATA[proj] or comp not in PROJDATA[proj]["components"]:
        # We need to fetch the project homepage first so that we can find out the version URL 
        fetchProject(proj)
 
    if proj not in PROJDATA:
        print "Error"
        return
        
    if comp not in PROJDATA[proj]["components"]:
        print "Invalid Component"
        return
    
    # Otherwise, fetch the page
    plist = getJSON(PROJDATA[proj]["components"][comp])
    
    if not plist:
        print "Error"
        return
    
    CACHE.setItem('Navi-curproject',proj, ttl=99999999)
    
    print "%s: Component %s\n\n%s" % (proj,plist['Name'],plist['Description'])
    print "--------------"
    print "Issues"
    print "--------------"
    print buildIssueTable(plist['issues'],isstype,issstatus,titleContains)
 
 
 
def listProjectComps(proj):
    ''' Generate a list of all components for a project
    '''
    plist = fetchProject(proj)
    if "components" not in plist or len(plist['components']) < 1:
        print "No components configured for project %s" % (proj,)
        return
    
    CACHE.setItem('Navi-curproject',proj, ttl=99999999)
    # Otherwise iterate over and build a table
    Cols = ['Name','Description']
    Rows = []
    
    for ver in plist['components']:
        p = {
                'Name' : ver['Name'],
                'Description' : ver['Description']
            }
 
        
        Rows.append(p)
    
    print make_table(Cols,Rows)    
 
 
def listProjectVers(proj):
    ''' Generate a list of all versions for a project
    '''
    
    plist = fetchProject(proj)
    if "versions" not in plist or len(plist['versions']) < 1:
        print "No versions configured for project %s" % (proj,)
        return
    
    CACHE.setItem('Navi-curproject',proj, ttl=99999999)
    # Otherwise iterate over and build a table
    Cols = ['Name','State','Release Date']
    Rows = []
    
    for ver in plist['versions']:
        p = {
                'Name' : ver['Name'],
                'State' : ver['State'],
                'Release Date' : ''           
            }
        
        if ver['ReleaseDate']:
            p['Release Date'] = time.strftime('%Y-%m-%d', time.localtime(ver['ReleaseDate']))
        
        Rows.append(p)
    
    print make_table(Cols,Rows)
 
 
def listProjectVersion(proj,ver,isstype=False,issstatus=False,showKnown=True,showFixes=True,titleContains=False):
    ''' List issues for a specific project version
    
        Args:
        
        proj - the project key (E.g. GPXIN)
        ver - The version name (e.g. 1.02)
    
    
    '''
    
    if proj not in PROJDATA or "versions" not in PROJDATA[proj] or ver not in PROJDATA[proj]["versions"]:
        # We need to fetch the project homepage first so that we can find out the version URL 
        fetchProject(proj)
 
 
    if proj not in PROJDATA:
        print "Error"
        return
        
    if ver not in PROJDATA[proj]["versions"]:
        print "Invalid version"
        return
    
    # Otherwise, fetch the version page
    plist = getJSON(PROJDATA[proj]["versions"][ver])
    if not plist:
        print "Error"
        return
    
    CACHE.setItem('Navi-curproject',proj, ttl=99999999)
    
    print "%s: Version %s\n\nState:        %s" % (proj,plist['Name'],plist['State'])
    print "Time Est:     %s          Time Logged: %s\n"    % (plist['TimeEstimate'], plist['TimeLogged'])
    print "Release Date: %s\n" % (time.strftime('%Y-%m-%d', time.localtime(plist['ReleaseDate'])),)
    
    if showFixes:
        print "--------------"
        print "Fixed Issues"
        print "--------------"
        print buildIssueTable(plist['issues'],isstype,issstatus,titleContains)
    
 
    if showKnown:
        print "\n--------------"
        print "Known Issues"
        print "--------------"
        print buildIssueTable(plist['Knownissues'],isstype,issstatus,titleContains)    
    
 
 
def doBasicSearch(term):
    ''' Run a basic search for the provided term in title
    '''
    
    print "Search results for '%s'\n" % (term,)
    
    cachekey = 'Search-Basic-Search:%s' % (term,)
    cachedres = CACHE.getItem(cachekey)
    
    if cachedres:
          print buildIssueTable(cachedres)
          return
    
    url = "%s/sitemap.json" % (BASEDIR,)
    plist = getJSON(url)
    
    term = term.lower()
    matches = []
 
    for entry in plist['items']:
        if entry['Class'] != "Issue":
            continue
        
        if "Name" not in entry or not entry['Name']:
            # We want to exclude any moved entries
            continue
        
        if term in entry["Name"].lower():
            matches.append(entry)
            continue
 
    CACHE.setItem(cachekey,matches)
    print buildIssueTable(matches)
        
        
        
 
def secondsToTime(s):
    ''' Convert a count in seconds to hours and minutes
    '''
    
    if not s:
        return "0h 0m"
    
    mins, secs = divmod(int(s),60)
    hours, mins = divmod(mins,60)
    
    return "%dh %02dm" % (hours,mins)
 
 
def printIssue(isskey):
    ''' Print out details about an issue
    '''
    
 
    if isskey not in ISSUEURLS:
        url = "%s/browse/%s.json" % (BASEDIR,isskey)
    else:
        url = ISSUEURLS[isskey]
 
    issue = getJSON(url)
    if not issue:
        print "Error"
        return
 
    # Set the history
    lastview = CACHE.getItem('Navi-now')
    CACHE.setItem('Navi-last',lastview, ttl=99999999)
    CACHE.setItem('Navi-now',isskey, ttl=99999999)
    CACHE.setItem('Navi-curproject',isskey.split("-")[0], ttl=99999999)
 
    # Set the navigation globals based on the data
    if issue['Next']['Key']:
        CACHE.setItem('Navi-next',issue['Next']['Key'], ttl=99999999)
 
    if issue['Previous']['Key']:
        CACHE.setItem('Navi-prev',issue['Previous']['Key'],  ttl=99999999)
        
 
    print "%s: %s\n\n" % (issue['Key'],issue['Name'])
    print "------------------"
    print "Issue Details"
    print "------------------"
    print "Issue Type:  %s" % (issue['IssueType'])
    print "Priority:    %s          Status: %s\n\n" % (issue['Priority'], issue['Status'])
    
    if len(issue['components']) > 0:
        print "Components:  %s\n" % (','.join([x['Name'] for x in issue['components']]))
 
    print "Affects:     %s" % (','.join([x['Name'] for x in issue['AffectsVersions']]))
    print "Fixed in:    %s\n" % (','.join([x['Name'] for x in issue['FixVersions']]))
 
        
    print "Reporter:    %s          Assignee: %s" % (issue['Reporter'], issue['assigneee'])
    print "Resolution:  %s\n" % (issue['Resolution'],)
    print "Time Est:    %s          Time Logged: %s\n"    % (secondsToTime(issue['TimeEstimate']), secondsToTime(issue['TimeLogged']))
    print "Created:     %s" % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(issue['Created'])))
    print "Updated: %s\n\n" % (issue['LastModified'],)
    
    
    if len(issue['AffectsVersions']) > 0:
        print "Affects Versions: %s" % (','.join([x['Name'] for x in issue['AffectsVersions']]))
    
    
    if len(issue['FixVersions']) > 0:
        print "Fix Versions: %s" % (','.join([x['Name'] for x in issue['FixVersions']]))
            
    print "------------------"
    print "Issue Description"
    print "------------------\n"
    print "%s\n\n" % (issue['Description'],)
    
    # Print subtasks if there are any
    if len(issue['Relations']['SubTasks']) > 0:
            print "------------------"
            print "Subtasks"
            print "------------------\n"
            Cols = ['Key','Summary']
            rows = []
            for subtask in issue['Relations']['SubTasks']:
                entry = {
                        'Key' : subtask['Key'],
                        'Summary' : subtask['Name']
                    }
                rows.append(entry)
                if subtask['Key'] not in ISSUEURLS:
                    ISSUEURLS[subtask['Key']] = subtask['href']
            
            print make_table(Cols,rows)
    
    # Print internal relations (if any)
    Cols = ['Relation Type','Key','Summary','URL']
    relrows = []
    if len(issue['Relations']['LinkedIssues']) > 0:
            for relissue in issue['Relations']['LinkedIssues']:
                entry = {
                        'Relation Type' : relissue['RelType'],
                        'Key' : relissue['Key'],
                        'Summary' : relissue['Name'],
                        'URL' : '' # Will be used later
                    }
                relrows.append(entry)
                if relissue['Key'] not in ISSUEURLS:
                    ISSUEURLS[relissue['Key']] = relissue['href']
 
            # We don't print yet, as we want to merge in any external links
 
 
    if "RelatedLinks" in issue['Relations']:
            for link in issue['Relations']['RelatedLinks']:
                entry = {
                        'Relation Type' : '',
                        'Key' : '',
                        'Summary' : link['title'],
                        'URL' : link['href']
                    }
                relrows.append(entry)
    
    # Similarly, add any attachments if present
    if len(issue['attachments']) > 0:
            for attachment in issue['attachments']:
                entry = {
                        'Relation Type' : 'Attachment',
                        'Key' : '',
                        'Summary' : attachment['Name'],
                        'URL' : attachment['href']
                    }
                relrows.append(entry)
    
    
    if len(relrows) > 0:
            print "\n------------------"
            print "Relations"
            print "------------------\n"        
            print make_table(Cols,relrows)            
    
    # Finally, the big one, issue comments
    if issue['Comments']['count'] > 0:
        print "\n------------------"
        print "Comments"
        print "------------------\n"
        for comment in issue['Comments']['items']:
                print "----------------------------------------------------------------"
                print "%s\n%s" % (comment['Author'],time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(comment['Created'])))
                print "----------------------------------------------------------------"
                print "%s\n\n" % (comment['body'],)
 
 
# These were used for testing when building the methods above
#listprojects()
#listProject('BTFW',isstype=['Task'],issstatus=['Open'])
#listProject('BUGGER')
#printIssue('BUGGER-4')
#printIssue('DNSCHAT-2')
#printIssue('BUGGER-1')
#printIssue('MAILARCHIV-10')
#listProjectVersion('GPXIN','1.02')
#listProjectVersion('GPXIN','1.02',showFixes=False)
#listProjectVersion('GPXIN','1.02',showKnown=False)
#listProjectComponent('GPXIN','Experimental Features')
 
 
 
# CLI related functions begin
 
 
def runInteractive(display_prompt,echo_cmd=False):
    
        # Trigger the periodic auto flushes
        CACHE.selfpurge()
        
        try:
            readline.read_history_file(os.path.expanduser("~/.pbtcli.history"))
        except: 
            pass # Ignore FileNotFoundError, history file doesn't exist
 
        while True:
            try:
                command = raw_input(display_prompt)
 
            except EOFError:
                print("")
                break
 
            if command == "q":
                break
 
            elif command.startswith("#") or command == "" or command == " ":
                continue
 
            if echo_cmd:
                print "> " + command
 
            readline.write_history_file(os.path.expanduser("~/.pbtcli.history"))
            processCommand(command)
 
 
def processCommand(cmd):
    ''' Process the command syntax to work out which functions need to be called
    '''
    
    # First, check whether we've just been given an issue key 
    if re.match('[A-Z]+-[0-9]+',cmd):
        return printIssue(cmd)
 
 
    if re.match('[0-9]+',cmd):
        curproject = CACHE.getItem('Navi-curproject')
        if not curproject:
            print "Error: You cannot use Issue shortcut when not already viewing a project"
            return
        return printIssue("%s-%s" % (curproject,cmd))
        
 
 
    # We now need to build the command, but take into account that strings may be wrapped in quotes
    # these shoudld be treated as a single argument 
 
    # Split the command out to a list
    origcmdlist = cmd.split(' ')
    cmdlist = []
    NEEDQUOTE=False
    ENDSWITHQUOTE=False
    txtbuffer=''
    
    for entry in origcmdlist:
        if entry[0] == '"' or entry[0] == "'":
            # Starts with a quote.
            NEEDQUOTE=True
        
        if entry[-1] == '"' or entry[-1] == "'":
            ENDSWITHQUOTE=True
        
        if NEEDQUOTE and not ENDSWITHQUOTE:
            # Need a quote, just append it to the buffer for now
            txtbuffer += entry.replace("'","").replace('"',"")
            
            # Reinstate the original space
            txtbuffer += " "
    
        # Does it end with a quote?
        if ENDSWITHQUOTE:
            # It does. Append to the buffer (known bug here!)
            txtbuffer += entry.replace("'","").replace('"',"")
            NEEDQUOTE=False
            entry = txtbuffer
            txtbuffer = ''
            
        if not NEEDQUOTE:
            # Append the command segment
            cmdlist.append(entry.rstrip())
 
 
    if cmdlist[0] == 'n':
        # Navigation command to browse to the next issue       
        nextiss = CACHE.getItem('Navi-next')
        if not nextiss:
            print "No issue defined as next. View an issue first"
            return
        
        return printIssue(nextiss)
 
 
    if cmdlist[0] == 'b':
        # Navigation command to browse to the previous issue
        previss = CACHE.getItem('Navi-prev')
        if not previss:
            print "No issue defined as previous. View an issue first"
            return
        
        return printIssue(previss)
 
 
    if cmdlist[0] == 'p' or cmdlist[0] == 'back':
        # Navigation command to go back to the last issue viewed
        lastview = CACHE.getItem('Navi-last')
        if not lastview:
            print "You don't seem to have viewed an issue previously"
            return
        return printIssue(lastview)
 
            
    if cmdlist[0] == "projects":
        return listprojects()
 
    if cmdlist[0] == "project":
        return parseProjectDisplay(cmdlist)
 
 
    if cmdlist[0] == "projectver":
        return parseProjectVerDisplay(cmdlist)
    
 
    if cmdlist[0] == "projectcomp":
        return parseProjectCompDisplay(cmdlist)
 
    if cmdlist[0] == "cache":
        return parseCacheOptions(cmdlist)
 
    if cmdlist[0] == "issue":
        return printIssue(cmdlist[1])
    
    if cmdlist[0] == "set":
        return parseSetCmd(cmdlist)
    
    if cmdlist[0] == "search":
        return parseSearchCmd(cmdlist)    
    
 
 
def parseSetCmd(cmdlist):
    ''' Used to set various internals
    '''
 
 
    if cmdlist[1] == "defaultttl":
        CACHE.config['defaultTTL'] = int(cmdlist[2])
        print "Default TTL set to %s" % (cmdlist[2])
 
    if cmdlist[1] == "lrutarget":
        CACHE.config['LRUTarget'] = cmdlist[2]
        print "LRU Target set to %s%" % (cmdlist[2])
        
    if cmdlist[1] == "Offline":
        CACHE.config['amOffline'] = True
        print "Offline mode enabled"
        
    if cmdlist[1] == "Online":
        CACHE.config['amOffline'] = False
        print "Offline mode disabled"
        
    if cmdlist[1] == "curproject":
        CACHE.setItem('Navi-curproject',cmdlist[2], ttl=99999999)
 
 
def parseSearchCmd(cmdlist):
    ''' Used to provide basic search functionality
    '''
    
    
    return doBasicSearch(' '.join(cmdlist[1:]))
 
 
 
def parseCacheOptions(cmdlist):
    ''' Utility functions to aid troubleshooting if the cache causes any headaches
    '''
    
    if cmdlist[1] == "dump":
        # Dump the contents of the cache
        Cols = ['Key','Expires','Value']
        Rows = []
        
        for entry in CACHE.storage:
            p = {
                'Key' : CACHE.storage[entry]['Origkey'],
                'Expires' : time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(CACHE.storage[entry]['SetAt'] + CACHE.storage[entry]['TTL'])),
                'Value' : CACHE.storage[entry]['Value'],
                }
            Rows.append(p)
        print make_table(Cols,Rows)
 
 
    if cmdlist[1] == "fetch":
        if re.match('[A-Z]+-[0-9]+',cmdlist[2]):
            url = "%s/browse/%s.json" % (BASEDIR,cmdlist[2])
            getJSON(url)
            print "Written to cache"
            return
            
        # Fetch the specified URL 
        getJSON(cmdlist[2])
        print "Written to cache"
        return
 
    if cmdlist[1] == "LRU":
        count = CACHE.LRU()
        print "LRU Triggered. %s items removed" % (count,)
 
 
    if cmdlist[1] == "flush":
        # Flush the cache
        CACHE.flush()
        print "Cache flushed"
 
    if cmdlist[1] == "get":
        f = CACHE.getItem(cmdlist[2])
        if not f:
            print "Not in Cache"
            return
        
        print f
 
 
    if cmdlist[1] == "invalidate":
        CACHE.invalidate(cmdlist[2])
        print "Invalidated"
 
 
        
    if cmdlist[1] == "print":
        # Print a list of keys and when they expire
        Cols = ['Key','Expires']
        Rows = []
        
        for entry in CACHE.storage:
            p = {
                'Key' : CACHE.storage[entry]['Origkey'],
                'Expires' : time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(CACHE.storage[entry]['SetAt'] + CACHE.storage[entry]['TTL']))
                }
            Rows.append(p)
        print make_table(Cols,Rows)
 
 
 
                
 
 
def parseProjectCompDisplay(cmdlist):
    ''' Handle the command line syntax for anything beginning with the word projectver
    '''
 
    if cmdlist[2] == "listcomps":
        return listProjectComps(cmdlist[1])
    
    # Most simple case, simply list the project
    if len(cmdlist) == 3:
        return listProjectComponent(cmdlist[1],cmdlist[2])
 
    if cmdlist[3] == "isopen":
        return listProjectComponent(cmdlist[1], cmdlist[2], issstatus=["Open","In Progress"])
    
    if cmdlist[3] == "type":
        return listProjectComponent(cmdlist[1], cmdlist[2], isstype=cmdlist[4:])
    
    if cmdlist[3] == "status":
        return listProjectComponent(cmdlist[1], cmdlist[2], issstatus=cmdlist[4:])    
 
    if cmdlist[3] == "title":
        return listProjectComponent(cmdlist[1], cmdlist[2], titleContains=' '.join(cmdlist[4:]))
 
 
 
 
def parseProjectVerDisplay(cmdlist):
    ''' Handle the command line syntax for anything beginning with the word projectver
    '''
    
    if cmdlist[2] == "listvers":
        return listProjectVers(cmdlist[1]) 
    
    # Most simple case, simply list the project
    if len(cmdlist) == 3:
        return listProjectVersion(cmdlist[1],cmdlist[2])
 
    if cmdlist[3] == "knownissues":
        return listProjectVersion(cmdlist[1], cmdlist[2], showFixes=False)        
 
    if cmdlist[3] == "implements":
        return listProjectVersion(cmdlist[1], cmdlist[2], showKnown=False)
 
 
    if cmdlist[3] == "isopen":
        return listProjectVersion(cmdlist[1], cmdlist[2], issstatus=["Open","In Progress"])
    
    if cmdlist[3] == "type":
        return listProjectVersion(cmdlist[1], cmdlist[2], isstype=cmdlist[4:])
    
    if cmdlist[3] == "status":
        return listProjectVersion(cmdlist[1], cmdlist[2], issstatus=cmdlist[4:])    
 
    if cmdlist[3] == "title":
        return listProjectVersion(cmdlist[1], cmdlist[2], titleContains=' '.join(cmdlist[4:]))
 
   
 
 
 
 
def parseProjectDisplay(cmdlist):
    ''' Handle the command line syntax for anything beginning with the word project
    '''
    
    # Most simple case, simply list the project
    if len(cmdlist) == 2:
        return listProject(cmdlist[1])
        
 
    if cmdlist[2] == "isopen":
        return listProject(cmdlist[1], issstatus=["Open","In Progress"])
 
    if cmdlist[2] == "listcomps":
        return listProjectComps(cmdlist[1])
 
    if cmdlist[2] == "listvers":
        return listProjectVers(cmdlist[1])
    
    if cmdlist[2] == "type":
        return listProject(cmdlist[1], isstype=cmdlist[3:])
    
    if cmdlist[2] == "status":
        return listProject(cmdlist[1], issstatus=cmdlist[3:])    
        
    if cmdlist[2] == "title":
        return listProject(cmdlist[1], titleContains=' '.join(cmdlist[3:]))
    
    
    
 
CACHE = MemCache()
if DISKCACHE:
    CACHE.setConfig('DiskCache',DISKCACHE)
    CACHE.loadFromDiskCache()
 
if CACHE_TTL:
    CACHE.setConfig('defaultTTL',CACHE_TTL)
 
 
if not doTestRequest():
    print "Enabling Offline mode"
    CACHE.setConfig('amOffline',True)
 
if len(sys.argv) < 2:
        # Launch interactive mode
        
        # If commands are being redirected/piped, we don't want to display the prompt after each
        mode = os.fstat(sys.stdin.fileno()).st_mode
        if stat.S_ISFIFO(mode) or stat.S_ISREG(mode):
                display_prompt = ""
                echo_cmd = True
        else:
                display_prompt = "pbtcli> "
                echo_cmd = False
 
        runInteractive(display_prompt,echo_cmd)
 
        # Save the most recent view history
        lastview = CACHE.getItem('Navi-now')
        CACHE.setItem('Navi-last',lastview, ttl=99999999)
        CACHE.writeToDiskCache()
        sys.exit()
 
 
# Otherwise, pull the command from the commandline arguments
 
# Process them first to handle quoted strings
for i,val in enumerate(sys.argv):
    if " " in val:
        sys.argv[i] = "'%s'" % (val,)
    
    
command=" ".join(sys.argv[1:])
processCommand(command)
CACHE.writeToDiskCache()