Movatterモバイル変換


[0]ホーム

URL:


Welcome, guest|Sign In|My Account|Store|Cart
ActiveState Code »Recipes
LanguagesTagsAuthorsSets

Simple Version Control(Python recipe)by Raymond Hettinger
ActiveState Code (http://code.activestate.com/recipes/576729/)

Read and write version history using TLIB version control format.

Python, 172 lines
Copy to clipboard
  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 99100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
importre,os,sysfromdifflibimportSequenceMatcher,context_difffromdatetimeimportdatetimefromitertoolsimportislicevline=re.compile(r'\.V(?:_\S+)? (\S+) (\S+) ?(.*)').matchnline=re.compile(r'\.N (.*)').matchcline=re.compile(r'\.C (\d+) (\d+)').matchiline=re.compile(r'\.I (\d+)').matchdefget_version(repo_fn,v=None):# Return version *v* or the last version if *v* is None.ifnotos.path.exists(repo_fn):return''currver=0curr=[]f=iter(open(repo_fn,'r'))line=next(f,'')whilelineand(visNoneorcurrver<v):# Start building up next version from the lastcurrver+=1prev,curr=curr,[]# Process mandatory .V line and optional .N msg linesassertline.startswith('.V')forlineinf:ifnotline.startswith('.N'):break# Process the .I and .C instructionswhilelineandline.startswith(('.I','.C')):ifline.startswith('.I'):n=int(iline(line).group(1))curr.extend(islice(f,n))else:m,n=map(int,cline(line).groups())curr.extend(prev[m-1:n])line=next(f,'')return''.join(curr)defprint_log(repo_fn,v=None):# Print log entries. *v* is a specific version number or None to print all.currver=0f=iter(open(repo_fn,'r'))line=next(f,'')whileline:# Process mandatory .V line and optional .N msg linesassertline.startswith('.V')repo_fn,datetime,msg=vline(line).groups()forlineinf:ifline.startswith('.N'):msg+='\n'+nline(line).group(1)else:breakcurrver+=1ifvisNone:print"%s%d%18s%s"%(repo_fn,currver,datetime,msg)elifcurrver==v:print"%s%d%18s%s"%(repo_fn,currver,datetime,msg)return# Skip through the .I and .C instructionswhilelineandline.startswith(('.I','.C')):ifline.startswith('.I'):n=int(iline(line).group(1))forlineinislice(f,n):passline=next(f,'')defdiff(repo_fn,vnum1=None,vnum2=None,context=False):# vnum1 or vnum2 can be None to indicate last version in repository# vnum2 can be a filename to compare tov1=get_version(repo_fn,vnum1).splitlines(True)ifisinstance(vnum2,int)orvnum2isNone:v2=get_version(repo_fn,vnum2).splitlines(True)else:v2=open(vnum2).readlines()results=[]ifcontext:return''.join(context_diff(v1,v2))fortag,i1,i2,j1,j2inSequenceMatcher(None,v1,v2).get_opcodes():iftagin('replace','insert'):results.append('.I%d\n'%(j2-j1))results.extend(v2[j1:j2])eliftag=='equal':results.append('.C%d%d\n'%(i1+1,i2))return''.join(results)defmake_header(filename,msg,create):first='_,03000'ifcreateelse''datestring=datetime.now().strftime('%d-%b-%y,%H:%M:%S')return'.V%(first)s%(filename)s%(datestring)s%(msg)s'%locals()defget_repo_fn(filename):path,fullname=os.path.split(filename)base,ext=os.path.splitext(fullname)ext=extor'.'newext=ext[:2]+'$'+ext[3:]result=os.path.join(repo_dir,base+newext)returnresultrepo_dir=os.environ.get('VCS','.')# ------- Command-line interface -------help_msg='''Usage:    vcs add foo.bar "Checkin message"    vcs extract foo.bar [revnum]    vcs log foo.bar [revnum]    vcs diff foo.bar [revnum1 [revnum2]]Repository:%s    '''%repo_dirdeftalkback(msg,help=False,code=1):print>>sys.stderr,msgifhelp:print>>sys.stderr,'\n'+help_msgsys.exit(code)defmain(argv):# XXX add support for branching# XXX support .N for outputiflen(argv)<=1:talkback(help_msg,code=0)iflen(argv)<3:talkback('Not enough arguments. Need a command and filename.',help=True)command=argv[1].lower()ifcommandnotin'log extract diff add update l e d a u'.split():talkback('Unknown command: '+command,help=True)command=command[:1]filename=argv[2]repo_fn=get_repo_fn(filename)ifcommandin'le':ifnotos.path.exists(repo_fn):talkback(repo_fn+' not found')v=int(argv[3])iflen(argv)>=4elseNoneifcommand=='l':print_log(repo_fn,v)else:printget_version(repo_fn,v),elifcommand=='d':v1=int(argv[3])iflen(argv)>=4elseNonev2=int(argv[4])iflen(argv)>=5elsefilenameprintdiff(repo_fn,v1,v2,context=True),elifcommandin'au':ifnotos.path.exists(filename):talkback('Cannot find file: '+filename)d=diff(repo_fn,None,filename)iflen(d.splitlines())==1:talkback('File is already current. There are no changes.',code=0)msg=' '.join(argv[3:])create=notos.path.exists(repo_fn)repo_file=open(repo_fn,'a+')print>>repo_file,make_header(filename,msg,create)print>>repo_file,d,repo_file.close()talkback('Added to '+repo_fn,code=0)else:talkback('Unreachable')if__name__=='__main__':main(sys.argv)

Add a file with: vcs a myfile.py Initial check-in

Update a file with: vcs u myfile.py Make some changes

List history: vcs l myfile.py

Show differences from the current version: vcs d myfile.py

Show difference from two checked-in versions: vcs d myfile 2 4

Extract a file with: vcs e myfile.py > myfile.py

3 comments

Gary Eakins14 years, 11 months ago # |flag

I had to define the next() function to get this to work in Python 2.5:

def next(o, default):    try:        return o.next()    except StopIteration:        return default
Johannes14 years, 5 months ago # |flag

It is unfortunately useless since it does not deal with deleted lines.

I am unfortunately ignorant on the tlib format so I don't know how to fix it.

/Johannes

Raymond Hettinger(author)13 years, 8 months ago # |flag

Johannes, the copy and insert style does not need deletes. It copies only the parts that are re-used and ignores the rest.

If lines abcdefgh get converted to xyabczef, the transformation is recorded as Insert xy, Copy abc, Insert z, Copy ef.

The deletes are implicit in that they are the lines that are not copied :-)

Created byRaymond HettingeronSun, 26 Apr 2009(MIT)
Python recipes (4591)
Raymond Hettinger's recipes (97)

Other Information and Tasks

 

Accounts

Code Recipes

Feedback & Information

ActiveState

Privacy Policy |Contact Us |Support

© 2024 ActiveState Software Inc. All rights reserved. ActiveState®, Komodo®, ActiveState Perl Dev Kit®, ActiveState Tcl Dev Kit®, ActivePerl®, ActivePython®, and ActiveTcl® are registered trademarks of ActiveState. All other marks are property of their respective owners.

 x  

[8]ページ先頭

©2009-2026 Movatter.jp