forked from scala/scala
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostreview.py
2540 lines (2104 loc) · 90.4 KB
/
postreview.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
#!/usr/bin/env python
import cookielib
import difflib
import getpass
import marshal
import mimetools
import ntpath
import os
import re
import socket
import stat
import subprocess
import sys
import tempfile
import urllib
import urllib2
from optparse import OptionParser
from tempfile import mkstemp
from urlparse import urljoin, urlparse
try:
from hashlib import md5
except ImportError:
# Support Python versions before 2.5.
from md5 import md5
try:
import json
except ImportError:
import simplejson as json
# This specific import is necessary to handle the paths for
# cygwin enabled machines.
if (sys.platform.startswith('win')
or sys.platform.startswith('cygwin')):
import ntpath as cpath
else:
import posixpath as cpath
###
# Default configuration -- user-settable variables follow.
###
# The following settings usually aren't needed, but if your Review
# Board crew has specific preferences and doesn't want to express
# them with command line switches, set them here and you're done.
# In particular, setting the REVIEWBOARD_URL variable will allow
# you to make it easy for people to submit reviews regardless of
# their SCM setup.
#
# Note that in order for this script to work with a reviewboard site
# that uses local paths to access a repository, the 'Mirror path'
# in the repository setup page must be set to the remote URL of the
# repository.
#
# Reviewboard URL.
#
# Set this if you wish to hard-code a default server to always use.
# It's generally recommended to set this using your SCM repository
# (for those that support it -- currently only SVN, Git, and Perforce).
#
# For example, on SVN:
# $ svn propset reviewboard:url http://reviewboard.example.com .
#
# Or with Git:
# $ git config reviewboard.url http://reviewboard.example.com
#
# On Perforce servers version 2008.1 and above:
# $ p4 counter reviewboard.url http://reviewboard.example.com
#
# Older Perforce servers only allow numerical counters, so embedding
# the url in the counter name is also supported:
# $ p4 counter reviewboard.url.http:\|\|reviewboard.example.com 1
#
# Note that slashes are not allowed in Perforce counter names, so replace them
# with pipe characters (they are a safe substitute as they are not used
# unencoded in URLs). You may need to escape them when issuing the p4 counter
# command as above.
#
# If this is not possible or desired, setting the value here will let
# you get started quickly.
#
# For all other repositories, a .reviewboardrc file present at the top of
# the checkout will also work. For example:
#
# $ cat .reviewboardrc
# REVIEWBOARD_URL = "http://reviewboard.example.com"
#
REVIEWBOARD_URL = None
# Default submission arguments. These are all optional; run this
# script with --help for descriptions of each argument.
TARGET_GROUPS = None
TARGET_PEOPLE = None
SUBMIT_AS = None
PUBLISH = False
OPEN_BROWSER = False
# Debugging. For development...
DEBUG = False
###
# End user-settable variables.
###
VERSION = "0.8"
user_config = None
tempfiles = []
options = None
class APIError(Exception):
pass
class RepositoryInfo:
"""
A representation of a source code repository.
"""
def __init__(self, path=None, base_path=None, supports_changesets=False,
supports_parent_diffs=False):
self.path = path
self.base_path = base_path
self.supports_changesets = supports_changesets
self.supports_parent_diffs = supports_parent_diffs
debug("repository info: %s" % self)
def __str__(self):
return "Path: %s, Base path: %s, Supports changesets: %s" % \
(self.path, self.base_path, self.supports_changesets)
def set_base_path(self, base_path):
if not base_path.startswith('/'):
base_path = '/' + base_path
debug("changing repository info base_path from %s to %s" % \
(self.base_path, base_path))
self.base_path = base_path
def find_server_repository_info(self, server):
"""
Try to find the repository from the list of repositories on the server.
For Subversion, this could be a repository with a different URL. For
all other clients, this is a noop.
"""
return self
class SvnRepositoryInfo(RepositoryInfo):
"""
A representation of a SVN source code repository. This version knows how to
find a matching repository on the server even if the URLs differ.
"""
def __init__(self, path, base_path, uuid, supports_parent_diffs=False):
RepositoryInfo.__init__(self, path, base_path,
supports_parent_diffs=supports_parent_diffs)
self.uuid = uuid
def find_server_repository_info(self, server):
"""
The point of this function is to find a repository on the server that
matches self, even if the paths aren't the same. (For example, if self
uses an 'http' path, but the server uses a 'file' path for the same
repository.) It does this by comparing repository UUIDs. If the
repositories use the same path, you'll get back self, otherwise you'll
get a different SvnRepositoryInfo object (with a different path).
"""
repositories = server.get_repositories()
for repository in repositories:
if repository['tool'] != 'Subversion':
continue
info = self._get_repository_info(server, repository)
if not info or self.uuid != info['uuid']:
continue
repos_base_path = info['url'][len(info['root_url']):]
relpath = self._get_relative_path(self.base_path, repos_base_path)
if relpath:
return SvnRepositoryInfo(info['url'], relpath, self.uuid)
# We didn't find a matching repository on the server. We'll just return
# self and hope for the best.
return self
def _get_repository_info(self, server, repository):
try:
return server.get_repository_info(repository['id'])
except APIError, e:
# If the server couldn't fetch the repository info, it will return
# code 210. Ignore those.
# Other more serious errors should still be raised, though.
rsp = e.args[0]
if rsp['err']['code'] == 210:
return None
raise e
def _get_relative_path(self, path, root):
pathdirs = self._split_on_slash(path)
rootdirs = self._split_on_slash(root)
# root is empty, so anything relative to that is itself
if len(rootdirs) == 0:
return path
# If one of the directories doesn't match, then path is not relative
# to root.
if rootdirs != pathdirs:
return None
# All the directories matched, so the relative path is whatever
# directories are left over. The base_path can't be empty, though, so
# if the paths are the same, return '/'
if len(pathdirs) == len(rootdirs):
return '/'
else:
return '/'.join(pathdirs[len(rootdirs):])
def _split_on_slash(self, path):
# Split on slashes, but ignore multiple slashes and throw away any
# trailing slashes.
split = re.split('/*', path)
if split[-1] == '':
split = split[0:-1]
return split
class ReviewBoardHTTPPasswordMgr(urllib2.HTTPPasswordMgr):
"""
Adds HTTP authentication support for URLs.
Python 2.4's password manager has a bug in http authentication when the
target server uses a non-standard port. This works around that bug on
Python 2.4 installs. This also allows post-review to prompt for passwords
in a consistent way.
See: http://bugs.python.org/issue974757
"""
def __init__(self, reviewboard_url):
self.passwd = {}
self.rb_url = reviewboard_url
self.rb_user = None
self.rb_pass = None
def find_user_password(self, realm, uri):
if uri.startswith(self.rb_url):
if self.rb_user is None or self.rb_pass is None:
print "==> HTTP Authentication Required"
print 'Enter username and password for "%s" at %s' % \
(realm, urlparse(uri)[1])
self.rb_user = raw_input('Username: ')
self.rb_pass = getpass.getpass('Password: ')
return self.rb_user, self.rb_pass
else:
# If this is an auth request for some other domain (since HTTP
# handlers are global), fall back to standard password management.
return urllib2.HTTPPasswordMgr.find_user_password(self, realm, uri)
class ReviewBoardServer(object):
"""
An instance of a Review Board server.
"""
def __init__(self, url, info, cookie_file):
self.url = url
if self.url[-1] != '/':
self.url += '/'
self._info = info
self._server_info = None
self.cookie_file = cookie_file
self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file)
# Set up the HTTP libraries to support all of the features we need.
cookie_handler = urllib2.HTTPCookieProcessor(self.cookie_jar)
password_mgr = ReviewBoardHTTPPasswordMgr(self.url)
auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(cookie_handler, auth_handler)
opener.addheaders = [('User-agent', 'post-review/' + VERSION)]
urllib2.install_opener(opener)
def login(self, force=False):
"""
Logs in to a Review Board server, prompting the user for login
information if needed.
"""
if not force and self.has_valid_cookie():
return
print "==> Review Board Login Required"
print "Enter username and password for Review Board at %s" % self.url
if options.username:
username = options.username
elif options.submit_as:
username = options.submit_as
else:
username = raw_input('Username: ')
if not options.password:
password = getpass.getpass('Password: ')
else:
password = options.password
debug('Logging in with username "%s"' % username)
try:
self.api_post('api/json/accounts/login/', {
'username': username,
'password': password,
})
except APIError, e:
rsp, = e.args
die("Unable to log in: %s (%s)" % (rsp["err"]["msg"],
rsp["err"]["code"]))
debug("Logged in.")
def has_valid_cookie(self):
"""
Load the user's cookie file and see if they have a valid
'rbsessionid' cookie for the current Review Board server. Returns
true if so and false otherwise.
"""
try:
parsed_url = urlparse(self.url)
host = parsed_url[1]
path = parsed_url[2] or '/'
# Cookie files don't store port numbers, unfortunately, so
# get rid of the port number if it's present.
host = host.split(":")[0]
debug("Looking for '%s %s' cookie in %s" % \
(host, path, self.cookie_file))
self.cookie_jar.load(self.cookie_file, ignore_expires=True)
try:
cookie = self.cookie_jar._cookies[host][path]['rbsessionid']
if not cookie.is_expired():
debug("Loaded valid cookie -- no login required")
return True
debug("Cookie file loaded, but cookie has expired")
except KeyError:
debug("Cookie file loaded, but no cookie for this server")
except IOError, error:
debug("Couldn't load cookie file: %s" % error)
return False
def new_review_request(self, changenum, submit_as=None):
"""
Creates a review request on a Review Board server, updating an
existing one if the changeset number already exists.
If submit_as is provided, the specified user name will be recorded as
the submitter of the review request (given that the logged in user has
the appropriate permissions).
"""
try:
debug("Attempting to create review request for %s" % changenum)
data = { 'repository_path': self.info.path }
if changenum:
data['changenum'] = changenum
if submit_as:
debug("Submitting the review request as %s" % submit_as)
data['submit_as'] = submit_as
rsp = self.api_post('api/json/reviewrequests/new/', data)
except APIError, e:
rsp, = e.args
if not options.diff_only:
if rsp['err']['code'] == 204: # Change number in use
debug("Review request already exists. Updating it...")
rsp = self.api_post(
'api/json/reviewrequests/%s/update_from_changenum/' %
rsp['review_request']['id'])
else:
raise e
debug("Review request created")
return rsp['review_request']
def set_review_request_field(self, review_request, field, value):
"""
Sets a field in a review request to the specified value.
"""
rid = review_request['id']
debug("Attempting to set field '%s' to '%s' for review request '%s'" %
(field, value, rid))
self.api_post('api/json/reviewrequests/%s/draft/set/' % rid, {
field: value,
})
def get_review_request(self, rid):
"""
Returns the review request with the specified ID.
"""
rsp = self.api_get('api/json/reviewrequests/%s/' % rid)
return rsp['review_request']
def get_repositories(self):
"""
Returns the list of repositories on this server.
"""
rsp = self.api_get('/api/json/repositories/')
return rsp['repositories']
def get_repository_info(self, rid):
"""
Returns detailed information about a specific repository.
"""
rsp = self.api_get('/api/json/repositories/%s/info/' % rid)
return rsp['info']
def save_draft(self, review_request):
"""
Saves a draft of a review request.
"""
self.api_post("api/json/reviewrequests/%s/draft/save/" %
review_request['id'])
debug("Review request draft saved")
def upload_diff(self, review_request, diff_content, parent_diff_content):
"""
Uploads a diff to a Review Board server.
"""
debug("Uploading diff, size: %d" % len(diff_content))
if parent_diff_content:
debug("Uploading parent diff, size: %d" % len(parent_diff_content))
fields = {}
files = {}
if self.info.base_path:
fields['basedir'] = self.info.base_path
files['path'] = {
'filename': 'diff',
'content': diff_content
}
if parent_diff_content:
files['parent_diff_path'] = {
'filename': 'parent_diff',
'content': parent_diff_content
}
self.api_post('api/json/reviewrequests/%s/diff/new/' %
review_request['id'], fields, files)
def publish(self, review_request):
"""
Publishes a review request.
"""
debug("Publishing")
self.api_post('api/json/reviewrequests/%s/publish/' %
review_request['id'])
def _get_server_info(self):
if not self._server_info:
self._server_info = self._info.find_server_repository_info(self)
return self._server_info
info = property(_get_server_info)
def process_json(self, data):
"""
Loads in a JSON file and returns the data if successful. On failure,
APIError is raised.
"""
rsp = json.loads(data)
if rsp['stat'] == 'fail':
raise APIError, rsp
return rsp
def http_get(self, path):
"""
Performs an HTTP GET on the specified path, storing any cookies that
were set.
"""
debug('HTTP GETting %s' % path)
url = self._make_url(path)
try:
rsp = urllib2.urlopen(url).read()
self.cookie_jar.save(self.cookie_file)
return rsp
except urllib2.HTTPError, e:
print "Unable to access %s (%s). The host path may be invalid" % \
(url, e.code)
try:
debug(e.read())
except AttributeError:
pass
die()
def _make_url(self, path):
"""Given a path on the server returns a full http:// style url"""
app = urlparse(self.url)[2]
if path[0] == '/':
url = urljoin(self.url, app[:-1] + path)
else:
url = urljoin(self.url, app + path)
if not url.startswith('http'):
url = 'http://%s' % url
return url
def api_get(self, path):
"""
Performs an API call using HTTP GET at the specified path.
"""
return self.process_json(self.http_get(path))
def http_post(self, path, fields, files=None):
"""
Performs an HTTP POST on the specified path, storing any cookies that
were set.
"""
if fields:
debug_fields = fields.copy()
else:
debug_fields = {}
if 'password' in debug_fields:
debug_fields["password"] = "**************"
url = self._make_url(path)
debug('HTTP POSTing to %s: %s' % (url, debug_fields))
content_type, body = self._encode_multipart_formdata(fields, files)
headers = {
'Content-Type': content_type,
'Content-Length': str(len(body))
}
try:
r = urllib2.Request(url, body, headers)
data = urllib2.urlopen(r).read()
self.cookie_jar.save(self.cookie_file)
return data
except urllib2.URLError, e:
try:
debug(e.read())
except AttributeError:
pass
die("Unable to access %s. The host path may be invalid\n%s" % \
(url, e))
except urllib2.HTTPError, e:
die("Unable to access %s (%s). The host path may be invalid\n%s" % \
(url, e.code, e.read()))
def api_post(self, path, fields=None, files=None):
"""
Performs an API call using HTTP POST at the specified path.
"""
return self.process_json(self.http_post(path, fields, files))
def _encode_multipart_formdata(self, fields, files):
"""
Encodes data for use in an HTTP POST.
"""
BOUNDARY = mimetools.choose_boundary()
content = ""
fields = fields or {}
files = files or {}
for key in fields:
content += "--" + BOUNDARY + "\r\n"
content += "Content-Disposition: form-data; name=\"%s\"\r\n" % key
content += "\r\n"
content += fields[key] + "\r\n"
for key in files:
filename = files[key]['filename']
value = files[key]['content']
content += "--" + BOUNDARY + "\r\n"
content += "Content-Disposition: form-data; name=\"%s\"; " % key
content += "filename=\"%s\"\r\n" % filename
content += "\r\n"
content += value + "\r\n"
content += "--" + BOUNDARY + "--\r\n"
content += "\r\n"
content_type = "multipart/form-data; boundary=%s" % BOUNDARY
return content_type, content
class SCMClient(object):
"""
A base representation of an SCM tool for fetching repository information
and generating diffs.
"""
def get_repository_info(self):
return None
def scan_for_server(self, repository_info):
"""
Scans the current directory on up to find a .reviewboard file
containing the server path.
"""
server_url = self._get_server_from_config(user_config, repository_info)
if server_url:
return server_url
for path in walk_parents(os.getcwd()):
filename = os.path.join(path, ".reviewboardrc")
if os.path.exists(filename):
config = load_config_file(filename)
server_url = self._get_server_from_config(config,
repository_info)
if server_url:
return server_url
return None
def diff(self, args):
"""
Returns the generated diff and optional parent diff for this
repository.
The returned tuple is (diff_string, parent_diff_string)
"""
return (None, None)
def diff_between_revisions(self, revision_range, args, repository_info):
"""
Returns the generated diff between revisions in the repository.
"""
return None
def _get_server_from_config(self, config, repository_info):
if 'REVIEWBOARD_URL' in config:
return config['REVIEWBOARD_URL']
elif 'TREES' in config:
trees = config['TREES']
if not isinstance(trees, dict):
die("Warning: 'TREES' in config file is not a dict!")
if repository_info.path in trees and \
'REVIEWBOARD_URL' in trees[repository_info.path]:
return trees[repository_info.path]['REVIEWBOARD_URL']
return None
class CVSClient(SCMClient):
"""
A wrapper around the cvs tool that fetches repository
information and generates compatible diffs.
"""
def get_repository_info(self):
if not check_install("cvs"):
return None
cvsroot_path = os.path.join("CVS", "Root")
if not os.path.exists(cvsroot_path):
return None
fp = open(cvsroot_path, "r")
repository_path = fp.read().strip()
fp.close()
i = repository_path.find("@")
if i != -1:
repository_path = repository_path[i + 1:]
i = repository_path.find(":")
if i != -1:
host = repository_path[:i]
try:
canon = socket.getfqdn(host)
repository_path = repository_path.replace('%s:' % host,
'%s:' % canon)
except socket.error, msg:
debug("failed to get fqdn for %s, msg=%s" % (host, msg))
return RepositoryInfo(path=repository_path)
def diff(self, files):
"""
Performs a diff across all modified files in a CVS repository.
CVS repositories do not support branches of branches in a way that
makes parent diffs possible, so we never return a parent diff
(the second value in the tuple).
"""
return (self.do_diff(files), None)
def diff_between_revisions(self, revision_range, args, repository_info):
"""
Performs a diff between 2 revisions of a CVS repository.
"""
revs = []
for rev in revision_range.split(":"):
revs += ["-r", rev]
return self.do_diff(revs)
def do_diff(self, params):
"""
Performs the actual diff operation through cvs diff, handling
fake errors generated by CVS.
"""
# Diff returns "1" if differences were found.
return execute(["cvs", "diff", "-uN"] + params,
extra_ignore_errors=(1,))
class ClearCaseClient(SCMClient):
"""
A wrapper around the clearcase tool that fetches repository
information and generates compatible diffs.
This client assumes that cygwin is installed on windows.
"""
ccroot_path = "/view/reviewboard.diffview/vobs/"
viewinfo = ""
viewtype = "snapshot"
def get_filename_hash(self, fname):
# Hash the filename string so its easy to find the file later on.
return md5(fname).hexdigest()
def get_repository_info(self):
if not check_install('cleartool help'):
return None
# We must be running this from inside a view.
# Otherwise it doesn't make sense.
self.viewinfo = execute(["cleartool", "pwv", "-short"])
if self.viewinfo.startswith('\*\* NONE'):
return None
# Returning the hardcoded clearcase root path to match the server
# respository path.
# There is no reason to have a dynamic path unless you have
# multiple clearcase repositories. This should be implemented.
return RepositoryInfo(path=self.ccroot_path,
base_path=self.ccroot_path,
supports_parent_diffs=False)
def get_previous_version(self, files):
file = []
curdir = os.getcwd()
# Cygwin case must transform a linux-like path to windows like path
# including drive letter.
if 'cygdrive' in curdir:
where = curdir.index('cygdrive') + 9
drive_letter = curdir[where:where+1]
curdir = drive_letter + ":\\" + curdir[where+2:len(curdir)]
for key in files:
# Sometimes there is a quote in the filename. It must be removed.
key = key.replace('\'', '')
elem_path = cpath.normpath(os.path.join(curdir, key))
# Removing anything before the last /vobs
# because it may be repeated.
elem_path_idx = elem_path.rfind("/vobs")
if elem_path_idx != -1:
elem_path = elem_path[elem_path_idx:len(elem_path)].strip("\"")
# Call cleartool to get this version and the previous version
# of the element.
curr_version, pre_version = execute(
["cleartool", "desc", "-pre", elem_path])
curr_version = cpath.normpath(curr_version)
pre_version = pre_version.split(':')[1].strip()
# If a specific version was given, remove it from the path
# to avoid version duplication
if "@@" in elem_path:
elem_path = elem_path[:elem_path.rfind("@@")]
file.append(elem_path + "@@" + pre_version)
file.append(curr_version)
# Determnine if the view type is snapshot or dynamic.
if os.path.exists(file[0]):
self.viewtype = "dynamic"
return file
def get_extended_namespace(self, files):
"""
Parses the file path to get the extended namespace
"""
versions = self.get_previous_version(files)
evfiles = []
hlist = []
for vkey in versions:
# Verify if it is a checkedout file.
if "CHECKEDOUT" in vkey:
# For checkedout files just add it to the file list
# since it cannot be accessed outside the view.
splversions = vkey[:vkey.rfind("@@")]
evfiles.append(splversions)
else:
# For checkedin files.
ext_path = []
ver = []
fname = "" # fname holds the file name without the version.
(bpath, fpath) = cpath.splitdrive(vkey)
if bpath :
# Windows.
# The version (if specified like file.c@@/main/1)
# should be kept as a single string
# so split the path and concat the file name
# and version in the last position of the list.
ver = fpath.split("@@")
splversions = fpath[:vkey.rfind("@@")].split("\\")
fname = splversions.pop()
splversions.append(fname + ver[1])
else :
# Linux.
bpath = vkey[:vkey.rfind("vobs")+4]
fpath = vkey[vkey.rfind("vobs")+5:]
ver = fpath.split("@@")
splversions = ver[0][:vkey.rfind("@@")].split("/")
fname = splversions.pop()
splversions.append(fname + ver[1])
filename = splversions.pop()
bpath = cpath.normpath(bpath + "/")
elem_path = bpath
for key in splversions:
# For each element (directory) in the path,
# get its version from clearcase.
elem_path = cpath.join(elem_path, key)
# This is the version to be appended to the extended
# path list.
this_version = execute(
["cleartool", "desc", "-fmt", "%Vn",
cpath.normpath(elem_path)])
if this_version:
ext_path.append(key + "/@@" + this_version + "/")
else:
ext_path.append(key + "/")
# This must be done in case we haven't specified
# the version on the command line.
ext_path.append(cpath.normpath(fname + "/@@" +
vkey[vkey.rfind("@@")+2:len(vkey)]))
epstr = cpath.join(bpath, cpath.normpath(''.join(ext_path)))
evfiles.append(epstr)
"""
In windows, there is a problem with long names(> 254).
In this case, we hash the string and copy the unextended
filename to a temp file whose name is the hash.
This way we can get the file later on for diff.
The same problem applies to snapshot views where the
extended name isn't available.
The previous file must be copied from the CC server
to a local dir.
"""
if cpath.exists(epstr) :
pass
else:
if len(epstr) > 254 or self.viewtype == "snapshot":
name = self.get_filename_hash(epstr)
# Check if this hash is already in the list
try:
i = hlist.index(name)
die("ERROR: duplicate value %s : %s" %
(name, epstr))
except ValueError:
hlist.append(name)
normkey = cpath.normpath(vkey)
td = tempfile.gettempdir()
# Cygwin case must transform a linux-like path to
# windows like path including drive letter
if 'cygdrive' in td:
where = td.index('cygdrive') + 9
drive_letter = td[where:where+1] + ":"
td = cpath.join(drive_letter, td[where+1:])
tf = cpath.normpath(cpath.join(td, name))
if cpath.exists(tf):
debug("WARNING: FILE EXISTS")
os.unlink(tf)
execute(["cleartool", "get", "-to", tf, normkey])
else:
die("ERROR: FILE NOT FOUND : %s" % epstr)
return evfiles
def get_files_from_label(self, label):
voblist=[]
# Get the list of vobs for the current view
allvoblist = execute(["cleartool", "lsvob", "-short"]).split()
# For each vob, find if the label is present
for vob in allvoblist:
try:
execute(["cleartool", "describe", "-local",
"lbtype:%s@%s" % (label, vob)]).split()
voblist.append(vob)
except:
pass
filelist=[]
# For each vob containing the label, get the file list
for vob in voblist:
try:
res = execute(["cleartool", "find", vob, "-all", "-version",
"lbtype(%s)" % label, "-print"])
filelist.extend(res.split())
except :
pass
# Return only the unique itens
return set(filelist)
def diff(self, files):
"""
Performs a diff of the specified file and its previous version.
"""
# We must be running this from inside a view.
# Otherwise it doesn't make sense.
return self.do_diff(self.get_extended_namespace(files))
def diff_label(self, label):
"""
Get the files that are attached to a label and diff them
TODO
"""
return self.diff(self.get_files_from_label(label))
def diff_between_revisions(self, revision_range, args, repository_info):
"""
Performs a diff between 2 revisions of a CC repository.
"""
rev_str = ''
for rev in revision_range.split(":"):
rev_str += "-r %s " % rev
return self.do_diff(rev_str)
def do_diff(self, params):
# Diff returns "1" if differences were found.
# Add the view name and view type to the description
if options.description:
options.description = ("VIEW: " + self.viewinfo +
"VIEWTYPE: " + self.viewtype + "\n" + options.description)
else:
options.description = (self.viewinfo +
"VIEWTYPE: " + self.viewtype + "\n")
o = []
Feol = False
while len(params) > 0:
# Read both original and modified files.
onam = params.pop(0)
mnam = params.pop(0)
file_data = []
do_rem = False
# If the filename length is greater than 254 char for windows,
# we copied the file to a temp file
# because the open will not work for path greater than 254.
# This is valid for the original and
# modified files if the name size is > 254.
for filenam in (onam, mnam) :
if cpath.exists(filenam) and self.viewtype == "dynamic":
do_rem = False
fn = filenam
elif len(filenam) > 254 or self.viewtype == "snapshot":
fn = self.get_filename_hash(filenam)
fn = cpath.join(tempfile.gettempdir(), fn)
do_rem = True
fd = open(cpath.normpath(fn))
fdata = fd.readlines()
fd.close()