chiark / gitweb /
d5dbd48b711a481ce5fbaec6138b7c8deb4ed7c8
[stgit] / stgit / lib / stack.py
1 """A Python class hierarchy wrapping the StGit on-disk metadata."""
2
3 import os.path
4 from stgit import exception, utils
5 from stgit.lib import git, stackupgrade
6 from stgit.config import config
7
8 class StackException(exception.StgException):
9     """Exception raised by L{stack} objects."""
10
11 class Patch(object):
12     """Represents an StGit patch. This class is mainly concerned with
13     reading and writing the on-disk representation of a patch."""
14     def __init__(self, stack, name):
15         self.__stack = stack
16         self.__name = name
17     name = property(lambda self: self.__name)
18     @property
19     def __ref(self):
20         return 'refs/patches/%s/%s' % (self.__stack.name, self.__name)
21     @property
22     def __log_ref(self):
23         return self.__ref + '.log'
24     @property
25     def commit(self):
26         return self.__stack.repository.refs.get(self.__ref)
27     @property
28     def old_commit(self):
29         """Return the previous commit for this patch."""
30         fn = os.path.join(self.__compat_dir, 'top.old')
31         if not os.path.isfile(fn):
32             return None
33         return self.__stack.repository.get_commit(utils.read_string(fn))
34     @property
35     def __compat_dir(self):
36         return os.path.join(self.__stack.directory, 'patches', self.__name)
37     def __write_compat_files(self, new_commit, msg):
38         """Write files used by the old infrastructure."""
39         def write(name, val, multiline = False):
40             fn = os.path.join(self.__compat_dir, name)
41             if val:
42                 utils.write_string(fn, val, multiline)
43             elif os.path.isfile(fn):
44                 os.remove(fn)
45         def write_patchlog():
46             try:
47                 old_log = [self.__stack.repository.refs.get(self.__log_ref)]
48             except KeyError:
49                 old_log = []
50             cd = git.CommitData(tree = new_commit.data.tree, parents = old_log,
51                                 message = '%s\t%s' % (msg, new_commit.sha1))
52             c = self.__stack.repository.commit(cd)
53             self.__stack.repository.refs.set(self.__log_ref, c, msg)
54             return c
55         d = new_commit.data
56         write('authname', d.author.name)
57         write('authemail', d.author.email)
58         write('authdate', d.author.date)
59         write('commname', d.committer.name)
60         write('commemail', d.committer.email)
61         write('description', d.message)
62         write('log', write_patchlog().sha1)
63         write('top', new_commit.sha1)
64         write('bottom', d.parent.sha1)
65         try:
66             old_top_sha1 = self.commit.sha1
67             old_bottom_sha1 = self.commit.data.parent.sha1
68         except KeyError:
69             old_top_sha1 = None
70             old_bottom_sha1 = None
71         write('top.old', old_top_sha1)
72         write('bottom.old', old_bottom_sha1)
73     def __delete_compat_files(self):
74         if os.path.isdir(self.__compat_dir):
75             for f in os.listdir(self.__compat_dir):
76                 os.remove(os.path.join(self.__compat_dir, f))
77             os.rmdir(self.__compat_dir)
78         try:
79             # this compatibility log ref might not exist
80             self.__stack.repository.refs.delete(self.__log_ref)
81         except KeyError:
82             pass
83     def set_commit(self, commit, msg):
84         self.__write_compat_files(commit, msg)
85         self.__stack.repository.refs.set(self.__ref, commit, msg)
86     def delete(self):
87         self.__delete_compat_files()
88         self.__stack.repository.refs.delete(self.__ref)
89     def is_applied(self):
90         return self.name in self.__stack.patchorder.applied
91     def is_empty(self):
92         return self.commit.data.is_nochange()
93
94 class PatchOrder(object):
95     """Keeps track of patch order, and which patches are applied.
96     Works with patch names, not actual patches."""
97     def __init__(self, stack):
98         self.__stack = stack
99         self.__lists = {}
100     def __read_file(self, fn):
101         return tuple(utils.read_strings(
102             os.path.join(self.__stack.directory, fn)))
103     def __write_file(self, fn, val):
104         utils.write_strings(os.path.join(self.__stack.directory, fn), val)
105     def __get_list(self, name):
106         if not name in self.__lists:
107             self.__lists[name] = self.__read_file(name)
108         return self.__lists[name]
109     def __set_list(self, name, val):
110         val = tuple(val)
111         if val != self.__lists.get(name, None):
112             self.__lists[name] = val
113             self.__write_file(name, val)
114     applied = property(lambda self: self.__get_list('applied'),
115                        lambda self, val: self.__set_list('applied', val))
116     unapplied = property(lambda self: self.__get_list('unapplied'),
117                          lambda self, val: self.__set_list('unapplied', val))
118     hidden = property(lambda self: self.__get_list('hidden'),
119                       lambda self, val: self.__set_list('hidden', val))
120     all = property(lambda self: self.applied + self.unapplied + self.hidden)
121     all_visible = property(lambda self: self.applied + self.unapplied)
122
123     @staticmethod
124     def create(stackdir):
125         """Create the PatchOrder specific files
126         """
127         utils.create_empty_file(os.path.join(stackdir, 'applied'))
128         utils.create_empty_file(os.path.join(stackdir, 'unapplied'))
129         utils.create_empty_file(os.path.join(stackdir, 'hidden'))
130
131 class Patches(object):
132     """Creates L{Patch} objects. Makes sure there is only one such object
133     per patch."""
134     def __init__(self, stack):
135         self.__stack = stack
136         def create_patch(name):
137             p = Patch(self.__stack, name)
138             p.commit # raise exception if the patch doesn't exist
139             return p
140         self.__patches = git.ObjectCache(create_patch) # name -> Patch
141     def exists(self, name):
142         try:
143             self.get(name)
144             return True
145         except KeyError:
146             return False
147     def get(self, name):
148         return self.__patches[name]
149     def new(self, name, commit, msg):
150         assert not name in self.__patches
151         p = Patch(self.__stack, name)
152         p.set_commit(commit, msg)
153         self.__patches[name] = p
154         return p
155
156 class Stack(git.Branch):
157     """Represents an StGit stack (that is, a git branch with some extra
158     metadata)."""
159     __repo_subdir = 'patches'
160
161     def __init__(self, repository, name):
162         git.Branch.__init__(self, repository, name)
163         self.__patchorder = PatchOrder(self)
164         self.__patches = Patches(self)
165         if not stackupgrade.update_to_current_format_version(repository, name):
166             raise StackException('%s: branch not initialized' % name)
167     patchorder = property(lambda self: self.__patchorder)
168     patches = property(lambda self: self.__patches)
169     @property
170     def directory(self):
171         return os.path.join(self.repository.directory, self.__repo_subdir, self.name)
172     @property
173     def base(self):
174         if self.patchorder.applied:
175             return self.patches.get(self.patchorder.applied[0]
176                                     ).commit.data.parent
177         else:
178             return self.head
179     @property
180     def top(self):
181         """Commit of the topmost patch, or the stack base if no patches are
182         applied."""
183         if self.patchorder.applied:
184             return self.patches.get(self.patchorder.applied[-1]).commit
185         else:
186             # When no patches are applied, base == head.
187             return self.head
188     def head_top_equal(self):
189         if not self.patchorder.applied:
190             return True
191         return self.head == self.patches.get(self.patchorder.applied[-1]).commit
192
193     def set_parents(self, remote, branch):
194         if remote:
195             self.set_parent_remote(remote)
196         if branch:
197             self.set_parent_branch(branch)
198
199     @classmethod
200     def initialise(cls, repository, name = None):
201         """Initialise a Git branch to handle patch series.
202
203         @param repository: The L{Repository} where the L{Stack} will be created
204         @param name: The name of the L{Stack}
205         """
206         if not name:
207             name = repository.current_branch_name
208         # make sure that the corresponding Git branch exists
209         git.Branch(repository, name)
210
211         dir = os.path.join(repository.directory, cls.__repo_subdir, name)
212         compat_dir = os.path.join(dir, 'patches')
213         if os.path.exists(dir):
214             raise StackException('%s: branch already initialized' % name)
215
216         # create the stack directory and files
217         utils.create_dirs(dir)
218         utils.create_dirs(compat_dir)
219         PatchOrder.create(dir)
220         config.set(stackupgrade.format_version_key(name),
221                    str(stackupgrade.FORMAT_VERSION))
222
223         return repository.get_stack(name)
224
225     @classmethod
226     def create(cls, repository, name,
227                create_at = None, parent_remote = None, parent_branch = None):
228         """Create and initialise a Git branch returning the L{Stack} object.
229
230         @param repository: The L{Repository} where the L{Stack} will be created
231         @param name: The name of the L{Stack}
232         @param create_at: The Git id used as the base for the newly created
233             Git branch
234         @param parent_remote: The name of the remote Git branch
235         @param parent_branch: The name of the parent Git branch
236         """
237         git.Branch.create(repository, name, create_at = create_at)
238         stack = cls.initialise(repository, name)
239         stack.set_parents(parent_remote, parent_branch)
240         return stack
241
242 class Repository(git.Repository):
243     """A git L{Repository<git.Repository>} with some added StGit-specific
244     operations."""
245     def __init__(self, *args, **kwargs):
246         git.Repository.__init__(self, *args, **kwargs)
247         self.__stacks = {} # name -> Stack
248     @property
249     def current_stack(self):
250         return self.get_stack()
251     def get_stack(self, name = None):
252         if not name:
253             name = self.current_branch_name
254         if not name in self.__stacks:
255             self.__stacks[name] = Stack(self, name)
256         return self.__stacks[name]