~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to shelf.py

  • Committer: Michael Ellerman
  • Date: 2006-03-22 07:03:32 UTC
  • mto: (0.3.1 shelf-dev)
  • mto: This revision was merged to the branch mainline in revision 367.
  • Revision ID: michael@ellerman.id.au-20060322070332-ab379ffa63244cc8
Add test machinery to cope with subdirectories.

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