source: tailor/vcpx/svn.py @ 46

Revision 46, 9.4 KB checked in by lele@…, 9 years ago (diff)

Correct the initialization of a new working directory

Line 
1#! /usr/bin/python
2# -*- mode: python; coding: utf-8 -*-
3# :Progetto: vcpx -- Subversion details
4# :Creato:   ven 18 giu 2004 15:00:52 CEST
5# :Autore:   Lele Gaifax <lele@nautilus.homeip.net>
6#
7
8"""
9This module contains supporting classes for Subversion.
10"""
11
12__docformat__ = 'reStructuredText'
13
14from shwrap import SystemCommand
15from source import UpdatableSourceWorkingDir
16from target import SyncronizableTargetWorkingDir, TargetInitializationFailure
17
18
19class SvnUpdate(SystemCommand):
20    COMMAND = "svn update --revision %(revision)s %(entry)s"
21
22
23class SvnInfo(SystemCommand):
24    COMMAND = "LANG= svn info %(entry)s"
25
26    def __call__(self, output=None, dry_run=False, **kwargs):
27        output = SystemCommand.__call__(self, output=True,
28                                        dry_run=dry_run,
29                                        **kwargs)
30        res = {}
31        for l in output:
32            l = l[:-1]
33            if l:
34                key, value = l.split(':', 1)
35                res[key] = value[1:]
36        return res
37
38                 
39class SvnPropGet(SystemCommand):
40    COMMAND = "svn propget %(property)s %(entry)s"
41
42   
43class SvnPropSet(SystemCommand):
44    COMMAND = "svn propset --quiet %(property)s %(value)s %(entry)s"
45
46
47class SvnLog(SystemCommand):
48    COMMAND = "svn log %(quiet)s %(xml)s --revision %(startrev)s:%(endrev)s %(entry)s 2>&1"
49   
50    def __call__(self, output=None, dry_run=False, **kwargs):
51        quiet = kwargs.get('quiet', True)
52        if quiet == True:
53            kwargs['quiet'] = '--quiet'
54        elif quiet == False:
55            kwargs['quiet'] = ''
56           
57        xml = kwargs.get('xml', False)
58        if xml:
59            kwargs['xml'] = '--xml'
60            output = True
61        else:
62            kwargs['xml'] = ''
63
64        startrev = kwargs.get('startrev')
65        if not startrev:
66            kwargs['startrev'] = 'BASE'
67
68        endrev = kwargs.get('endrev')
69        if not endrev:
70            kwargs['endrev'] = 'HEAD'
71
72        output = SystemCommand.__call__(self, output=output,
73                                        dry_run=dry_run, **kwargs)
74
75        if xml:
76            # parse the output and return the result
77            pass
78
79        return output
80
81
82class SvnCommit(SystemCommand):
83    COMMAND = "svn commit --quiet --file %(logfile)s %(entries)s"
84
85    def __call__(self, output=None, dry_run=False, **kwargs):
86        logfile = kwargs.get('logfile')
87        if not logfile:
88            from tempfile import NamedTemporaryFile
89
90            log = NamedTemporaryFile(bufsize=0)
91            logmessage = kwargs.get('logmessage')
92            if logmessage:
93                print >>log, logmessage
94           
95            kwargs['logfile'] = log.name
96       
97        return SystemCommand.__call__(self, output=output,
98                                      dry_run=dry_run, **kwargs)
99
100
101class SvnAdd(SystemCommand):
102    COMMAND = "svn add --quiet --no-auto-props --non-recursive %(entry)s"
103
104       
105class SvnRemove(SystemCommand):
106    COMMAND = "svn remove --quiet --force %(entry)s"
107
108
109class SvnMv(SystemCommand):
110    COMMAND = "svn mv --quiet %(old)s %(new)s"
111
112   
113class SvnCheckout(SystemCommand):
114    COMMAND = "svn co --revision %(revision)s %(repository)s %(wc)s"
115
116   
117class SvnWorkingDir(UpdatableSourceWorkingDir, SyncronizableTargetWorkingDir):
118
119    ## UpdatableSourceWorkingDir
120
121    def _getUpstreamChangesets(self, root, sincerev=None):
122        if sincerev:
123            sincerev = int(sincerev)
124        else:
125            sincerev = 0
126           
127        svnlog = SvnLog(working_dir=root)
128        log = svnlog(quiet='--verbose', output=True, xml=True,
129                     startrev=sincerev+1, entry='.')
130       
131        if svnlog.exit_status:
132            errmsg = log.getvalue()
133            # XXX
134            if 'No such revision' in errmsg:
135                return []
136            else:
137                raise 'XXX: svn log error: %s' % errmsg
138       
139        return self.__parseSvnLog(log)
140
141    def __parseSvnLog(self, log):
142        """Return an object representation of the ``svn log`` thru HEAD."""
143
144        from xml.sax import parseString
145        from xml.sax.handler import ContentHandler
146        from changes import ChangesetEntry, Changeset
147        from datetime import datetime
148       
149        class SvnXMLLogHandler(ContentHandler):
150            def __init__(self):
151                self.changesets = []
152                self.current = None
153                self.current_field = []
154
155            def startElement(self, name, attributes):
156                if name == 'logentry':
157                    self.current = {}
158                    self.current['revision'] = attributes['revision']
159                    self.current['entries'] = []
160                elif name in ['author', 'date', 'msg']:
161                    self.current_field = []
162                elif name == 'path':
163                    self.current_field = []
164                    if attributes.has_key('copyfrom-path'):
165                        self.current_path_action = (
166                            attributes['action'],
167                            attributes['copyfrom-path'][1:], # make it relative
168                            attributes['copyfrom-rev'])
169                    else:
170                        self.current_path_action = attributes['action']
171
172            def endElement(self, name):
173                if name == 'logentry':
174                    # Sort the paths to make tests easier
175                    self.current['entries'].sort()
176                    svndate = self.current['date']
177                    # 2004-04-16T17:12:48.000000Z
178                    y,m,d = map(int, svndate[:10].split('-'))
179                    hh,mm,ss = map(int, svndate[11:19].split(':'))
180                    ms = int(svndate[20:-1])
181                    timestamp = datetime(y, m, d, hh, mm, ss, ms)
182                    self.changesets.append(Changeset(self.current['revision'],
183                                                     timestamp,
184                                                     self.current['author'],
185                                                     self.current['msg'],
186                                                     self.current['entries']))
187                    self.current = None
188                elif name in ['author', 'date', 'msg']:
189                    self.current[name] = ''.join(self.current_field)
190                elif name == 'path':
191                    entry = ChangesetEntry(''.join(self.current_field)[1:])
192                    if type(self.current_path_action) == type( () ):
193                        entry.action_kind = entry.RENAMED
194                        entry.old_name = self.current_path_action[1]
195                    else:
196                        entry.action_kind = self.current_path_action
197
198                    self.current['entries'].append(entry)
199
200            def characters(self, data):
201                self.current_field.append(data)
202
203       
204        handler = SvnXMLLogHandler()
205        parseString(log.getvalue(), handler)
206        return handler.changesets
207   
208    def _applyChangeset(self, root, changeset):
209        svnup = SvnUpdate(working_dir=root)
210        out = svnup(output=True, entry='.', revision=changeset.revision)       
211        result = []
212        for line in out:
213            if len(line)>2 and line[0] == 'C' and line[1] == ' ':
214                result.append(line[2:-1])
215           
216        return result
217       
218    ## SyncronizableTargetWorkingDir
219
220    def _addEntry(self, root, entry):
221        """
222        Add a new entry, maybe registering the directory as well.
223        """
224
225        from os.path import split, join, exists
226
227        basedir = split(entry)[0]
228        if basedir and not exists(join(basedir, '.svn')):
229            self._addEntry(root, basedir)
230
231        c = SvnAdd(working_dir=root)
232        c(entry=entry)
233
234    def _checkoutUpstreamRevision(self, basedir, repository, module, revision):
235        """
236        Concretely do the checkout of the upstream revision.
237        """
238       
239        from os.path import join, exists
240       
241        wdir = join(basedir, module)
242
243        if not exists(wdir):
244            svnco = SvnCheckout(working_dir=basedir)
245            svnco(output=True, repository=repository,
246                  wc=module, revision=revision)
247           
248        return SvnInfo(working_dir=wdir)(entry='.')['Revision']
249   
250    def _commit(self,root, date, author, remark, changelog=None, entries=None):
251        """
252        Commit the changeset.
253        """
254
255        c = SvnCommit(working_dir=root)
256       
257        logmessage = remark + '\n'
258        if changelog:
259            logmessage = logmessage + changelog + '\n'
260           
261        if entries:
262            entries = ' '.join(entries)
263        else:
264            entries = '.'
265           
266        c(logmessage=logmessage, entries=entries)
267       
268    def _removeEntry(self, root, entry):
269        """
270        Remove an entry.
271        """
272
273        c = SvnRemove(working_dir=root)
274        c(entry=entry)
275
276    def _renameEntry(self, root, oldentry, newentry):
277        """
278        Rename an entry.
279        """
280
281        c = SvnMv(working_dir=root)
282        c(old=oldentry, new=newentry)
283
284    def _initializeWorkingDir(self, root, module, addentry=None):
285        """
286        Add the given directory to an already existing svn working tree.
287        """
288
289        from os.path import exists, join
290
291        if not exists(join(root, '.svn')):
292            raise TargetInitializationFailure("'%s' should already be under SVN" % root)
293
294        SyncronizableTargetWorkingDir._initializeWorkingDir(self, root, module,
295                                                            SvnAdd)
Note: See TracBrowser for help on using the repository browser.