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
|
#!/usr/bin/python
import os
import sys
import subprocess
from errors import CommandError
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.remove(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_hunks=False):
patch_name = self.last_patch()
if patch_name is None:
raise CommandError("No patch found on shelf %s" % self.name)
hunks = FilePatchSource(patch_name).readhunks()
if all_hunks:
to_unshelve = hunks
to_remain = []
else:
to_unshelve, to_remain = UnshelveHunkSelector(hunks).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 CommandError:
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 hunk in to_remain:
f.write(str(hunk))
f.close()
def shelve(self, patch_source, all_hunks=False, message=None):
from datetime import datetime
hunks = patch_source.readhunks()
if all_hunks:
to_shelve = hunks
else:
to_shelve = ShelveHunkSelector(hunks).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))
patch = open(patch_name, 'a')
assert '\n' not in message
patch.write("%s%s\n" % (self.MESSAGE_PREFIX, message))
for hunk in to_shelve:
patch.write(str(hunk))
patch.flush()
os.fsync(patch.fileno())
patch.close()
self._run_patch(to_shelve, reverse=True)
def _run_patch(self, patches, reverse=False, dry_run=False):
args = ['patch', '-d', self.base, '-s', '-p1', '-f']
if reverse:
args.append('-R')
if dry_run:
args.append('--dry-run')
process = subprocess.Popen(args, stdin=subprocess.PIPE)
for patch in patches:
process.stdin.write(str(patch))
process.stdin.close()
result = process.wait()
if result != 0:
raise CommandError("Failed applying patches!")
return result
|