~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
 
 
15
 
DEFAULT_IGNORE.append('./.bzr-shelf*')
16
 
 
17
 
class QuitException(Exception):
18
 
    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
19
9
 
20
10
class Shelf(object):
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):
 
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):
48
265
            if name == stem:
49
266
                return 0
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
 
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()
109
290
 
110
291
        if len(patches) == 0:
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
 
 
 
292
            self.log('No old-style shelves found to upgrade.\n')
 
293
            return
 
294
 
 
295
        for patch in patches:
 
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 + '~')