-
Notifications
You must be signed in to change notification settings - Fork 24
/
git-bz
executable file
·2217 lines (1851 loc) · 78.8 KB
/
git-bz
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/python
#
# git-bz - git subcommand to integrate with bugzilla
#
# Copyright (C) 2008 Owen Taylor
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, If not, see
# http://www.gnu.org/licenses/.
#
# Patches for git-bz
# ==================
# Send to Owen Taylor <otaylor@fishsoup.net>
#
# Installation
# ============
# Copy or symlink somewhere in your path.
#
# Documentation
# =============
# See http://git.fishsoup.net/man/git-bz.html
# (generated from git-bz.txt in this directory.)
#
DEFAULT_CONFIG = \
"""
default-assigned-to =
default-op-sys = All
default-platform = All
default-version = unspecified
"""
CONFIG = {}
CONFIG['bugs.freedesktop.org'] = \
"""
https = true
default-priority = medium
"""
CONFIG['bugzilla.gnome.org'] = \
"""
https = true
default-priority = Normal
"""
CONFIG['bugzilla.mozilla.org'] = \
"""
https = true
default-priority = --
"""
################################################################################
import base64
import cPickle as pickle
from ConfigParser import RawConfigParser, NoOptionError
import httplib
from optparse import OptionParser
import os
try:
from sqlite3 import dbapi2 as sqlite
except ImportError:
from pysqlite2 import dbapi2 as sqlite
import re
from StringIO import StringIO
from subprocess import Popen, CalledProcessError, PIPE
import shutil
import sys
import tempfile
import time
import traceback
import xmlrpclib
import urlparse
from xml.etree.cElementTree import ElementTree
import base64
import platform
# Globals
# =======
# options dictionary from optparse
global_options = None
# Utility functions for git
# =========================
# Run a git command
# Non-keyword arguments are passed verbatim as command line arguments
# Keyword arguments are turned into command line options
# <name>=True => --<name>
# <name>='<str>' => --<name>=<str>
# Special keyword arguments:
# _quiet: Discard all output even if an error occurs
# _interactive: Don't capture stdout and stderr
# _input=<str>: Feed <str> to stdinin of the command
# _return_error: Return tuple of captured (stdout,stderr)
#
def git_run(command, *args, **kwargs):
to_run = ['git', command.replace("_", "-")]
interactive = False
quiet = False
input = None
return_stderr = False
for (k,v) in kwargs.iteritems():
if k == '_quiet':
quiet = True
elif k == '_interactive':
interactive = True
elif k == '_return_stderr':
return_stderr = True
elif k == '_input':
input = v
elif v is True:
if len(k) == 1:
to_run.append("-" + k)
else:
to_run.append("--" + k.replace("_", "-"))
else:
to_run.append("--" + k.replace("_", "-") + "=" + v)
to_run.extend(args)
process = Popen(to_run,
stdout=(None if interactive else PIPE),
stderr=(None if interactive else PIPE),
stdin=(PIPE if (input != None) else None))
output, error = process.communicate(input)
if process.returncode != 0:
if not quiet and not interactive:
# Using print here could result in Python adding a stray space
# before the next print
sys.stderr.write(error)
sys.stdout.write(output)
raise CalledProcessError(process.returncode, " ".join(to_run))
if interactive:
return None
elif return_stderr:
return output.strip(), error.strip()
else:
return output.strip()
# Wrapper to allow us to do git.<command>(...) instead of git_run()
class Git:
def __getattr__(self, command):
def f(*args, **kwargs):
return git_run(command, *args, **kwargs)
return f
git = Git()
class GitCommit:
def __init__(self, id, subject):
self.id = id
self.subject = subject
def rev_list_commits(*args, **kwargs):
kwargs_copy = dict(kwargs)
kwargs_copy['pretty'] = 'format:%s'
output = git.rev_list(*args, **kwargs_copy)
if output == "":
lines = []
else:
lines = output.split("\n")
if (len(lines) % 2 != 0):
raise RuntimeException("git rev-list didn't return an even number of lines")
result = []
for i in xrange(0, len(lines), 2):
m = re.match("commit\s+([A-Fa-f0-9]+)", lines[i])
if not m:
raise RuntimeException("Can't parse commit it '%s'", lines[i])
commit_id = m.group(1)
subject = lines[i + 1]
result.append(GitCommit(commit_id, subject))
return result
def get_commits(commit_or_revision_range):
# We take specifying a single revision to mean everything since that
# revision, while git-rev-list lists that revision and all ancestors
try:
# See if the argument identifies a single revision
rev = git.rev_parse(commit_or_revision_range, verify=True, _quiet=True)
commits = rev_list_commits(rev, max_count='1')
except CalledProcessError:
# If not, assume the argument is a range
commits = rev_list_commits(commit_or_revision_range)
if len(commits) == 0:
die("'%s' does not name any commits. Use HEAD to specify just the last commit" %
commit_or_revision_range)
return commits
def get_patch(commit):
# We could pass through -M as an option, but I think you basically always
# want it; showing renames as renames rather than removes/adds greatly
# improves readability.
return git.diff(commit.id + "^.." + commit.id, M=True, binary=True, unified="8") + "\n"
def get_body(commit):
return git.log(commit.id + "^.." + commit.id, pretty="format:%b")
def commit_is_merge(commit):
contents = git.cat_file("commit", commit.id)
parent_count = 0
for line in contents.split("\n"):
if line == "":
break
if line.startswith("parent "):
parent_count += 1
return parent_count > 1
# Global configuration variables
# ==============================
def get_browser():
try:
return git.config('bz.browser', get=True)
except CalledProcessError:
return 'firefox3'
def get_tracker():
if global_options.bugzilla != None:
return global_options.bugzilla
try:
return git.config('bz.default-tracker', get=True)
except CalledProcessError:
return 'bugzilla.gnome.org'
def get_default_product():
try:
return git.config('bz.default-product', get=True)
except CalledProcessError:
return None
def get_default_component():
try:
return git.config('bz.default-component', get=True)
except CalledProcessError:
return None
def get_add_url():
try:
return git.config('bz.add-url', get=True) == 'true'
except CalledProcessError:
return True
def get_add_url_method():
try:
return git.config('bz.add-url-method', get=True)
except CalledProcessError:
return "body-append:%u"
def get_firefox_profile_pref():
try:
return git.config('bz.firefox-profile', get=True)
except CalledProcessError:
return ""
# Per-tracker configuration variables
# ===================================
def resolve_host_alias(alias):
try:
return git.config('bz-tracker.' + alias + '.host', get=True)
except CalledProcessError:
return alias
def split_local_config(config_text):
result = {}
for line in config_text.split("\n"):
line = re.sub("#.*", "", line)
line = line.strip()
if line == "":
continue
m = re.match("([a-zA-Z0-9-]+)\s*=\s*(.*)", line)
if not m:
die("Bad config line '%s'" % line)
param = m.group(1)
value = m.group(2)
result[param] = value
return result
def get_git_config(name):
try:
name = name.replace(".", r"\.")
config_options = git.config(r'bz-tracker\.' + name + r'\..*', get_regexp=True)
except CalledProcessError:
return {}
result = {}
for line in config_options.split("\n"):
line = line.strip()
m = re.match("(\S+)\s+(.*)", line)
key = m.group(1)
value = m.group(2)
m = re.match(r'bz-tracker\.' + name + r'\.(.*)', key)
param = m.group(1)
result[param] = value
return result
# We only ever should be the config for one tracker in the course of a single run
cached_config = None
cached_config_tracker = None
def get_config(tracker):
global cached_config
global cached_config_tracker
if cached_config == None:
cached_config_tracker = tracker
host = resolve_host_alias(tracker)
cached_config = split_local_config(DEFAULT_CONFIG)
if host in CONFIG:
cached_config.update(split_local_config(CONFIG[host]))
cached_config.update(get_git_config(host))
if tracker != host:
cached_config.update(get_git_config(tracker))
assert cached_config_tracker == tracker
return cached_config
def tracker_uses_https(tracker):
config = get_config(tracker)
return 'https' in config and config['https'] == 'true'
def tracker_get_path(tracker):
config = get_config(tracker)
if 'path' in config:
return config['path']
return None
def tracker_get_auth_user(tracker):
config = get_config(tracker)
if 'path' in config:
return config['auth-user']
return None
def tracker_get_auth_password(tracker):
config = get_config(tracker)
if 'path' in config:
return config['auth-password']
return None
def get_default_fields(tracker):
config = get_config(tracker)
default_fields = {}
for key, value in config.iteritems():
if key.startswith("default-"):
param = key[8:].replace("-", "_")
default_fields[param] = value
return default_fields
# Utility functions for bugzilla
# ==============================
class BugParseError(Exception):
pass
# A BugHandle is the parsed form of a bug reference string; it
# uniquely identifies a bug on a server, though until we try
# to load it (and create a Bug) we don't know if it actually exists.
class BugHandle:
def __init__(self, host, path, https, id, auth_user=None, auth_password=None):
self.host = host
self.path = path
self.https = https
self.id = id
self.auth_user = auth_user
self.auth_password = auth_password
# ensure that the path to the bugzilla installation is an absolute path
# so that it will still work even if their config option specifies
# something like:
# path = bugzilla
# instead of the proper form:
# path = /bugzilla
if self.path and self.path[0] != '/':
self.path = '/' + self.path
def get_url(self):
return "%s://%s/show_bug.cgi?id=%s" % ("https" if self.https else "http",
self.host,
self.id)
def needs_auth(self):
return self.auth_user and self.auth_password
@staticmethod
def parse(bug_reference):
parseresult = urlparse.urlsplit (bug_reference)
if parseresult.scheme in ('http', 'https'):
# Catch http://www.gnome.org and the oddball http:relative/path and http:/path
if len(parseresult.path) == 0 or parseresult.path[0] != '/' or parseresult.hostname is None:
raise BugParseError("Invalid bug reference '%s'" % bug_reference)
user = parseresult.username
password = parseresult.password
# if the url did not specify http auth credentials in the form
# https://user:password@host.com, check to see whether the config file
# specifies any auth credentials for this host
if not user:
user = tracker_get_auth_user(parseresult.hostname)
if not password:
password = tracker_get_auth_password(parseresult.hostname)
# strip off everything after the last '/', so '/bugzilla/show_bug.cgi'
# will simply become '/bugzilla'
base_path = parseresult.path[:parseresult.path.rfind('/')]
m = re.match("id=([^&]+)", parseresult.query)
if m:
return BugHandle(host=parseresult.hostname,
path=base_path,
https=parseresult.scheme=="https",
id=m.group(1),
auth_user=user,
auth_password=password)
colon = bug_reference.find(":")
if colon > 0:
tracker = bug_reference[0:colon]
id = bug_reference[colon + 1:]
else:
tracker = get_tracker()
id = bug_reference
if not id.isdigit():
raise BugParseError("Invalid bug reference '%s'" % bug_reference)
host = resolve_host_alias(tracker)
https = tracker_uses_https(tracker)
path = tracker_get_path(tracker)
auth_user = tracker_get_auth_user(tracker)
auth_password = tracker_get_auth_password(tracker)
if not re.match(r"^.*\.[a-zA-Z]{2,}$", host):
raise BugParseError("'%s' doesn't look like a valid bugzilla host or alias" % host)
return BugHandle(host=host, path=path, https=https, id=id, auth_user=auth_user, auth_password=auth_password)
@staticmethod
def parse_or_die(str):
try:
return BugHandle.parse(str)
except BugParseError, e:
die(e.message)
def __hash__(self):
return hash((self.host, self.https, self.id))
def __eq__(self, other):
return ((self.host, self.https, self.id) ==
(other.host, other.https, other.id))
class CookieError(Exception):
pass
def do_get_cookies_from_sqlite(host, cookies_sqlite, browser, query, chromium_time):
result = {}
# We use a timeout of 0 since we expect to hit the browser holding
# the lock often and we need to fall back to making a copy without a delay
connection = sqlite.connect(cookies_sqlite, timeout=0)
try:
cursor = connection.cursor()
cursor.execute(query, { 'host': host })
now = time.time()
for name,value,path,expiry in cursor.fetchall():
# Excessive caution: toss out values that need to be quoted in a cookie header
expiry = float(expiry)
if chromium_time:
# Time stored in microseconds since epoch
expiry /= 1000000.
# Old chromium versions used to use the Unix epoch, but newer versions
# use the Windows epoch of January 1, 1601. Convert the latter to Unix epoch
if expiry > 11644473600:
expiry -= 11644473600
if float(expiry) > now and not re.search(r'[()<>@,;:\\"/\[\]?={} \t]', value):
result[name] = value
return result
# Let the user know what might be going wrong in the case of a cryptic database error.
except sqlite.DatabaseError:
print ("Python threw a database error. A likely cause is that your version of python "
"doesn't have a recent enough sqlite module to support this cookie database. "
"Try upgrading your python sqlite module.")
raise
finally:
connection.close()
# Firefox 3.5 keeps the cookies database permamently locked; as a workaround
# hack, we make a copy, read from that, then delete the copy. Of course,
# we may hit an inconsistent state of the database
def get_cookies_from_sqlite_with_copy(host, cookies_sqlite, browser, *args, **kwargs):
db_copy = cookies_sqlite + ".git-bz-temp"
shutil.copyfile(cookies_sqlite, db_copy)
try:
return do_get_cookies_from_sqlite(host, db_copy, browser, *args, **kwargs)
except sqlite.OperationalError, e:
raise CookieError("Cookie database was locked; temporary copy didn't work")
finally:
os.remove(db_copy)
def get_cookies_from_sqlite(host, cookies_sqlite, browser, query, chromium_time=False):
try:
result = do_get_cookies_from_sqlite(host, cookies_sqlite, browser, query,
chromium_time=chromium_time)
except sqlite.OperationalError, e:
if "database is locked" in str(e):
# Try making a temporary copy
result = get_cookies_from_sqlite_with_copy(host, cookies_sqlite, browser, query,
chromium_time=chromium_time)
else:
raise
if not ('Bugzilla_login' in result and 'Bugzilla_logincookie' in result):
raise CookieError("You don't appear to be signed into %s; please log in with %s" % (host,
browser))
return result
def get_cookies_from_sqlite_xulrunner(host, cookies_sqlite, name):
return get_cookies_from_sqlite(host, cookies_sqlite, name,
"select name,value,path,expiry from moz_cookies where host = :host")
def get_bugzilla_cookies_ff3(host):
if (platform.system() == "Darwin"):
profiles_dir = os.path.expanduser('~/Library/Application Support/Firefox')
else:
profiles_dir = os.path.expanduser('~/.mozilla/firefox')
profile_path = None
specific_profile = get_firefox_profile_pref()
cp = RawConfigParser()
cp.read(os.path.join(profiles_dir, "profiles.ini"))
for section in cp.sections():
if not cp.has_option(section, "Path"):
continue
# If we're looking for a specific profile, just check for that
if specific_profile != "":
if cp.has_option(section, "Name") and cp.get(section, "Name").strip() == specific_profile:
profile_path = os.path.join(profiles_dir, cp.get(section, "Path").strip())
# Otherwise use the profile tagged as default
elif (not profile_path or
(cp.has_option(section, "Default") and cp.get(section, "Default").strip() == "1")):
profile_path = os.path.join(profiles_dir, cp.get(section, "Path").strip())
if not profile_path:
raise CookieError("Cannot find default Firefox profile")
cookies_sqlite = os.path.join(profile_path, "cookies.sqlite")
if not os.path.exists(cookies_sqlite):
raise CookieError("%s doesn't exist." % cookies_sqlite)
return get_cookies_from_sqlite_xulrunner(host, cookies_sqlite, "Firefox")
def get_bugzilla_cookies_epy(host):
# epiphany-webkit migrated the cookie db to a different location, but the
# format is the same
profile_dir = os.path.expanduser('~/.gnome2/epiphany')
cookies_sqlite = os.path.join(profile_dir, "cookies.sqlite")
if not os.path.exists(cookies_sqlite):
# try the old location
cookies_sqlite = os.path.join(profile_dir, "mozilla/epiphany/cookies.sqlite")
if not os.path.exists(cookies_sqlite):
raise CookieError("%s doesn't exist" % cookies_sqlite)
return get_cookies_from_sqlite_xulrunner(host, cookies_sqlite, "Epiphany")
# Shared for Chromium and Google Chrome
def get_bugzilla_cookies_chr(host, browser, config_dir):
config_dir = os.path.expanduser(config_dir)
cookies_sqlite = os.path.join(config_dir, "Cookies")
if not os.path.exists(cookies_sqlite):
raise CookieError("%s doesn't exist" % cookies_sqlite)
return get_cookies_from_sqlite(host, cookies_sqlite, browser,
"select name,value,path,expires_utc from cookies where host_key = :host",
chromium_time=True)
def get_bugzilla_cookies_chromium(host):
return get_bugzilla_cookies_chr(host,
"Chromium",
'~/.config/chromium/Default')
def get_bugzilla_cookies_google_chrome(host):
return get_bugzilla_cookies_chr(host,
"Google Chrome",
'~/.config/google-chrome/Default')
browsers = { 'firefox3' : get_bugzilla_cookies_ff3,
'epiphany' : get_bugzilla_cookies_epy,
'chromium' : get_bugzilla_cookies_chromium,
'google-chrome': get_bugzilla_cookies_google_chrome }
def browser_list():
return ", ".join(sorted(browsers.keys()))
def get_bugzilla_cookies(host):
browser = get_browser()
if browser in browsers:
do_get_cookies = browsers[browser]
else:
die('Unsupported browser %s (we only support %s)' % (browser, browser_list()))
try:
return do_get_cookies(host)
except CookieError, e:
die("""Error getting login cookie from browser:
%s
Configured browser: %s (change with 'git config --global bz.browser <value>')
Possible browsers: %s""" %
(str(e), browser, browser_list()))
# Based on http://code.activestate.com/recipes/146306/ - Wade Leftwich
def encode_multipart_formdata(fields, files=None):
"""
fields is a dictionary of { name : value } for regular form fields. if value is a list,
one form field is added for each item in the list
files is a dictionary of { name : ( filename, content_type, value) } for data to be uploaded as files
Return (content_type, body) ready for httplib.HTTPContent instance
"""
BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
CRLF = '\r\n'
L = []
for key in sorted(fields.keys()):
value = fields[key]
if isinstance(value, list):
for v in value:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(v)
else:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(value)
if files:
for key in sorted(files.keys()):
(filename, content_type, value) = files[key]
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
L.append('Content-Type: %s' % content_type)
L.append('')
L.append(value)
L.append('--' + BOUNDARY + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body
# Cache of constant-responses per bugzilla server
# ===============================================
CACHE_EXPIRY_TIME = 3600 * 24 # one day
class Cache(object):
def __init__(self):
self.cfp = None
def __ensure(self, host):
if self.cfp == None:
self.cfp = RawConfigParser()
self.cfp.read(os.path.expanduser("~/.git-bz-cache"))
if self.cfp.has_section(host):
if time.time() > self.cfp.getfloat(host, "expires"):
self.cfp.remove_section(host)
if not self.cfp.has_section(host):
self.cfp.add_section(host)
self.cfp.set(host, "expires", time.time() + CACHE_EXPIRY_TIME)
def get(self, host, key):
self.__ensure(host)
try:
return pickle.loads(self.cfp.get(host, key))
except NoOptionError:
raise IndexError()
def set(self, host, key, value):
self.__ensure(host)
self.cfp.set(host, key, pickle.dumps(value))
f = open(os.path.expanduser("~/.git-bz-cache"), "w")
self.cfp.write(f)
f.close()
cache = Cache()
# General Utility Functions
# =========================
def make_filename(description):
filename = re.sub(r"\s+", "-", description)
filename = re.sub(r"[^A-Za-z0-9-]+", "", filename)
filename = filename[0:50]
return filename
def edit_file(filename):
editor = None
if 'GIT_EDITOR' in os.environ:
editor = os.environ['GIT_EDITOR']
if editor == None:
try:
editor = git.config('core.editor', get=True)
except CalledProcessError:
pass
if editor == None and 'EDITOR' in os.environ:
editor = os.environ['EDITOR']
if editor == None:
editor = "vi"
process = Popen(editor + " " + filename, shell=True)
process.wait()
if process.returncode != 0:
die("Editor exited with non-zero return code")
def edit_template(template):
# Prompts the user to edit the text 'template' and returns list of
# lines with comments stripped
handle, filename = tempfile.mkstemp(".txt", "git-bz-")
f = os.fdopen(handle, "w")
f.write(template)
f.close()
edit_file(filename)
f = open(filename, "r")
lines = filter(lambda x: not x.startswith("#"), f.readlines())
f.close
return lines
def split_subject_body(lines):
# Splits the first line (subject) from the subsequent lines (body)
i = 0
subject = ""
while i < len(lines):
subject = lines[i].strip()
if subject != "":
break
i += 1
return subject, "".join(lines[i + 1:]).strip()
def _shortest_unique_abbreviation(full, l):
for i in xrange(1, len(full) + 1):
abbrev = full[0:i]
if not any((x != full and x.startswith(abbrev) for x in l)):
return abbrev
# Duplicate items or one item is a prefix of another
raise ValueError("%s has no unique abbreviation in %s" % (full, l))
def _abbreviation_item_help(full, l):
abbrev = _shortest_unique_abbreviation(full, l)
return '[%s]%s' % (abbrev, full[len(abbrev):])
# Return '[a]pple, [pe]ar, [po]tato'
def abbreviation_help_string(l):
return ", ".join((_abbreviation_item_help(full, l) for full in l))
# Find the unique element in l that starts with abbrev
def expand_abbreviation(abbrev, l):
for full in l:
if full.startswith(abbrev) and len(abbrev) >= len(_shortest_unique_abbreviation(full, l)):
return full
raise ValueError("No unique abbreviation expansion")
def prompt(message):
while True:
# Using print here could result in Python adding a stray space
# before the next print
sys.stdout.write(message + " [yn] ")
line = sys.stdin.readline().strip()
if line == 'y' or line == 'Y':
return True
elif line == 'n' or line == 'N':
return False
def die(message):
print >>sys.stderr, message
sys.exit(1)
def http_auth_header(user, password):
return 'Basic ' + base64.encodestring("%s:%s" % (user, password)).strip()
# Classes for bug handling
# ========================
class BugPatch(object):
def __init__(self, attach_id):
self.attach_id = attach_id
class NoXmlRpcError(Exception):
pass
connections = {}
def get_connection(host, https):
identifier = (host, https)
if not identifier in connections:
if https:
connection = httplib.HTTPSConnection(host, 443)
else:
connection = httplib.HTTPConnection(host, 80)
connections[identifier] = connection
return connections[identifier]
def kill_connection(host, https):
identifier = (host, https)
if identifier in connections:
del connections[identifier]
class BugServer(object):
def __init__(self, host, path, https, auth_user=None, auth_password=None):
self.host = host
self.path = path
self.https = https
self.auth_user = auth_user
self.auth_password = auth_password
self.cookies = get_bugzilla_cookies(host)
self._xmlrpc_proxy = None
def get_cookie_string(self):
return ("Bugzilla_login=%s; Bugzilla_logincookie=%s" %
(self.cookies['Bugzilla_login'], self.cookies['Bugzilla_logincookie']))
def send_request(self, method, url, data=None, headers={}):
headers = dict(headers)
headers['Cookie'] = self.get_cookie_string()
headers['User-Agent'] = "git-bz"
if self.auth_user and self.auth_password:
headers['Authorization'] = http_auth_header(self.auth_user, self.auth_password)
if self.path:
url = self.path + url
seen_urls = []
retries = 0
connection = get_connection(self.host, self.https)
while True:
# BMO seems to generate some "bad status line" exception intermittently.
try:
connection.request(method, url, data, headers)
response = connection.getresponse()
except httplib.BadStatusLine:
retries = retries + 1
print "Got bad status line - retrying..."
connection.close()
kill_connection(self.host, self.https)
time.sleep(2)
connection = get_connection(self.host, self.https)
continue
retries = 0
seen_urls.append(url)
# Redirect status codes:
#
# 301 (Moved Permanently): Redo with the new URL,
# save the new location.
# 303 (See Other): Redo with the method changed to GET/HEAD.
# 307 (Temporary Redirect): Redo with the new URL, don't
# save the new location.
#
# [ For 301/307, you are supposed to ask the user if the
# method isn't GET/HEAD, but we're automating anyways... ]
#
# 302 (Found): The confusing one, and the one that
# Bugzilla uses, both to redirect to http to https and to
# redirect attachment.cgi&action=view to a different base URL
# for security. Specified like 307, traditionally treated as 301.
#
# See http://en.wikipedia.org/wiki/HTTP_302
if response.status in (301, 302, 303, 307):
new_url = response.getheader("location")
if new_url is None:
die("Redirect received without a location to redirect to")
if new_url in seen_urls or len(seen_urls) >= 10:
die("Circular redirect or too many redirects")
old_split = urlparse.urlsplit(url)
new_split = urlparse.urlsplit(new_url)
new_https = new_split.scheme == 'https'
if new_split.hostname != self.host or new_https != self.https:
connection = get_connection(new_split.hostname, new_https != self.https)
# This is a bit of a hack to avoid keeping on redirecting for every
# request. If the server redirected show_bug.cgi we assume it's
# really saying "hey, the bugzilla instance is really over here".
#
# We can't do this for old.split.path == new_split.path because of
# attachment.cgi, though we alternatively could just exclude
# attachment.cgi here.
if (response.status in (301, 302) and
method == 'GET' and
old_split.path == '/show_bug.cgi' and new_split.path == '/show_bug.cgi'):
self.host = new_split.hostname
self.https = new_https
# We can't treat 302 like 303 because of the use of 302 for http
# to https, though the hack above will hopefully get us on https
# before we try to POST.
if response.status == 303:
if method not in ('GET', 'HEAD'):
method = 'GET'
# Get the relative component of the new URL
url = urlparse.urlunsplit((None, None, new_split.path, new_split.query, new_split.fragment))
else:
return response
def send_post(self, url, fields, files=None):
content_type, body = encode_multipart_formdata(fields, files)
return self.send_request("POST", url, data=body, headers={ 'Content-Type': content_type })
def get_xmlrpc_proxy(self):
if self._xmlrpc_proxy is None:
uri = "%s://%s/xmlrpc.cgi" % ("https" if self.https else "http",
self.host)
if self.https:
transport = SafeBugTransport(self)
else:
transport = BugTransport(self)
self._xmlrpc_proxy = xmlrpclib.ServerProxy(uri, transport)
return self._xmlrpc_proxy
# Query the server for the legal values of the given field; returns an
# array, or None if the query failed
def _legal_values(self, field):
try:
response = self.get_xmlrpc_proxy().Bug.legal_values({ 'field': field })
cache.set(self.host, 'legal_' + field, response['values'])
return response['values']
except xmlrpclib.Fault, e:
if e.faultCode == -32000: # https://bugzilla.mozilla.org/show_bug.cgi?id=513511
return None
raise
except xmlrpclib.ProtocolError, e:
if e.errcode == 500: # older bugzilla versions die this way
return None
elif e.errcode == 404: # really old bugzilla, no XML-RPC
return None
raise
def legal_values(self, field):
try:
return cache.get(self.host, 'legal_' + field)
except IndexError:
values = self._legal_values(field)
cache.set(self.host, 'legal_' + field, values)
return values