18a8d18ac32a9c5995de90e9e09a424df149942d
[redakcja.git] / lib / hg.py
1 # -*- coding: utf-8 -*-
2 import os
3 import codecs
4 from mercurial import localrepo, ui, match, node, encoding, util
5 import mercurial.merge, mercurial.error
6
7 encoding.encoding = 'utf-8'
8
9
10 def clearpath(path):
11     return unicode(path).encode("utf-8")
12
13 class Repository(object):
14     """Abstrakcja repozytorium Mercurial. DziaƂa z Mercurial w wersji 1.3.1."""
15     
16     def __init__(self, path, create=False):
17         self.ui = ui.ui()
18         self.ui.config('ui', 'quiet', 'true')
19         self.ui.config('ui', 'interactive', 'false')
20         
21         self.real_path = os.path.realpath(path)
22         self.repo = self.open_repository(self.real_path, create)
23         self._pending_files = []
24     
25     def open_repository(self, path, create=False):
26         if os.path.isdir(path):
27             try:
28                 return localrepo.localrepository(self.ui, path)
29             except mercurial.error.RepoError:
30                 # dir is not an hg repo, we must init it
31                 if create:
32                     return localrepo.localrepository(self.ui, path, create=1)
33         elif create:
34             os.makedirs(path)
35             return localrepo.localrepository(self.ui, path, create=1)
36         raise RepositoryDoesNotExist("Repository %s does not exist." % path)
37         
38     def file_list(self, branch):
39         return self.in_branch(lambda: self._file_list(), branch)
40
41     def _file_list(self):
42         return list(self.repo[None])
43     
44     def get_file(self, path, branch):
45         return self.in_branch(lambda: self._get_file(path), branch)
46
47     def _get_file(self, path):
48         path = clearpath(path)
49
50         if not self._file_exists(path):
51             raise RepositoryException("File not availble in this branch.")
52         
53         return self.repo.wread(path)
54
55     def file_exists(self, path, branch):
56         return self.in_branch(lambda: self._file_exists(path), branch)
57
58     def _file_exists(self, path):
59         path = clearpath(path)
60         return self.repo.dirstate[path] != "?"
61
62     def write_file(self, path, value, branch):
63         return self.in_branch(lambda: self._write_file(path, value), branch)
64
65     def _write_file(self, path, value):
66         path = clearpath(path)
67         return self.repo.wwrite(path, value, [])
68
69     def add_file(self, path, value, branch):
70         return self.in_branch(lambda: self._add_file(path, value), branch)
71
72     def _add_file(self, path, value):
73         path = clearpath(path)
74         self._write_file(path, value)
75         return self.repo.add( [path] )
76
77     def _commit(self, message, user=None):
78         return self.repo.commit(text=message, user=user)
79     
80     def commit(self, message, branch, user=None):
81         return self.in_branch(lambda: self._commit(message, key=key, user=user), branch)
82
83     def in_branch(self, action, bname):
84         wlock = self.repo.wlock()
85         try:
86             old = self._switch_to_branch(bname)
87             try:
88                 # do some stuff
89                 return action()
90             finally:
91                 self._switch_to_branch(old)
92         finally:
93             wlock.release()
94
95     def _switch_to_branch(self, bname, create=True):
96         wlock = self.repo.wlock()
97         try:
98             current = self.repo[None].branch()
99             if current == bname:
100                 return current
101             try:
102                 tip = self.repo.branchtags()[bname]
103             except KeyError, ke:
104                 if not create: raise ke
105                 
106                 # create the branch on the fly
107
108                 # first switch to default branch
109                 default_tip = self.repo.branchtags()['default']
110                 mercurial.merge.update(self.repo, default_tip, False, True, None)
111
112                 # set the dirstate to new branch
113                 self.repo.dirstate.setbranch(bname)
114                 self._commit('Initial commit for automatic branch "%s".' % bname, user="django-admin")
115
116                 # collect the new tip
117                 tip = self.repo.branchtags()[bname]
118
119             upstats = mercurial.merge.update(self.repo, tip, False, True, None)
120             return current
121         except KeyError, ke:
122             raise RepositoryException("Can't switch to branch '%s': no such branch." % bname , ke)
123         except util.Abort, ae:
124             raise RepositoryException("Can't switch to branch '%s': %s"  % (bname, ae.message), ae)
125         finally:
126             wlock.release()
127
128     def write_lock(self):
129         """Returns w write lock to the repository."""
130         return self.repo.wlock()
131
132
133 class RepositoryException(Exception):
134
135     def __init__(self, msg, cause=None):
136         Exception.__init__(self, msg)
137         self.cause = cause
138
139 class RepositoryDoesNotExist(RepositoryException):
140     pass