~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to shelf.py

  • Committer: Aaron Bentley
  • Date: 2013-08-20 03:02:43 UTC
  • Revision ID: aaron@aaronbentley.com-20130820030243-r8v1xfbcnd8f10p4
Fix zap command for 2.6/7

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