~abentley/bzrtools/bzrtools.dev

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#!/usr/bin/python

import os
import sys
import subprocess
from datetime import datetime
from errors import CommandError, PatchFailed
from hunk_selector import ShelveHunkSelector, UnshelveHunkSelector
from patchsource import PatchSource, FilePatchSource

class Shelf(object):
    MESSAGE_PREFIX = "# Shelved patch: "

    _paths = {
        'base'          : '.shelf',
        'shelves'       : '.shelf/shelves',
        'current-shelf' : '.shelf/current-shelf',
    }

    def __init__(self, base, name=None):
        self.base = base
        self.__setup()

        if name is None:
            current = os.path.join(self.base, self._paths['current-shelf'])
            name = open(current).read().strip()

        assert '\n' not in name
        self.name = name

        self.dir = os.path.join(self.base, self._paths['shelves'], name)
        if not os.path.isdir(self.dir):
            os.mkdir(self.dir)

    def __setup(self):
        # Create required directories etc.
        for dir in [self._paths['base'], self._paths['shelves']]:
            dir = os.path.join(self.base, dir)
            if not os.path.isdir(dir):
                os.mkdir(dir)

        current = os.path.join(self.base, self._paths['current-shelf'])
        if not os.path.exists(current):
            f = open(current, 'w')
            f.write('default')
            f.close()

    def make_default(self):
        f = open(os.path.join(self.base, self._paths['current-shelf']), 'w')
        f.write(self.name)
        f.close()
        self.log("Default shelf is now '%s'\n" % self.name)

    def log(self, msg):
        sys.stderr.write(msg)

    def delete(self, patch):
        path = self.__path_from_user(patch)
        os.rename(path, '%s~' % path)

    def display(self, patch):
        path = self.__path_from_user(patch)
        sys.stdout.write(open(path).read())

    def list(self):
        indexes = self.__list()
        self.log("Patches on shelf '%s':" % self.name)
        if len(indexes) == 0:
            self.log(' None\n')
            return
        self.log('\n')
        for index in indexes:
            msg = self.get_patch_message(self.__path(index))
            if msg is None:
                msg = "No message saved with patch."
            self.log(' %.2d: %s\n' % (index, msg))

    def __path_from_user(self, patch_id):
        try:
            patch_index = int(patch_id)
        except TypeError:
            raise CommandError("Invalid patch name '%s'" % patch_id)

        path = self.__path(patch_index)

        if not os.path.exists(path):
            raise CommandError("Patch '%s' doesn't exist on shelf %s!" % \
                        (patch_id, self.name))

        return path

    def __path(self, index):
        return os.path.join(self.dir, '%.2d' % index)

    def next_patch(self):
        indexes = self.__list()

        if len(indexes) == 0:
            next = 0
        else:
            next = indexes[-1] + 1
        return self.__path(next)

    def __list(self):
        patches = os.listdir(self.dir)
        indexes = []
        for f in patches:
            if f.endswith('~'):
                continue # ignore backup files
            try:
                indexes.append(int(f))
            except ValueError:
                self.log("Warning: Ignoring junk file '%s' on shelf.\n" % f)

        indexes.sort()
        return indexes

    def last_patch(self):
        indexes = self.__list()

        if len(indexes) == 0:
            return None

        return self.__path(indexes[-1])

    def get_patch_message(self, patch_path):
        patch = open(patch_path, 'r').read()

        if not patch.startswith(self.MESSAGE_PREFIX):
            return None
        return patch[len(self.MESSAGE_PREFIX):patch.index('\n')]

    def unshelve(self, patch_source, all=False, force=False):
        self._check_upgrade()

        patch_name = self.last_patch()

        if patch_name is None:
            raise CommandError("No patch found on shelf %s" % self.name)

        patches = FilePatchSource(patch_name).readpatches()
        if all:
            to_unshelve = patches
            to_remain = []
        else:
            to_unshelve, to_remain = UnshelveHunkSelector(patches).select()

        if len(to_unshelve) == 0:
            raise CommandError('Nothing to unshelve')

        message = self.get_patch_message(patch_name)
        if message is None:
            message = "No message saved with patch."
        self.log('Unshelving from %s/%s: "%s"\n' % \
                (self.name, os.path.basename(patch_name), message))

        try:
            self._run_patch(to_unshelve, dry_run=True)
            self._run_patch(to_unshelve)
        except PatchFailed:
            try:
                self._run_patch(to_unshelve, strip=1, dry_run=True)
                self._run_patch(to_unshelve, strip=1)
            except PatchFailed:
                if force:
                    self.log('Warning: Unshelving failed, forcing as ' \
                             'requested. Shelf will not be modified.\n')
                    try:
                        self._run_patch(to_unshelve)
                    except PatchFailed:
                        pass
                    return
                raise CommandError("Your shelved patch no " \
                    "longer applies cleanly to the working tree!")

        # Backup the shelved patch
        os.rename(patch_name, '%s~' % patch_name)

        if len(to_remain) > 0:
            f = open(patch_name, 'w')
            for patch in to_remain:
                f.write(str(patch))
            f.close()

    def shelve(self, patch_source, all=False, message=None):
        self._check_upgrade()

        patches = patch_source.readpatches()

        if all:
            to_shelve = patches
        else:
            to_shelve = ShelveHunkSelector(patches).select()[0]

        if len(to_shelve) == 0:
            raise CommandError('Nothing to shelve')

        if message is None:
            timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            message = "Changes shelved on %s" % timestamp

        patch_name = self.next_patch()
        self.log('Shelving to %s/%s: "%s"\n' % \
                (self.name, os.path.basename(patch_name), message))

        f = open(patch_name, 'a')

        assert '\n' not in message
        f.write("%s%s\n" % (self.MESSAGE_PREFIX, message))

        for patch in to_shelve:
            f.write(str(patch))

        f.flush()
        os.fsync(f.fileno())
        f.close()

        try:
            self._run_patch(to_shelve, reverse=True, dry_run=True)
            self._run_patch(to_shelve, reverse=True)
        except PatchFailed:
            try:
                self._run_patch(to_shelve, reverse=True, strip=1, dry_run=True)
                self._run_patch(to_shelve, reverse=True, strip=1)
            except PatchFailed:
                raise CommandError("Failed removing shelved changes from the"
                    "working tree!")

    def _run_patch(self, patches, strip=0, reverse=False, dry_run=False):
        args = ['patch', '-d', self.base, '-s', '-p%d' % strip, '-f']
        if reverse:
            args.append('-R')
        if dry_run:
            args.append('--dry-run')
            stdout = stderr = subprocess.PIPE
        else:
            stdout = stderr = None

        process = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=stdout,
                        stderr=stderr)
        for patch in patches:
            process.stdin.write(str(patch))

        process.communicate()

        result = process.wait()
        if result != 0:
            raise PatchFailed()

        return result

    def _check_upgrade(self):
        if len(self._list_old_shelves()) > 0:
            raise CommandError("Old format shelves found, either upgrade " \
                    "or remove them!")

    def _list_old_shelves(self):
        import glob
        stem = os.path.join(self.base, '.bzr-shelf')

        patches = glob.glob(stem)
        patches.extend(glob.glob(stem + '-*[!~]'))

        if len(patches) == 0:
            return []

        def patch_index(name):
            if name == stem:
                return 0
            return int(name[len(stem) + 1:])

        # patches might not be sorted in the right order
        patch_ids = []
        for patch in patches:
            if patch == stem:
                patch_ids.append(0)
            else:
                patch_ids.append(int(patch[len(stem) + 1:]))

        patch_ids.sort()

        patches = []
        for id in patch_ids:
            if id == 0:
                patches.append(stem)
            else:
                patches.append('%s-%s' % (stem, id))

        return patches

    def upgrade(self):
        patches = self._list_old_shelves()

        if len(patches) == 0:
            self.log('No old-style shelves found to upgrade.\n')
            return

        for patch in patches:
            old_file = open(patch, 'r')
            new_path = self.next_patch()
            new_file = open(new_path, 'w')
            new_file.write(old_file.read())
            old_file.close()
            new_file.close()
            self.log('Copied %s to %s/%s\n' % (os.path.basename(patch),
                self.name, os.path.basename(new_path)))
            os.rename(patch, patch + '~')