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
|
#!/usr/bin/env python
#******************************************************************************\
#* Copyright (C) 2003-2004 Martin Blais <blais@furius.ca>
#*
#* 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, write to the Free Software
#* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#*
#*****************************************************************************/
"""Script to interface between xxdiff and CVS.
This script is used as a simple interface between xxdiff and CVS.
For a more advanced interface, check out Cervisia.
Usage:
------------------------------
xxcvs [<options>] <filename> ...
"""
__version__ = "$Revision: 762 $"
__author__ = "Martin Blais"
#===============================================================================
# EXTERNAL DECLARATIONS
#===============================================================================
import sys, os, shutil
import re, string
import tempfile
from os.path import exists, dirname, isdir, join
import cvs
import cmdqueue
#===============================================================================
# LOCAL DECLARATIONS
#===============================================================================
error_str = "Error:"
extfnre = re.compile('(.*)@@(.*)')
#===============================================================================
# CLASS Error
#===============================================================================
class Error:
"""Exception class for module-level errors."""
def __init__(self, msg):
self.msg = msg
def __repr__(self):
return repr(self.msg)
def __str__(self):
return str(self.msg)
#===============================================================================
# CLASS PrintCheckoutInfo
#===============================================================================
class PrintCheckoutInfo:
"""Print both the current module name and sticky tag if present."""
names = ['pww']
def execute(self, subargs):
if subargs:
raise Error('This command takes no arguments.')
module = cvs.getModule(os.getcwd())
print "Module: ", module
tag = cvs.getTag(os.getcwd())
if not tag: tag = '(none)'
print "Branch: ", tag
#===============================================================================
# CLASS PrintBranches
#===============================================================================
class PrintBranches:
"""Prints all of a file's branches.
<args> are files for which we want to list the branches.
"""
names = ['lsbranches', 'listbranches', 'list_branches']
def execute(self, subargs):
if not subargs:
raise Error('You need to specify files.')
# launch status command
mstatii = cvs.MultipleStatii(subargs,
1, # self.opts.orig_stamp, # we need tags
0, # non-recursive
indir=os.getcwd())
# read the status output asynchronously
self.res = []
while 1:
status = mstatii.next()
if not status:
break
branchTags = status.branchTags()
branchTags.sort()
print status.filename
print '------------------------------'
for tag in branchTags:
print tag
#===============================================================================
# CLASS List
#===============================================================================
class List:
"""Lists the files.
This command is used to get the filenames, branch or stamp tag, status,
revision number.
Output is restricted when using branch-only, modified-only and
conflicts-only options. Otherwise everything specified is output.
"""
names = ['ls', 'list', 'status']
def addopts(self, parser):
parser.add_option('-s', '--short', action='store_true',
help="Output short format (default).")
parser.add_option('-l', '--long', action='store_true',
help="Output long format.")
parser.add_option('-R', '--recursive', action='store_true',
help="List files recursively.")
parser.add_option('-B', '--branch-only', action='store_true',
help="Prints only files on the branch.")
parser.add_option('-M', '--modified-only', action='store_true',
help="Prints only modified files.")
parser.add_option('-C', '--conflicts-only', action='store_true',
help="Prints only conflict files.")
parser.add_option('-H', '--header', action='store_true',
help="Print a nice header at the top (default is "
"off).")
parser.add_option('-w', '--wide', action='store_true',
help="Widen progressive display.")
parser.add_option('-p', '--final', action='store_true',
help="Don't print results progressively (default).")
# this option allows a more compact output
parser.add_option('-a', '--all', action='store_true',
help="Perform on all the files in the module.")
#('orig-stamp', 'o',\
# "Print first stamp of revision for non-branches (long only)."),
#('added-only', 'A', "Prints only added files."),
#('removed-only', 'D', "Prints only removed files."),
# FIXME we'd like to see directories as well
# FIXME when a files has been locally added and is in a subdir, we don't see
# the intervening directory
def execute(self, subargs):
if self.opts.all:
self.opts.recursive = 1
if len(subargs):
raise Error('Cannot use --all and filenames.')
# consolidate long and short
if self.opts.long and self.opts.short:
raise Error('Use either of --long or --short, but not both.')
if not self.opts.long and not self.opts.short:
self.opts.long = 0
self.opts.short = 1
# figure out if we should exclude, in general
self.only = self.opts.branch_only or \
self.opts.modified_only or \
self.opts.conflicts_only
# compute reasonable wideness factors
lenstamp = 20 # approx
if self.opts.wide:
self.wname = 96
self.wstamp = lenstamp + 20
else:
self.wname = 64
self.wstamp = lenstamp + 8
# no arguments, use cwd as input
workarea = getRoot()
indir = None
if not subargs:
subargs = ['.']
if self.opts.all:
indir = workarea
# validate existence
files = []
for file in subargs:
# We cannot do this, or locally deleted file will not show up.
#if not exists(file):
# print >> sys.stderr, "ls: %s: No such file or directory" % file
#else:
files.append(file)
# if progressive, print header now
self.fmtf = "%%-%ds %%-%ds %%-16s (%%s)" % (self.wname, self.wstamp)
self.fmtd = "%%-%ds Directory" % self.wname
if self.opts.header and not self.opts.final:
self.printHeader()
# launch status command
mstatii = cvs.MultipleStatii(files,
1, # self.opts.orig_stamp, # we need tags
self.opts.recursive,
indir)
# read the status output asynchronously
self.res = []
while 1:
status = mstatii.next()
if not status:
break
app = not self.only
branched = status.isBranched()
if self.opts.branch_only:
if branched:
app = 1
if self.opts.modified_only:
if status.status() in cvs.Status.STATSET_LOCAL:
app = 1
if self.opts.conflicts_only:
if status.status() == cvs.Status.CONFLICTS_ON_MERGE:
app = 1
if app == 1:
if self.opts.long:
status.lstag = status.stickyTag()
# note: we could do something smarter here but it depends on
# the way the user manages his CVS repository and release
# and branch tags.
self.res.append(status)
if not self.opts.final:
self.printEntry(status) # print right away
# write out final report
if self.opts.final:
self.printFinal(self.res)
def printFinal(self, res):
# final report: find longest pathname
if self.opts.long:
longn = longt = longr = 0
for s in res:
if type(s) != type(""):
longn = max(longn, len(s.filename))
longt = max(longt, len(s.lstag))
longr = max(longr, len(s.workingRev()))
else:
longn = max(longn, len(s))
self.fmtf = "%%-%ds %%-%ds %%-%ds (%%s)" % (longn, longt, longr)
self.fmtd = "%%-%ds Directory" % longn
if self.opts.header:
self.printHeader()
for s in res:
self.printEntry(s)
def resAppend(self, s):
"""Appends or prints the status or string, depending on it we're
progressive."""
if not self.opts.final:
self.printEntry(s)
self.res.append(s)
def printEntry(self, s):
if self.opts.long:
if type(s) != type(""):
print self.fmtf % (s.filename, s.lstag, s.workingRev(), s.statusStr())
else:
print self.fmtd % s
else: # short
if type(s) != type(""):
#print "%s (%s)" % (s.filename, s.statusStr())
print "%s" % s.filename
else:
print s
def printHeader(self):
l = self.fmtf % ('filename', 'stamp', 'revision', 'status')
print l
print len(l) * '-'
#===============================================================================
# CLASS ListBranchFiles
#===============================================================================
class ListBranchFiles(List):
"""Lists the branch and modified files in a simple report format.
See 'ls' command. This is just a convenience for a format suitable for merge
request.
"""
names = ['getmodfiles', 'get_mod_files', 'list_brfiles']
def execute(self, subargs):
self.opts.long = 1
self.opts.recursive = 1
self.opts.branch_only = 1
self.opts.modified_only = 1
self.opts.conflicts_only = 0
self.opts.header = 1
self.opts.final = 1
if subargs:
self.opts.all = None
else:
self.opts.all = 1
self.opts.short = None
self.opts.wide = None
# self.opts.orig_stamp = None
List.execute(self, subargs)
#def printFinal(self, res):
# # FIXME todo, fancy it up
#===============================================================================
# CLASS RemoveBranch
#===============================================================================
class RemoveBranch:
"""Removes the revisions on a branch.
This command allows you to get rid of the modifications you have done on a
branch for a particular file. *ACHTUNG*! The results are irreversible and
the revisions are obliterated. This does not delete the branch tag, and
does revert the file to its last stamp version.
<args> is a list of files for which we want to remove the changes made on
the branch.
"""
save_suffix = "%s.save.%d"
names = ['rmbranch', 'removebranch', 'remove_branch',
'deletebranch', 'delete_branch']
def addopts(self, parser):
parser.add_option('-s', '--save', action='store_true',
help="Save backup files before reverting.")
parser.add_option('--save-suffix', action='store_true',
help="Save format (default: %s)." % self.save_suffix)
def execute(self, subargs):
if not self.opts.save_suffix:
self.opts.save_suffix = Revert.save_suffix
if self.gopts.verbose: print "==> Checking that the files are on a branch"
statusmap = {}
for file in subargs:
status = cvs.Status(file)
if not status.isBranched():
raise Error('File %s is not on a branch.' % file)
statusmap[file] = status
workarea = getRoot()
for status in statusmap.values():
file = status.filename
branch = status.stickyTag()
if self.opts.save:
c = 0
savefn = self.opts.save_suffix % (file, c)
while exists(savefn):
c += 1
savefn = self.opts.save_suffix % (file, c)
try:
if self.gopts.verbose: print "==> Saving safe copy into %s" % savefn
shutil.copyfile(file, savefn)
print "Saved copy in '%s'" % savefn
except OSError, e:
raise Error("Cannot copy file %s into %s: %s",
(file, savefn, repr(e)))
else:
if not self.gopts.expert:
if not yesOrNo("Changes on '%s' will be lost, are you sure?" \
% file):
print "Ignoring file '%s'" % file
continue
if self.gopts.verbose:
print "==> Deleting the repository revisions for file %s" % file
cmd = '%s admin -o:%s %s' % \
(cvs.program, status.stickyTag(), file)
cvs.delegate(cmd)
if self.gopts.verbose:
print "==> Updating file %s" % file
cvs.delegate("%s update -r %s %s" % (cvs.program, branch, file))
#if sts[0]:
# raise Error("Moving tag.")
#===============================================================================
# CLASS Revert
#===============================================================================
class Revert:
"""Reverts to the last committed version.
This command allows you to get rid of the modifications you have done on a
file and revert to the last committed revision.
<args> is a list of files to revert.
"""
save_suffix = "%s.save.%d"
names = ['revert', 'uncheckout', 'unco']
def addopts(self, parser):
parser.add_option('-s', '--save', action='store_true',
help="Save backup files before reverting.")
parser.add_option('--save-suffix', action='store_true',
help="Save format "
"(default is %s)." % self.save_suffix)
#('all', 'a', "Perform on all the modified files in the module.")
def execute(self, subargs):
if not self.opts.save_suffix:
self.opts.save_suffix = Revert.save_suffix
for file in subargs:
if self.gopts.verbose: print "==> Processing file %s." % file
if isdir(file):
print >> sys.stderr, \
"Directories not supported yet, ignoring %s." % file
continue
if self.gopts.verbose: print "==> Checking that file is modified"
status = cvs.Status(file)
if status.status() not in cvs.Status.STATSET_MODIFIED:
print >> sys.stderr, "File %s is not Locally Modified." % file
continue
if self.opts.save:
c = 0
savefn = self.opts.save_suffix % (file, c)
while exists(savefn):
c += 1
savefn = self.opts.save_suffix % (file, c)
try:
if self.gopts.verbose: print "==> Saving safe copy into %s" % savefn
os.rename(file, savefn)
print "Saved copy in '%s'" % savefn
except OSError, e:
raise Error("Cannot rename file %s into %s: %s",
(file, savefn, repr(e)))
else:
if not self.gopts.expert:
if not yesOrNo("Changes on '%s' will be lost, are you sure?" \
% file):
print "Ignoring file '%s'" % file
continue
if self.gopts.verbose: print "==> Reverting file"
cvs.run('%s update -C %s' % (cvs.program, file))
status.lstag = status.stickyTag()
print "File '%s' reverted to revision %s (%s)" % \
(file, status.workingRev(), status.lstag)
#===============================================================================
# CLASS Fetch
#===============================================================================
class Fetch:
"""Fetches a revision of a file from the repository.
This command allows you to fetch any revision of any file from the
repository. By default the file is written out to 'filename@@rev'.
In practice, this is just a more convenient implementation of
'cvs update -p'. Files and revisions are specified as filename@@rev.
Revisions can be either revision numbers, stamps or branch tags.
If no revision is request, it saves to filename@@HEAD.
<args> are the names of the files to fetch. If revision is specified
thru option, only one filename is allowed.
"""
names = ['get', 'fetch', 'cat']
stdout_sep1 = 79 * '='
def addopts(self, parser):
parser.add_option('-p', '--stdout', action='store_true',
help="Output to stdout (don't write output file).")
parser.add_option('-m', '--module', action='store',
help="Fetch files from specified module (no need "
"for workarea).")
parser.add_option('-r', '--revision', action='store',
help="Specify which revision for filename.")
def execute(self, subargs):
if self.gopts.verbose: print "==> Parsing arguments"
if not subargs:
raise Error('No file specified.')
if self.opts.revision:
if len(subargs) != 1:
raise Error('Only one filename can be specified with --revision.')
# use equivalent format.
subargs = [ '%s@@%s' % (subargs[0], self.opts.revision) ]
for arg in subargs:
if self.gopts.verbose: print "==> Processing file %s", arg
if self.gopts.verbose: print "==> Parsing filename"
mo = extfnre.match(arg)
if mo:
(filename, rev) = mo.groups()
else:
filename = arg
rev = None
if self.gopts.verbose: print "==> Fetching file"
(contents, errors) = cvs.fetch(filename, rev, None, self.opts.module)
if contents == None:
print >> sys.stderr, \
"Error: fetching file %s with revision %s" % \
(filename, rev)
print >> sys.stderr, errors
# don't crash it, continue, there may be many files.
continue
if self.gopts.verbose: print "==> Outputting file"
if not rev:
rev = 'HEAD'
if self.opts.stdout:
if len(subargs) > 1:
# print header
print Fetch.stdout_sep1
print "File:", filename, " Revision:", rev
print
print contents
if contents == '':
print >> sys.stderr, "(Empty file)"
else:
try:
outf = open(filename + '@@' + rev, 'w')
outf.write(contents)
outf.close()
except IOError, e:
print >> sys.stderr, "Error: writing fetched file %s", outfn
print e
#===============================================================================
# CLASS Mani
#===============================================================================
class Mani:
"""Base class for classes that extract temporary files to disk."""
# Que viene el manisero... mani, maniiiii (slrp).
temp_sfx = '.xxcvs_tempfile'
# common diff options
def addopts(self, parser):
parser.add_option('-w', '--ignore-all-space', action='store_true',
help="Option given to diff(1).")
parser.add_option('-b', '--ignore-space-change', action='store_true',
help="Option given to diff(1).")
parser.add_option('-i', '--ignore-case', action='store_true',
help="Option given to diff(1).")
parser.add_option('-l', '--ignore-blank-lines', action='store_true',
help="Option given to diff(1).")
#===========================================================================
# CLASS Mani.QueueCmd
#===========================================================================
class QueueCmd:
def __init__(self, cmd, filelist):
self.cmd = cmd
self.filelist = filelist
self.post_hooks = []
def preRun(self, queue):
print >> sys.stderr, " ,------------------------------"
print >> sys.stderr, " | Running diff with:"
for file in self.filelist:
print >> sys.stderr, " |", file.print_name
print >> sys.stderr, " '------------------------------"
def postRun(self, queue):
self.filelist = None # release filelist and tempfile
if self.post_hooks:
for hook in self.post_hooks:
hook()
if queue.waitingForAll and len(queue.waiting) > 0:
print >> sys.stderr,\
"[ %s remaining commands queued ]" % len(queue.waiting)
#===========================================================================
# CLASS Mani.File
#===========================================================================
class File:
def __init__(self, name, rev):
self.name = name
self.rev = rev
self.print_rev = rev
self.tempname = None
self.status = None
self.print_name = name
self.valid = 1
self.empty = 0
def __del__(self):
if self.tempname and os.path.exists(self.tempname):
os.unlink(self.tempname)
def formatName(self):
self.print_name = self.doFormatName()
def doFormatName(self):
if self.print_rev:
return '%s (%s)' % (self.name, self.print_rev)
elif self.print_rev:
return '%s (%s)' % (self.name, self.rev)
else:
return self.name
def __init__(self):
self.queue = None # we cannot create the queue before we parse the options.
def __del__(self):
if self.queue:
self.queue = None # make sure we wait for queue here.
def computeOptionsString(self):
# compute diff options string
options = []
if self.opts.ignore_all_space:
options.append('--ignore-all-space')
if self.opts.ignore_space_change:
options.append('--ignore-space-change')
if self.opts.ignore_blank_lines:
options.append('--ignore-blank-lines')
return ' '.join(options)
def parseFilename(self, fn):
"""Parses a filename and returns a File object."""
if self.gopts.verbose: print "==> Parsing filename", fn
mo = extfnre.match(fn)
if mo:
(filename, rev) = mo.groups()
else:
filename = fn
rev = None
return Mani.File(filename, rev)
def printDiffGroup(self, group):
if len(group) == 2:
print " Left: ", group[0].print_name
print " Right: ", group[1].print_name
elif len(group) == 3:
print " Left: ", group[0].print_name
print " Middle:", group[1].print_name
print " Right: ", group[2].print_name
def fetchFile(self, file, workarea=None, module=None):
tempname = tempfile.mktemp() + Mani.temp_sfx
if file.empty:
if self.gopts.verbose:
print "==> Creating empty file into %s" % tempname
contents = ''
else:
if self.gopts.verbose:
print "==> Fetching file %s into %s" % (file.name, tempname)
(contents, errors) = cvs.fetch(file.name, file.rev, workarea, module)
if contents == None:
raise Error("Fetching file %s with revision %s" % \
(file.name, file.rev))
try:
tempf = open(tempname, 'w')
tempf.write(contents)
tempf.close()
except IOError, e:
raise Error("Writing to temp file %s" % tempname)
return tempname
def spawnDiff(self, filelist, graphical, merged_filename=None, root=None, hook=None):
options = self.options
if len(filelist) == 3:
options = ''
options += self.extra_options
if graphical:
cmd = [self.gopts.xxdiff] + options.split()
#cmd += '--exit-on-same ' # so we don't have annoying previews until stable
idx = 0
for file in filelist:
idx += 1
if file.tempname or file.print_rev:
cmd += ['--title%d=%s' % (idx, file.print_name)]
if not merged_filename:
merged_filename = filelist[0].name + '.merge'
cmd += ['--merged-filename=%s' % merged_filename]
else:
cmd = [self.gopts.diff] + options.split()
for file in filelist:
if file.tempname:
cmd += ['%s' % file.tempname]
elif root:
cmd += ['%s' % join(root, file.name)]
else:
cmd += ['%s' % file.name]
if self.gopts.verbose: print "==> Diffing command:", ' '.join(cmd)
if not self.queue:
if self.gopts.no_async:
self.queue = cmdqueue.SyncFakeQueue(1)
else:
self.queue = cmdqueue.CmdQueue(1)
cmdobj = Mani.QueueCmd(cmd, filelist)
if hook:
cmdobj.post_hooks.append(hook)
self.queue.queue(cmd, cmdobj)
# if graphical:
# os.popen(cmd)
# # interruptible
# else:
# #os.popen(cmd)
# os.system(cmd)
# # FIXME do something about interruptibility here, try/except
# # KeyboardInterrupt does not work, see man 3 system.
#===============================================================================
# CLASS Diff
#===============================================================================
class Diff(Mani):
"""Shows differences between files.
This command allows you to diff any two revisions of a file, with convenient
functionality for diffing with branch or previous. Most likely, you will use
the 'preview' command rather than this one, but this one is more flexible.
This command does not aspire to replace 'cvs diff', but to give a convenient
way to start the graphical diff, with the few options that it supports. If
you want more complex diffing options, use 'cvs diff' directly.
This command has a few syntactic forms:
xxcvs diff <file[@@rev]> <file[@@rev]> ...
--> diff all the specified file-revisions together (3 max)
xxcvs diff --revision=<rev> <file>
--> diff local file copy with its specified revision
xxcvs diff [--previous | --branch] <file[@@rev]> [<file[@@rev]> ...]
--> diff file-revisions with their respective previous (or main branch)
revisions. Note that we consider the previous revision of a modified
file to be the last committed revision.
"""
graphical_names = ['xdiff', 'xxdiff', 'graphical_diff']
names = ['diff', 'cmp', 'compare'] + graphical_names
def addopts(self, parser):
Mani.addopts(self, parser)
parser.add_option('-m', '--module', action='store',
help="Fetch files from specified module (no need for workarea).")
parser.add_option('-t', '--textual', action='store_true',
help="Run diff in text mode instead of graphical output.")
parser.add_option('-r', '--revision', action='store',
help="Diff local file copy with this revision.")
parser.add_option('-p', '--previous', action='store_true',
help="Diff each file with its previous revision, or parent.")
parser.add_option('-B', '--branch', action='store_true',
help="Diff each file with its parent branch (main).")
parser.add_option('--reverse', action='store_true',
help="Reverse order of files (order is by default reversed).")
# --recursive, -r Option passed to 2-files diff(1). This is only
# meaningful for directory diffs.
# FIXME make it possible to view the differences between two stamps without
# a checkout area
# FIXME if module is specified, then we should not assume anything about the
# files nor use the current repository at all. Otherwise, we assume that we
# are in a checkout.
def execute(self, subargs):
if self.gopts.verbose: print "==> Validating arguments"
if not subargs:
raise Error('No files specified.')
if self.opts.previous and self.opts.branch:
raise Error('Cannot request both previous and branch.')
self.options = self.computeOptionsString()
self.extra_options = ''
workarea = getRoot()
indir = None
if self.opts.module:
indir = workarea
if self.gopts.verbose: print "==> Parsing filenames"
# parse all filenames to potentially figure out if we need to compute
# status to find previous or branch. this allows us to launch a single
# status command if necessary (much faster).
fileobjs = []
need_status = []
for arg in subargs:
file = self.parseFilename(arg)
fileobjs.append(file)
if self.opts.previous or self.opts.branch:
need_status.append(file)
if self.gopts.verbose: print "==> Getting status for needed filenames"
need_fns = map(lambda x: x.name, need_status)
if self.gopts.verbose: print "==>", need_fns
if self.opts.previous or self.opts.branch and need_status:
mstatii = cvs.MultipleStatii(need_fns, 1, 0, indir)
i = 0
while 1:
status = mstatii.next()
if not status:
break
file = need_status[i]
file.status = status
i += 1
if self.gopts.verbose: print "==> Building filegroups"
filegroups = []
if self.opts.revision:
if len(fileobjs) != 1:
raise Error('Only one filename can be specified with --revision.')
file = fileobjs[0]
#if not file.rev:
# file.print_rev = 'Local'
# # here we don't bother with status just for the working revision
filer = Mani.File(file.name, self.opts.revision)
filegroups.append( (file, filer) )
elif self.opts.previous:
for file in fileobjs:
if file.rev:
rev_pob = file.status.previousOrParent(file.rev)
elif file.status.status() == cvs.Status.LOCALLY_MODIFIED:
file.print_rev = 'Local: %s modified' % file.status.workingRev()
rev_pob = file.status.workingRev()
else:
file.print_rev = 'Local: %s' % file.status.workingRev()
rev_pob = file.status.previousOrParent( file.status.workingRev() )
if not rev_pob:
print 'Warning: no previous or branch for', file.name
continue
file_pob = Mani.File(file.name, rev_pob)
filegroups.append( (file_pob, file) )
elif self.opts.branch:
for file in fileobjs:
if file.rev:
rev_pob = file.status.parentBranchRev(file.rev)
else:
rev_pob = file.status.parentBranchRev(file.status.workingRev())
if file.status.status() == cvs.Status.LOCALLY_MODIFIED:
file.print_rev = 'Local: %s modified' % file.status.workingRev()
else:
file.print_rev = 'Local: %s' % file.status.workingRev()
if not rev_pob:
print 'Warning: no parent branch for', file.name
continue
file_b = Mani.File(file.name, rev_pob)
filegroups.append( (file_b, file) )
else:
if len(fileobjs) not in [2, 3]:
raise Error('You need to specify 2 or 3 filenames to diff.')
files = []
for file in fileobjs:
files.append(file)
filegroups.append(files)
for group in filegroups:
for file in group:
if file.rev:
file.tempname = self.fetchFile(file, module=self.opts.module)
assert(len(group) == 2 or len(group) == 3)
for file in group:
file.formatName()
# by default, new file is on the right.
if self.opts.reverse:
group.reverse()
print "--------------------"
self.printDiffGroup(group)
self.spawnDiff(group, not self.opts.textual)
#===============================================================================
# CLASS DiffModified
#===============================================================================
class DiffModified(Mani):
"""Shows differences for all modified files with last committed revision.
This command allows you to preview the differences before committing
changes.
xxcvs diffmodfiles [<dir>]
--> diff all modified files under directory with their last committed
revisions. Default directory is module root.
"""
names = ['diffmodfiles', 'diff_mod_files', 'moddiff']
def addopts(self, parser):
Mani.addopts(self, parser)
parser.add_option('-m', '--module', action='store',
help="Fetch files from specified module (no need for workarea).")
parser.add_option('-t', '--textual', action='store_true',
help="Run diff in text mode instead of graphical output.")
parser.add_option('-N', '--no-recursive', action='store_true',
help="Don't preview directories recursively.")
parser.add_option('--silent', action='store_true',
help="Don't be so verbose about progress and all.")
parser.add_option('-r', '--reverse', action='store_true',
help="Reverse order of files (order is by default reversed).")
def execute(self, subargs):
self.options = self.computeOptionsString()
self.extra_options = ''
if self.gopts.verbose: print "==> Validating arguments"
workarea = getRoot()
indir = None
if self.opts.module:
indir = workarea
# do preview on the whole repository if there were no arguments
if not subargs:
subargs = ['.']
indir = workarea
# validate existence
files = []
for file in subargs:
# We cannot do this, or locally deleted file will not show up.
#if not exists(file):
# print >> sys.stderr, "ls: %s: No such file or directory" % file
#else:
files.append(file)
mstatii = cvs.MultipleStatii(files, 1, not self.opts.no_recursive, indir)
prog = 0
while 1:
status = mstatii.next()
if not status:
break
if not self.opts.silent:
print "(%s)" % status.filename
if self.queue:
self.queue.poll()
status.local_name = status.filename
if status.status() not in [cvs.Status.LOCALLY_MODIFIED,
cvs.Status.CONFLICTS_ON_MERGE]:
continue
# Note: it is important here that if there is no revision,
# the filename be relative to the current directory.
local_file = Mani.File(status.local_name, None)
local_file.print_rev = 'Local: %s modified' % status.workingRev()
workrev_file = Mani.File(status.filename, status.workingRev())
group = [ workrev_file, local_file ]
for file in group:
if file.rev:
file.tempname = self.fetchFile(file, workarea, self.opts.module)
# by default, new file is on the right.
if self.opts.reverse:
group.reverse()
for file in group:
file.formatName()
print "--------------------"
self.printDiffGroup(group)
self.spawnDiff(group, not self.opts.textual, status.filename, root=workarea)
print
#-------------------------------------------------------------------------------
#
def parse_subcommands(gparser, subcmds):
"""Parse given global arguments, find subcommand from given list of
subcommand objects, parse local arguments and return a tuple of global
options, selected command object, command options, and command arguments.
Call execute() on the command object to run. The command object has members
'self.gopts' and 'opts' set for global and command options respectively, you
don't need to call execute with those but you could if you wanted to."""
import optparse
global subcmds_map # needed for help command only.
# Build map of name -> command and docstring.
subcmds_map = {}
gparser.usage += '\n\nAvailable Subcommands\n\n'
for sc in subcmds:
gparser.usage += '- %s: %s\n' % (', '.join(sc.names),
sc.__doc__.splitlines()[0])
for n in sc.names:
assert n not in subcmds_map
subcmds_map[n] = sc
# Declare and parse global options.
gparser.disable_interspersed_args()
gopts, args = gparser.parse_args()
if not args:
gparser.print_help()
raise SystemExit("Error: you must specify a command to use.")
subcmdname, subargs = args[0], args[1:]
# Parse command arguments and invoke command.
try:
sc = subcmds_map[subcmdname]
lparser = optparse.OptionParser(sc.__doc__.strip())
if hasattr(sc, 'addopts'):
sc.addopts(lparser)
sc.gopts = gopts
sc.opts, subsubargs = lparser.parse_args(subargs)
except KeyError:
raise SystemExit("Error: invalid command '%s'" % subcmdname)
return sc.gopts, sc, sc.opts, subsubargs
#===============================================================================
# MAIN
#===============================================================================
co_root = None
def getRoot():
"""Returns the checkout directory root."""
global co_root
dir = os.getcwd()
while exists(join(dir,'CVS')) and dir and dir != '/':
dir = dirname(dir)
if not dir or dir == '/':
raise Error('Not currently in a checked out directory')
co_root = dir
return co_root
try:
import optparse
parser = optparse.OptionParser(__doc__.strip(), version=__version__)
parser.add_option('-v', '--verbose', action='store_true',
help="Verbose mode.")
parser.add_option('--debug', action='store_true',
help="Full-on debug mode, including CVS commands.")
parser.add_option('-x', '--expert', action='store_true',
help="Expert mode, skip confirmations, use with care.")
parser.add_option('-D', '--dir', action='store',
help="Specify workarea directory (default is cwd).")
parser.add_option('--cvs', action='store',
help="Specify cvs executable.")
parser.add_option('--diff', action='store',
help="Specify textual diff executable.")
parser.add_option('--xxdiff', action='store',
help="Specify graphical diff executable.")
parser.add_option('--no-async', action='store_true',
help="Disable asynchronous command queuing for those "
"commands that support it.")
# don't use 'd' in case we want it for cvsroot in the future.
#('silent', 's', "Silent mode." ),
# Declare subcommands
subcmds = [
Fetch(),
PrintCheckoutInfo(),
PrintBranches(),
List(),
ListBranchFiles(),
RemoveBranch(),
Revert(),
Diff(),
DiffModified()
]
#Test()
gopts, sc, opts, args = parse_subcommands(parser, subcmds)
if gopts.dir:
if not exists(gopts.dir):
raise Error('Specified workarea directory does not exist.')
else:
gopts.dir = os.getcwd()
#if gopts.silent and gopts.verbose:
# raise Error('Can only specify one of --verbose and --silent.')
#if gopts.silent:
# gopts.verbose = 0
if gopts.verbose:
cvs.trace_level = 1
if gopts.debug:
gopts.verbose = 1
cvs.trace_level = 2
gopts.verbfmt = ''
if gopts.verbose:
gopts.verbfmt = "==> %s."
if gopts.cvs:
cvs.program = gopts.cvs
if not gopts.xxdiff:
gopts.xxdiff = 'xxdiff'
if not gopts.diff:
gopts.diff = 'diff'
if not gopts.expert:
if os.environ.has_key('EXP_SCRIPTS_EXPERT'):
gopts.expert = 1
sc.execute(args)
# delete all references to the subcmd here for the cmdqueue.
subcmds = subcmd = sc = None
except Error, e:
print error_str, e
sys.exit(1)
except cvs.Error, e:
print 'CVS Error:', e
if gopts.debug:
raise
sys.exit(1)
except KeyboardInterrupt:
print "Interrupted, exiting."
subcmds = subcmd = None
if gopts.debug:
raise
sys.exit(1)
|