source: tracdarcs/tracdarcs/repository.py @ 66

Revision 66, 13.1 KB checked in by Erik Swanson <erik.swanson@…>, 6 years ago (diff)

Fix ticket #22

Line 
1# -*- coding: iso-8859-1 -*-
2#
3# Copyright (C) 2005 Edgewall Software
4# Copyright (C) 2006 K.S.Sreeram <sreeram@tachyontech.net>
5#
6# This software is licensed as described in the file COPYING, which
7# you should have received as part of this distribution. The terms
8# are also available at http://trac.edgewall.com/license.html.
9#
10# This software consists of voluntary contributions made by many
11# individuals. For the exact contribution history, see the revision
12# history and logs, available at http://projects.edgewall.com/trac/.
13#
14# Author: K.S.Sreeram <sreeram@tachyontech.net>
15
16import os, StringIO, mimetypes
17from datetime import tzinfo, timedelta, datetime
18
19from trac.util import TracError
20from trac.versioncontrol import Repository, Node, Changeset, \
21        NoSuchChangeset, NoSuchNode
22
23from command import DarcsCommand
24from updatedb import update_darcsdb
25from dbutil import NODE_FILE_TYPE, NODE_DIR_TYPE
26from dbutil import CHANGE_ADDED, CHANGE_REMOVED, CHANGE_MOVED, \
27        CHANGE_EDITED, CHANGE_MOVED_EDITED
28from dbutil import query_nodes_for_revision
29
30'''
31This module implements the trac versioncontrol backend API.
32The API consists of 3 classes: DarcsRepository, DarcsNode
33and DarcsChangeset.
34
35Please see the docs in trac.versioncontrol.api for the interface
36which is implemented by this module.
37'''
38
39ZERO = timedelta(0)
40HOUR = timedelta(hours=1)
41
42class UTC(tzinfo):
43    """UTC"""
44
45    def utcoffset(self, dt):
46        return ZERO
47
48    def tzname(self, dt):
49        return "UTC"
50
51    def dst(self, dt):
52        return ZERO
53
54utc = UTC()
55
56# mapping from node types used by the darcs backend and the types
57# used by the trac api
58_node_type_map = {
59        NODE_FILE_TYPE : Node.FILE,
60        NODE_DIR_TYPE : Node.DIRECTORY
61        }
62
63# mapping from change types used by the darcs backend and the types
64# used by the trac api
65_change_map = {
66        CHANGE_ADDED : Changeset.ADD,
67        CHANGE_REMOVED : Changeset.DELETE,
68        CHANGE_MOVED : Changeset.MOVE,
69        CHANGE_EDITED : Changeset.EDIT,
70        #FIXME: treat moved&edited as just moved?
71        CHANGE_MOVED_EDITED : Changeset.MOVE
72        }
73
74def to_utc_datetime(dt):
75    if isinstance(dt, long):
76        dt = datetime.strptime(str(dt), '%Y%m%d%H%M%S')
77    return dt.replace(tzinfo = utc)
78
79def get_node_type( db, node_id ) :
80    c = db.cursor()
81    c.execute( 'SELECT node_type FROM darcs_nodes ' +
82            'WHERE node_id = %s', (node_id,) )
83    return c.fetchone()[0]
84
85def get_prev_path_rev( db, node_id, rev ) :
86    c = db.cursor()
87    c.execute( 'SELECT path,rev FROM darcs_node_changes ' +
88            'WHERE node_id = %s AND rev < %s ' +
89            'ORDER BY rev DESC LIMIT 1', (node_id,rev) )
90    path,rev = c.fetchone()
91    return path,rev
92
93class DarcsRepository( Repository ) :
94    def __init__( self, db, path, log, config ) :
95        Repository.__init__( self, path, None, log )
96        self.db = db
97        self.path = path
98        self.log = log
99        self.config = config
100        self.__cmd = DarcsCommand( 'darcs', path, log )
101        # import any new changesets, if any
102        update_darcsdb( db, self.__cmd, log )
103
104    def close( self ) :
105        pass
106
107    def get_changeset( self, rev ) :
108        rev = self.normalize_rev( rev )
109        return DarcsChangeset( self.db, rev )
110
111    def get_node( self, path, rev=None ) :
112        path = self.normalize_path( path )
113        rev = self.normalize_rev( rev )
114        # compute node_id, node_type and last_rev and then
115        # create a DarcsNode object.
116        # 'last_rev' is the last revision <= rev where this
117        # node was modified.
118        if path == '/' :
119            node_id = None
120            node_type = NODE_DIR_TYPE
121            last_rev = rev
122        else :
123            c = self.db.cursor()
124            q = query_nodes_for_revision( rev )
125            q += ' AND dnc.path = %s'
126            c.execute( q, (path,) )
127            row = c.fetchone()
128            if row is None :
129                raise NoSuchNode( path, rev )
130            node_id,last_rev = row[:2]
131            node_type = get_node_type( self.db, node_id )
132        return DarcsNode( node_id, node_type, path, last_rev,
133                self.db, self.__cmd )
134
135    def get_oldest_rev( self ) :
136        if self.get_youngest_rev() is None :
137            return None
138        return 1
139
140    def get_youngest_rev( self ) :
141        c = self.db.cursor()
142        c.execute( 'SELECT rev FROM darcs_revisions ' +
143                'ORDER BY rev DESC LIMIT 1' )
144        row = c.fetchone()
145        return row and row[0] or None
146
147    def previous_rev( self, rev ) :
148        rev = self.normalize_rev( rev )
149        if rev > 1 :
150            return rev-1
151        return None
152
153    def next_rev( self, rev, path='' ) :
154        rev = self.normalize_rev( rev )
155        if rev < self.get_youngest_rev() :
156            return rev+1
157        return None
158
159    def rev_older_than( self, rev1, rev2 ) :
160        return self.normalize_rev(rev1) < self.normalize_rev(rev2)
161
162    def get_path_history( self, path, rev=None, limit=None ) :
163        # FIXME: this is not correct
164        return self.get_node( path, rev ).get_history( limit )
165
166    def normalize_path( self, path ) :
167        return path and path.strip('/') or '/'
168
169    def normalize_rev( self, rev ) :
170        youngest = self.get_youngest_rev()
171        if rev is None or rev == "" :
172            return youngest
173        rev = int( rev )
174        if rev > youngest :
175            rev = youngest
176        return rev
177
178    def get_changes( self, old_path, old_rev, new_path, new_rev,
179            ignore_ancestry=1 ) :
180        old_path = self.normalize_path( old_path )
181        old_rev = self.normalize_rev( old_rev )
182        new_path = self.normalize_path( new_path )
183        new_rev = self.normalize_rev( new_rev )
184        old_node = self.get_node( old_path, old_rev )
185        new_node = self.get_node( new_path, new_rev )
186
187        node_id = old_node._get_node_id()
188        if node_id != new_node._get_node_id() :
189            raise TracError( 'Node mismatch: base is %s in rev %d '
190                    'and target is %s in rev %d' % (old_path,old_rev,
191                        new_path,new_rev) )
192
193        if old_node.kind == Node.FILE :
194            if old_node.rev != new_node.rev :
195                yield (old_node,new_node,Node.FILE,Changeset.EDIT)
196            return
197
198        c = self.db.cursor()
199        c.execute( 'SELECT rev,path FROM darcs_node_changes '
200                'WHERE node_id = %s AND rev >= %s AND rev <= %s',
201                (node_id,old_rev,new_rev) )
202        node_set = dict()
203        node_list = []
204        c1 = self.db.cursor()
205        for rev,path in c :
206            c1.execute( 'SELECT node_id FROM darcs_node_changes '
207                    'WHERE rev = %s AND path LIKE %s',
208                    (rev,path+'/%') )
209            for nid, in c1 :
210                if nid not in node_set :
211                    node_set[nid] = 1
212                    node_list.append( nid )
213        for nid in node_list :
214            old_node = new_node = None
215            c1.execute( 'SELECT rev,path FROM darcs_node_changes '
216                    'WHERE node_id = %s AND rev < %s '
217                    'ORDER BY rev DESC LIMIT 1',
218                    (nid,old_rev) )
219            row = c1.fetchone()
220            if row is not None :
221                rev,path = row
222                old_node = self.get_node( path, rev )
223            c1.execute( 'SELECT rev,path,the_change FROM darcs_node_changes '
224                    'WHERE node_id = %s AND rev >= %s AND rev <= %s '
225                    'ORDER BY rev DESC LIMIT 1',
226                    (nid,old_rev,new_rev) )
227            rev,path,change = c1.fetchone()
228            if change != CHANGE_REMOVED :
229                new_node = self.get_node( path, rev )
230            assert (old_node is not None) or (new_node is not None)
231            kind = old_node and old_node.kind or new_node.kind
232            if old_node is None :
233                change = Changeset.ADD
234            elif new_node is None :
235                change = Changeset.DELETE
236            elif old_node.path != new_node.path :
237                change = Changeset.MOVE
238            else :
239                change = Changeset.EDIT
240            yield (old_node,new_node,kind,change)
241
242    def sync( self, rev_callback=None ) :
243        # This is called by trac-admin resync
244        update_darcsdb(self.db, self.__cmd, self.log, rev_callback=rev_callback)
245
246class DarcsNode( Node ) :
247    def __init__( self, node_id, node_type, path, rev,
248            db, cmd ) :
249        kind = _node_type_map[node_type]
250        Node.__init__( self, path, rev, kind )
251        self.__node_id = node_id
252        self.__node_type = node_type
253        self.__db = db
254        self.__cmd = cmd
255        self.created_path = path
256        self.created_rev = rev
257
258    def _get_node_id( self ) :
259        return self.__node_id
260
261    def get_content( self ) :
262        if self.__node_type == NODE_DIR_TYPE :
263            return None
264        c = self.__db.cursor()
265        # check if the file content is there in the cache
266        c.execute( 'SELECT content FROM darcs_cache '
267                'WHERE node_id = %s AND rev = %s',
268                (self.__node_id,self.rev) )
269        row = c.fetchone()
270        if row is not None :
271            # if present just return it
272            data = str(buffer(row[0]))
273            return StringIO.StringIO( data )
274        # load the file content from the repo
275        c.execute( 'SELECT hash FROM darcs_revisions ' +
276                'WHERE rev = %s', (self.rev,) )
277        hash = c.fetchone()[0]
278        data = self.__cmd.cat( hash, self.path )
279
280        # save the file content in the cache
281
282        # UGLY HACK: the following line is required otherwise
283        # db.commit() (pysqlite-2.3.2,winxp) throws
284        # OperationalError: 'SQL logic error or missing database'
285        #self.__db.cnx.cnx.isolation_level = None
286        # END UGLY HACK
287
288        c = self.__db.cursor()
289        c.execute( 'INSERT INTO darcs_cache(node_id,rev,content) '
290                'VALUES (%s,%s,%s)',
291                (self.__node_id,self.rev,buffer(data)) )
292        self.__db.commit()
293        return StringIO.StringIO( data )
294
295    def get_entries( self ) :
296        if self.__node_type == NODE_FILE_TYPE :
297            return
298        q = query_nodes_for_revision( self.rev )
299        if self.__node_id is None :
300            q += ' AND dnc.parent_id IS NULL'
301        else :
302            q += ' AND dnc.parent_id = %d' % self.__node_id
303        c = self.__db.cursor()
304        c.execute( q )
305        for node_id,rev,path,_ in c :
306            node_type = get_node_type( self.__db, node_id )
307            yield DarcsNode( node_id, node_type, path, rev,
308                    self.__db, self.__cmd )
309
310    def get_history( self, limit=None ) :
311        if self.path == '/' :
312            for i in range(self.rev,0,-1) :
313                yield ( self.path, i, Changeset.EDIT )
314            return
315        c = self.__db.cursor()
316        q = 'SELECT path,rev,the_change FROM darcs_node_changes ' + \
317                'WHERE node_id = %s AND rev <= %s ' + \
318                'ORDER BY rev DESC'
319        if limit is not None :
320            q += ' LIMIT %d' % limit
321        c.execute( q, (self.__node_id,self.rev) )
322        for path,rev,change in c :
323            yield ( path, rev, _change_map[change] )
324
325    def get_properties( self ) :
326        return {}
327
328    def get_content_length( self ) :
329        if self.isdir :
330            return None
331        return len(self.get_content().read())
332
333    def get_content_type( self ) :
334        if self.isdir :
335            return None
336        return mimetypes.guess_type( self.path )[0]
337
338    def get_name( self ) :
339        return os.path.split( self.path )[1]
340
341    def get_last_modified( self ) :
342        if self.__node_id is None :
343            return 0
344        c = self.__db.cursor()
345        c.execute( 'SELECT rev FROM darcs_node_changes ' +
346                'WHERE node_id = %s AND rev = %s',
347                (self.__node_id,self.rev) )
348        rev = c.fetchone()[0]
349        c.execute( 'SELECT time FROM darcs_revisions ' +
350                'WHERE rev = %s', (rev,) )
351        return to_utc_datetime(c.fetchone()[0])
352
353class DarcsChangeset( Changeset ) :
354    def __init__( self, db, rev ) :
355        c = db.cursor()
356        c.execute( 'SELECT author,time,name,comment ' +
357                'FROM darcs_revisions WHERE rev = %s', (rev,) )
358        row = c.fetchone()
359        if row is None :
360            raise NoSuchChangeset( rev )
361        author,date,name,comment = row
362        date = to_utc_datetime(date)
363        msg = name
364        if comment :
365            msg += '\n' + comment
366        Changeset.__init__( self, rev, msg, author, date )
367        self.__db = db
368
369    def get_changes( self ) :
370        c = self.__db.cursor()
371        c.execute( 'SELECT node_id,path,the_change FROM darcs_node_changes ' +
372                'WHERE rev = %s', (self.rev,) )
373        for node_id,path,change in c :
374            node_type = get_node_type( self.__db, node_id )
375            kind = _node_type_map[node_type]
376            if change == CHANGE_ADDED :
377                prev_path = prev_rev = None
378            else :
379                prev_path,prev_rev = get_prev_path_rev( self.__db,
380                        node_id, self.rev )
381            change = _change_map[change]
382            yield (path,kind,change,prev_path,prev_rev)
383
384    def get_properties( self ) :
385        return []
Note: See TracBrowser for help on using the repository browser.