~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to shelf.py

  • Committer: Michael Ellerman
  • Date: 2005-11-28 06:24:55 UTC
  • mto: (0.3.1 shelf-dev) (325.1.2 bzrtools)
  • mto: This revision was merged to the branch mainline in revision 334.
  • Revision ID: michael@ellerman.id.au-20051128062455-9da2ff70dd70e65c
Add tests for new shelf layout.

Shelves are now named .bzr/x-shelf/default/0x where x increases.

Also add a test for doing shelve/unshelve multiple times.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#!/usr/bin/python
2
2
 
 
3
from patches import parse_patches
3
4
import os
4
5
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
 
6
import string
 
7
import glob
 
8
import bzrlib
 
9
from bzrlib.commands import Command
 
10
from bzrlib.branch import Branch
 
11
from bzrlib import DEFAULT_IGNORE
 
12
from hunk_selector import HunkSelector
 
13
from diffstat import DiffStat
 
14
 
 
15
DEFAULT_IGNORE.append('./.bzr-shelf*')
 
16
 
 
17
class QuitException(Exception):
 
18
    pass
10
19
 
11
20
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:
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):
 
21
    def __init__(self, location):
 
22
        self.branch = Branch.open_containing(location)[0]
 
23
 
 
24
    def shelf_suffix(self, index):
 
25
        if index == 0:
 
26
            return ""
 
27
        else:
 
28
            return "-%d" % index
 
29
 
 
30
    def next_shelf(self):
 
31
        def name_sequence():
 
32
            i = 0
 
33
            while True:
 
34
                yield self.shelf_suffix(i)
 
35
                i = i + 1
 
36
 
 
37
        stem = os.path.join(self.branch.base, '.bzr-shelf')
 
38
        for end in name_sequence():
 
39
            name = stem + end
 
40
            if not os.path.exists(name):
 
41
                return name
 
42
 
 
43
    def last_shelf(self):
 
44
        stem = os.path.join(self.branch.base, '.bzr-shelf')
 
45
        shelves = glob.glob(stem)
 
46
        shelves.extend(glob.glob(stem + '-*'))
 
47
        def shelf_index(name):
274
48
            if name == stem:
275
49
                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()
 
50
            return int(name[len(stem)+1:])
 
51
        shelvenums = [shelf_index(f) for f in shelves]
 
52
        shelvenums.sort()
 
53
 
 
54
        if len(shelvenums) == 0:
 
55
            return None
 
56
        return stem + self.shelf_suffix(shelvenums[-1])
 
57
 
 
58
    def get_shelf_message(self, shelf):
 
59
        prefix = "# shelf: "
 
60
        if not shelf.startswith(prefix):
 
61
            return None
 
62
        return shelf[len(prefix):shelf.index('\n')]
 
63
 
 
64
    def unshelve(self):
 
65
        shelf = self.last_shelf()
 
66
 
 
67
        if shelf is None:
 
68
            raise Exception("No shelf found in '%s'" % self.branch.base)
 
69
 
 
70
        patch = open(shelf, 'r').read()
 
71
 
 
72
        print >>sys.stderr, "Reapplying shelved patches",
 
73
        message = self.get_shelf_message(patch)
 
74
        if message is not None:
 
75
            print >>sys.stderr, ' "%s"' % message
 
76
        else:
 
77
            print >>sys.stderr, ""
 
78
        pipe = os.popen('patch -d %s -s -p0' % self.branch.base, 'w')
 
79
        pipe.write(patch)
 
80
        pipe.flush()
 
81
 
 
82
        if pipe.close() is not None:
 
83
            raise Exception("Failed running patch!")
 
84
 
 
85
        os.remove(shelf)
 
86
 
 
87
        diff_stat = DiffStat(self.get_patches(None, None))
 
88
        print 'Diff status is now:\n', diff_stat
 
89
 
 
90
        return True
 
91
 
 
92
    def get_patches(self, revision, file_list):
 
93
        from StringIO import StringIO
 
94
        from bzrlib.diff import show_diff
 
95
        out = StringIO()
 
96
        show_diff(self.branch, revision, specific_files=file_list, output=out)
 
97
        out.seek(0)
 
98
        return out.readlines()
 
99
 
 
100
    def shelve(self, all_hunks=False, message=None, revision=None,
 
101
             file_list=None):
 
102
        patches = parse_patches(self.get_patches(revision, file_list))
 
103
 
 
104
        if not all_hunks:
 
105
            try:
 
106
                patches = HunkSelector(patches).select()
 
107
            except QuitException:
 
108
                return False
299
109
 
300
110
        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 + '~')
 
111
            print >>sys.stderr, 'Nothing to shelve'
 
112
            return True
 
113
 
 
114
        shelf = self.next_shelf()
 
115
        print >>sys.stderr, "Saving shelved patches to", shelf
 
116
        shelf = open(shelf, 'a')
 
117
        if message is not None:
 
118
            assert '\n' not in message
 
119
            shelf.write("# shelf: %s\n" % message)
 
120
        for patch in patches:
 
121
            shelf.write(str(patch))
 
122
 
 
123
        shelf.flush()
 
124
        os.fsync(shelf.fileno())
 
125
        shelf.close()
 
126
 
 
127
        print >>sys.stderr, "Reverting shelved patches"
 
128
        pipe = os.popen('patch -d %s -sR -p0' % self.branch.base, 'w')
 
129
        for patch in patches:
 
130
            pipe.write(str(patch))
 
131
        pipe.flush()
 
132
 
 
133
        if pipe.close() is not None:
 
134
            raise Exception("Failed running patch!")
 
135
 
 
136
        diff_stat = DiffStat(self.get_patches(None, None))
 
137
        print 'Diff status is now:\n', diff_stat
 
138
 
 
139
        return True
 
140