~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to shelf.py

  • Committer: Aaron Bentley
  • Date: 2006-06-27 14:36:32 UTC
  • Revision ID: abentley@panoramicfeedback.com-20060627143632-0f4114d7b0a8d7d9
Fix zap for checkouts of branches with no parents

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/python
 
2
 
 
3
import os
 
4
import sys
 
5
import subprocess
 
6
from datetime import datetime
 
7
from errors import CommandError, PatchFailed
 
8
from hunk_selector import ShelveHunkSelector, UnshelveHunkSelector
 
9
from patchsource import PatchSource, FilePatchSource
 
10
 
 
11
class Shelf(object):
 
12
    MESSAGE_PREFIX = "# Shelved patch: "
 
13
 
 
14
    _paths = {
 
15
        'base'          : '.shelf',
 
16
        'shelves'       : '.shelf/shelves',
 
17
        'current-shelf' : '.shelf/current-shelf',
 
18
    }
 
19
 
 
20
    def __init__(self, base, name=None):
 
21
        self.base = base
 
22
        self.__setup()
 
23
 
 
24
        if name is None:
 
25
            current = os.path.join(self.base, self._paths['current-shelf'])
 
26
            name = open(current).read().strip()
 
27
 
 
28
        assert '\n' not in name
 
29
        self.name = name
 
30
 
 
31
        self.dir = os.path.join(self.base, self._paths['shelves'], name)
 
32
        if not os.path.isdir(self.dir):
 
33
            os.mkdir(self.dir)
 
34
 
 
35
    def __setup(self):
 
36
        # Create required directories etc.
 
37
        for dir in [self._paths['base'], self._paths['shelves']]:
 
38
            dir = os.path.join(self.base, dir)
 
39
            if not os.path.isdir(dir):
 
40
                os.mkdir(dir)
 
41
 
 
42
        current = os.path.join(self.base, self._paths['current-shelf'])
 
43
        if not os.path.exists(current):
 
44
            f = open(current, 'w')
 
45
            f.write('default')
 
46
            f.close()
 
47
 
 
48
    def make_default(self):
 
49
        f = open(os.path.join(self.base, self._paths['current-shelf']), 'w')
 
50
        f.write(self.name)
 
51
        f.close()
 
52
        self.log("Default shelf is now '%s'\n" % self.name)
 
53
 
 
54
    def log(self, msg):
 
55
        sys.stderr.write(msg)
 
56
 
 
57
    def delete(self, patch):
 
58
        path = self.__path_from_user(patch)
 
59
        os.rename(path, '%s~' % path)
 
60
 
 
61
    def display(self, patch=None):
 
62
        if patch is None:
 
63
            path = self.last_patch()
 
64
        else:
 
65
            path = self.__path_from_user(patch)
 
66
        sys.stdout.write(open(path).read())
 
67
 
 
68
    def list(self):
 
69
        indexes = self.__list()
 
70
        self.log("Patches on shelf '%s':" % self.name)
 
71
        if len(indexes) == 0:
 
72
            self.log(' None\n')
 
73
            return
 
74
        self.log('\n')
 
75
        for index in indexes:
 
76
            msg = self.get_patch_message(self.__path(index))
 
77
            if msg is None:
 
78
                msg = "No message saved with patch."
 
79
            self.log(' %.2d: %s\n' % (index, msg))
 
80
 
 
81
    def __path_from_user(self, patch_id):
 
82
        try:
 
83
            patch_index = int(patch_id)
 
84
        except (TypeError, ValueError):
 
85
            raise CommandError("Invalid patch name '%s'" % patch_id)
 
86
 
 
87
        path = self.__path(patch_index)
 
88
 
 
89
        if not os.path.exists(path):
 
90
            raise CommandError("Patch '%s' doesn't exist on shelf %s!" % \
 
91
                        (patch_id, self.name))
 
92
 
 
93
        return path
 
94
 
 
95
    def __path(self, index):
 
96
        return os.path.join(self.dir, '%.2d' % index)
 
97
 
 
98
    def next_patch(self):
 
99
        indexes = self.__list()
 
100
 
 
101
        if len(indexes) == 0:
 
102
            next = 0
 
103
        else:
 
104
            next = indexes[-1] + 1
 
105
        return self.__path(next)
 
106
 
 
107
    def __list(self):
 
108
        patches = os.listdir(self.dir)
 
109
        indexes = []
 
110
        for f in patches:
 
111
            if f.endswith('~'):
 
112
                continue # ignore backup files
 
113
            try:
 
114
                indexes.append(int(f))
 
115
            except ValueError:
 
116
                self.log("Warning: Ignoring junk file '%s' on shelf.\n" % f)
 
117
 
 
118
        indexes.sort()
 
119
        return indexes
 
120
 
 
121
    def last_patch(self):
 
122
        indexes = self.__list()
 
123
 
 
124
        if len(indexes) == 0:
 
125
            return None
 
126
 
 
127
        return self.__path(indexes[-1])
 
128
 
 
129
    def get_patch_message(self, patch_path):
 
130
        patch = open(patch_path, 'r').read()
 
131
 
 
132
        if not patch.startswith(self.MESSAGE_PREFIX):
 
133
            return None
 
134
        return patch[len(self.MESSAGE_PREFIX):patch.index('\n')]
 
135
 
 
136
    def unshelve(self, patch_source, patch_name=None, all=False, force=False):
 
137
        self._check_upgrade()
 
138
 
 
139
        if patch_name is None:
 
140
            patch_path = self.last_patch()
 
141
        else:
 
142
            patch_path = self.__path_from_user(patch_name)
 
143
 
 
144
        if patch_path is None:
 
145
            raise CommandError("No patch found on shelf %s" % self.name)
 
146
 
 
147
        patches = FilePatchSource(patch_path).readpatches()
 
148
        if all:
 
149
            to_unshelve = patches
 
150
            to_remain = []
 
151
        else:
 
152
            to_unshelve, to_remain = UnshelveHunkSelector(patches).select()
 
153
 
 
154
        if len(to_unshelve) == 0:
 
155
            raise CommandError('Nothing to unshelve')
 
156
 
 
157
        message = self.get_patch_message(patch_path)
 
158
        if message is None:
 
159
            message = "No message saved with patch."
 
160
        self.log('Unshelving from %s/%s: "%s"\n' % \
 
161
                (self.name, os.path.basename(patch_path), message))
 
162
 
 
163
        try:
 
164
            self._run_patch(to_unshelve, dry_run=True)
 
165
            self._run_patch(to_unshelve)
 
166
        except PatchFailed:
 
167
            try:
 
168
                self._run_patch(to_unshelve, strip=1, dry_run=True)
 
169
                self._run_patch(to_unshelve, strip=1)
 
170
            except PatchFailed:
 
171
                if force:
 
172
                    self.log('Warning: Unshelving failed, forcing as ' \
 
173
                             'requested. Shelf will not be modified.\n')
 
174
                    try:
 
175
                        self._run_patch(to_unshelve)
 
176
                    except PatchFailed:
 
177
                        pass
 
178
                    return
 
179
                raise CommandError("Your shelved patch no " \
 
180
                    "longer applies cleanly to the working tree!")
 
181
 
 
182
        # Backup the shelved patch
 
183
        os.rename(patch_path, '%s~' % patch_path)
 
184
 
 
185
        if len(to_remain) > 0:
 
186
            f = open(patch_path, 'w')
 
187
            for patch in to_remain:
 
188
                f.write(str(patch))
 
189
            f.close()
 
190
 
 
191
    def shelve(self, patch_source, all=False, message=None):
 
192
        self._check_upgrade()
 
193
 
 
194
        patches = patch_source.readpatches()
 
195
 
 
196
        if all:
 
197
            to_shelve = patches
 
198
        else:
 
199
            to_shelve = ShelveHunkSelector(patches).select()[0]
 
200
 
 
201
        if len(to_shelve) == 0:
 
202
            raise CommandError('Nothing to shelve')
 
203
 
 
204
        if message is None:
 
205
            timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
 
206
            message = "Changes shelved on %s" % timestamp
 
207
 
 
208
        patch_path = self.next_patch()
 
209
        self.log('Shelving to %s/%s: "%s"\n' % \
 
210
                (self.name, os.path.basename(patch_path), message))
 
211
 
 
212
        f = open(patch_path, 'a')
 
213
 
 
214
        assert '\n' not in message
 
215
        f.write("%s%s\n" % (self.MESSAGE_PREFIX, message))
 
216
 
 
217
        for patch in to_shelve:
 
218
            f.write(str(patch))
 
219
 
 
220
        f.flush()
 
221
        os.fsync(f.fileno())
 
222
        f.close()
 
223
 
 
224
        try:
 
225
            self._run_patch(to_shelve, reverse=True, dry_run=True)
 
226
            self._run_patch(to_shelve, reverse=True)
 
227
        except PatchFailed:
 
228
            try:
 
229
                self._run_patch(to_shelve, reverse=True, strip=1, dry_run=True)
 
230
                self._run_patch(to_shelve, reverse=True, strip=1)
 
231
            except PatchFailed:
 
232
                raise CommandError("Failed removing shelved changes from the"
 
233
                    "working tree!")
 
234
 
 
235
    def _run_patch(self, patches, strip=0, reverse=False, dry_run=False):
 
236
        args = ['patch', '-d', self.base, '-s', '-p%d' % strip, '-f']
 
237
        if reverse:
 
238
            args.append('-R')
 
239
        if dry_run:
 
240
            args.append('--dry-run')
 
241
            stdout = stderr = subprocess.PIPE
 
242
        else:
 
243
            stdout = stderr = None
 
244
 
 
245
        process = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=stdout,
 
246
                        stderr=stderr)
 
247
        for patch in patches:
 
248
            process.stdin.write(str(patch))
 
249
 
 
250
        process.communicate()
 
251
 
 
252
        result = process.wait()
 
253
        if result != 0:
 
254
            raise PatchFailed()
 
255
 
 
256
        return result
 
257
 
 
258
    def _check_upgrade(self):
 
259
        if len(self._list_old_shelves()) > 0:
 
260
            raise CommandError("Old format shelves found, either upgrade " \
 
261
                    "or remove them!")
 
262
 
 
263
    def _list_old_shelves(self):
 
264
        import glob
 
265
        stem = os.path.join(self.base, '.bzr-shelf')
 
266
 
 
267
        patches = glob.glob(stem)
 
268
        patches.extend(glob.glob(stem + '-*[!~]'))
 
269
 
 
270
        if len(patches) == 0:
 
271
            return []
 
272
 
 
273
        def patch_index(name):
 
274
            if name == stem:
 
275
                return 0
 
276
            return int(name[len(stem) + 1:])
 
277
 
 
278
        # patches might not be sorted in the right order
 
279
        patch_ids = []
 
280
        for patch in patches:
 
281
            if patch == stem:
 
282
                patch_ids.append(0)
 
283
            else:
 
284
                patch_ids.append(int(patch[len(stem) + 1:]))
 
285
 
 
286
        patch_ids.sort()
 
287
 
 
288
        patches = []
 
289
        for id in patch_ids:
 
290
            if id == 0:
 
291
                patches.append(stem)
 
292
            else:
 
293
                patches.append('%s-%s' % (stem, id))
 
294
 
 
295
        return patches
 
296
 
 
297
    def upgrade(self):
 
298
        patches = self._list_old_shelves()
 
299
 
 
300
        if len(patches) == 0:
 
301
            self.log('No old-style shelves found to upgrade.\n')
 
302
            return
 
303
 
 
304
        for patch in patches:
 
305
            old_file = open(patch, 'r')
 
306
            new_path = self.next_patch()
 
307
            new_file = open(new_path, 'w')
 
308
            new_file.write(old_file.read())
 
309
            old_file.close()
 
310
            new_file.close()
 
311
            self.log('Copied %s to %s/%s\n' % (os.path.basename(patch),
 
312
                self.name, os.path.basename(new_path)))
 
313
            os.rename(patch, patch + '~')