~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to shelf.py

  • Committer: Aaron Bentley
  • Date: 2008-11-05 00:11:09 UTC
  • mto: This revision was merged to the branch mainline in revision 678.
  • Revision ID: aaron@aaronbentley.com-20081105001109-yt2dp0h5h3ssb7xt
Restore runtime ignore for .shelf

Show diffs side-by-side

added added

removed removed

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