~ubuntu-branches/ubuntu/oneiric/gquilt/oneiric

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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# -*- python -*-

### Copyright (C) 2005 Peter Williams <pwil3058@bigpond.net.au>

### This program is free software; you can redistribute it and/or modify
### it under the terms of the GNU General Public License as published by
### the Free Software Foundation; version 2 of the License only.

### This program is distributed in the hope that it will be useful,
### but WITHOUT ANY WARRANTY; without even the implied warranty of
### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
### GNU General Public License for more details.

### You should have received a copy of the GNU General Public License
### along with this program; if not, write to the Free Software
### Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

# This file provides access to "quilt" functionality required by "gquilt"

import gquilt_utils, os.path, os, gquilt_const, gquilt_tool, gquilt_pfuns, re, errno

class quilt_commands(gquilt_utils.cmd_list):
    def __init__(self):
        gquilt_utils.cmd_list.__init__(self)
    def _get_commands(self):
        res, sop, eop = gquilt_utils.run_cmd("quilt")
        if sop == "":
            return None
        lines = sop.splitlines()
        index = 2
        cmds = []
        while True:
            lcmds = lines[index].split()
            if len(lcmds) > 0:
                cmds += lcmds
            else:
                cmds.sort()
                return cmds
            index += 1

def find_patchfns():
    binloc = gquilt_utils.which("quilt")
    if binloc is None:
        return None
    bi = binloc.find("bin" + os.path.sep + "quilt")
    if bi == -1:
        return None
    res = os.path.join(binloc[0:bi], "share", "quilt", "scripts", "patchfns")
    if not os.path.exists(res) or not os.path.isfile(res):
        return None
    return res

patchfns = find_patchfns()
if patchfns is None:
    qbsfe = None
else:
    qbsfe = 'bash -c ". ' + os.environ['GQUILT_LIB_DIR'] + '/qbsfe.sh" gquilt ' + patchfns

def internal(cmd, input=None):
    if qbsfe is None:
        raise "quilt_specific_error", "Couldn't find patchfns"
    return gquilt_utils.run_cmd(" ".join([qbsfe, cmd]), input)

# run a command and log the result to the provided console
def _exec_console_cmd(console, cmd, error=gquilt_const.ERROR):
    res, so, se = gquilt_utils.run_cmd(cmd)
    if console is not None:
        console.log_cmd(cmd + "\n", so, se)
    if res != 0:
        return (error, so, se)
    else:
        return (gquilt_const.OK, so, se)

# Some useful private quilt functions (that shouldn't fail)
def _patch_file_name(patch):
    res, so, se = internal(" ".join(["patch_file_name", patch]))
    if res != 0:
        raise "quilt_specific_error", se
    return so[:-1]

def _patch_backup_dir(patch):
    res, so, se = internal(" ".join(["backup_file_name", patch, "x"]))
    if res != 0:
        raise "quilt_specific_error", se
    return so[:-3]

def _patch_backup_file(patch, filename):
    res, so, se = internal(" ".join(["backup_file_name", patch, filename]))
    if res != 0:
        raise "quilt_specific_error", se
    return so[:-1]

def _patch_files_may_have_changed(patch):
    res, so, se = internal(" ".join(["files_may_have_changed", patch]))
    if res != 0:
        raise "quilt_specific_error", se
    return res == 0

def _convert_pop_res(res, so, se):
    if res != gquilt_const.OK:
        if re.search("needs to be refreshed first", so + se):
            res = gquilt_const.ERROR_REFRESH
        elif re.search("\(refresh it or enforce with -f\)", so + se):
            res = gquilt_const.ERROR_FORCE_OR_REFRESH
        else:
            res = gquilt_const.ERROR
    return (res, so, se)

def _convert_push_res(res, so, se):
    if res != gquilt_const.OK:
        if re.search("\(forced; needs refresh\)", so + se):
            res = gquilt_const.OK
        elif re.search("needs to be refreshed first", so + se):
            res = gquilt_const.ERROR_REFRESH
        elif re.search("\(enforce with -f\)", so + se):
            res = gquilt_const.ERROR_FORCE
        else:
            res = gquilt_const.ERROR
    return (res, so, se)

def _convert_import_res(res, so, se):
    if res != gquilt_const.OK:
        if re.search("Replace with -f", so + se):
            res = gquilt_const.ERROR_FORCE
    return (res, so, se)

def _quilt_version_ge(rmajor, rminor):
    res, so, se = gquilt_utils.run_cmd("quilt --version")
    if res != 0:
        return False
    vstrs = so.split(".")
    amajor = int(vstrs[0])
    if  amajor > rmajor:
        return True
    elif amajor < rmajor:
        return False
    else:
        return int(vstrs[1]) >= rminor

def _patch_dir(dir=None):
    try:
        pd = os.environ['QUILT_PATCHES']
    except:
        pd = "patches"
    if dir is None:
        dir = os.getcwd()
    return dir + "/" + pd
    
# Now implement the tool interface for quilt
class interface(gquilt_tool.interface):
    def __init__(self):
        gquilt_tool.interface.__init__(self, "quilt")
    def new_playground(self, dir=None):
        patch_dir = _patch_dir(dir)
        if not os.path.exists(patch_dir):
            try:
                os.makedirs(patch_dir)
            except os.error, value:
               return (gquilt_const.ERROR, "", value[1])
        return gquilt_utils.run_cmd("touch " + os.path.join(patch_dir, "series"))
    def is_playground(self, dir=None):
        patch_dir = _patch_dir(dir)
        return os.path.exists(os.path.join(patch_dir, "series"))
    def is_patch_applied(self, patch):
        res, so, se = internal("is_applied " + patch)
        return res == 0
    def patch_file_name(self, patch):
        return _patch_file_name(patch)
    def top_patch(self):
        res, so, se = gquilt_utils.run_cmd("quilt top")
        if res == 0 or (se.strip() == "" and so.strip() == ""):
            return so.strip()
        elif res == 512 and so.strip() == "":
            return ""
        else:
            raise "quilt_specific_error", se
    def last_patch_in_series(self):
        res, op, err = gquilt_utils.run_cmd("quilt series")
        if res != 0:
            raise "quilt_specific_error", se
        return op.splitlines()[-1]
    def count_ok_meld(selfself, count):
        return count == 1
    def display_files_diff_in_viewer(self, viewer, files, patch=None):
        difffld = "--diff=" + viewer
        if patch is None:
            pid = os.spawnlp(os.P_NOWAIT, "quilt", "quilt", "diff", difffld, files[0])
        else:
            pid = os.spawnlp(os.P_NOWAIT, "quilt", "quilt", "diff", difffld, "-P", patch, files[0])
    def get_patch_status(self, patch):
        if not self.is_patch_applied(patch):
            return (gquilt_const.OK, gquilt_const.NOT_APPLIED, "")
        patch_fn = _patch_file_name(patch)
        patch_dirn = _patch_backup_dir(patch)
        if (not os.path.exists(patch_fn)) or os.path.exists(patch_dirn + "~refresh"):
            needs_refresh = True
        else:
            timestamp_fn = patch_dirn + "/.timestamp"
            if not os.path.exists(timestamp_fn):
                needs_refresh = True
            else:
                timestamp = os.stat(timestamp_fn).st_mtime
                if timestamp > os.stat(patch_fn).st_mtime:
                    needs_refresh = True
                else:
                    needs_refresh = False
                    res, files, err = gquilt_utils.run_cmd("quilt files " + patch)
                    for f in files.splitlines():
                        if timestamp < os.stat(f).st_mtime:
                            needs_refresh = True
                            break
        res, tp, se = self.get_top_patch()
        if tp == patch:
            if needs_refresh:
                return (gquilt_const.OK, gquilt_const.TOP_PATCH_NEEDS_REFRESH, "")
            else:
                return (gquilt_const.OK, gquilt_const.TOP_PATCH, "")
        else:
            if needs_refresh:
                return (gquilt_const.OK, gquilt_const.APPLIED_NEEDS_REFRESH, "")
            else:
                return (gquilt_const.OK, gquilt_const.APPLIED, "")
    def get_series(self):
        res, op, err = gquilt_utils.run_cmd("quilt series -v")
        if res != 0:
            return (gquilt_const.ERROR, (None, None), err)
        series = []
        for line in op.splitlines():
            if line[0] == " ":
                series.append((line[2:], gquilt_const.NOT_APPLIED))
            else:
                pn = line[2:]
                #res, status, err = self.get_patch_status(pn)
                #series.append((pn, status))
                series.append((pn, gquilt_const.APPLIED))
        try:
            patch_dir = os.environ['QUILT_PATCHES']
        except:
            patch_dir = ""
        return (gquilt_const.OK, (patch_dir, series), "")
    def get_diff(self, filelist=[], patch=None):
        if patch is None:
            cmd = "quilt diff"
        else:
            cmd = "quilt diff -P " + patch
        res, so, se = gquilt_utils.run_cmd(" ".join([cmd, " ".join(filelist)]))
        if res != 0:
            if not self.is_patch_applied(patch):
                res, diff = gquilt_pfuns.get_patch_diff_lines(self.patch_file_name(patch))
                if res:
                    return (gquilt_const.OK, "\n".join(diff), [])
            return (gquilt_const.ERROR, so, se)
        return (res, so, se)
    def get_combined_diff(self, start_patch=None, end_patch=None):
        cmd = "quilt diff --sort --combine "
        if start_patch is None:
            cmd += "-"
        else:
            cmd += start_patch
        if end_patch is not None:
            cms += " -P " + end_patch
        res, so, se = gquilt_utils.run_cmd(cmd)
        if res != 0:
            return (gquilt_const.ERROR, so, se)
        return (res, so, se)
    def get_patch_files(self, patch=None, withstatus=True):
        if self.top_patch() == "":
            return (gquilt_const.OK, "", "")
        cmd = "quilt files"
        if withstatus:
            cmd += " -v"
        if patch is not None:
            cmd += " " + patch
        res, so, se = gquilt_utils.run_cmd(cmd)
        if res != 0:
            if patch and not self.is_patch_applied(patch):
                patchfile = self.patch_file_name(patch)
                ok, filelist = gquilt_pfuns.get_patch_files(patchfile, withstatus)
                if ok:
                    return (gquilt_const.OK, filelist, "")
                else:
                    return (gquilt_const.ERROR, "", filelist)
            return (gquilt_const.ERROR, so, se)
        if withstatus:
            filelist = []
            for line in so.splitlines():
                if line[0] == "+":
                    filelist.append((line[2:], gquilt_const.ADDED))
                elif line[0] == "-":
                    filelist.append((line[2:], gquilt_const.DELETED))
                else:
                    filelist.append((line[2:], gquilt_const.EXTANT))
        else:
            filelist = so.splitlines()
        return (res, filelist, se)
    def do_rename_patch(self, console, patch, newname):
        if quilt_commands().has_cmd("rename"):
            cmd = "quilt rename "
            if patch is not None:
                if _quilt_version_ge(0, 43):
                    cmd += "-P " + patch + " "
                else:
                    cmd += "-p " + patch + " "
            cmd += newname
            res, so, se = gquilt_utils.run_cmd(cmd)
            if console is not None:
                console.log_cmd(cmd + "\n", so, se)
            if res != 0:
                return (gquilt_const.ERROR, so, se)
            else:
                return (gquilt_const.OK, so, se)
        else:
            newname_pfn = _patch_file_name(newname)
            newname_backup_dir =  _patch_backup_dir(newname)
            if os.path.exists(newname_pfn) or os.path.exists(newname_backup_dir):
                return (gquilt_const.ERROR, "", 'Patch rename failed. "' + newname + '" is already being used')
            if patch is None:
                res, patch, se = self.get_top_patch()
                if res != gquilt_const.OK:
                    return (res, patch, se)
            patchname_pfn = _patch_file_name(patch)
            if self.is_patch_applied(patch):
                res, so, se = internal(" ".join(["rename_in_db",  patch, newname]))
                if res != 0:
                    return (gquilt_const.ERROR, so, se)
                os.rename(_patch_backup_dir(patch), newname_backup_dir)
                if os.path.exists(patchname_pfn):
                    os.rename(patchname_pfn, newname_pfn)
            else:
                if os.path.exists(patchname_pfn):
                    os.rename(patchname_pfn, newname_pfn)
            res, so, se = internal(" ".join(["rename_in_series", patch, newname]))
            if res != 0:
                return (gquilt_const.ERROR, so, se)
            else:
                return (gquilt_const.OK, so, se)

    def do_pop_patch(self, console, force=False):
        cmd = "quilt pop"
        if force:
            cmd += " -f"
        res, so, se = _exec_console_cmd(console, cmd)
        return _convert_pop_res(res, so, se)
    def do_push_patch(self, console, force=False):
        cmd = "quilt push"
        if force:
            cmd += " -f"
        res, so, se = _exec_console_cmd(console, cmd)
        return _convert_push_res(res, so, se)
    def do_pop_to_patch(self, console, patch=None):
        cmd = "quilt pop"
        if patch is not None:
            if patch is "":
                cmd += " -a"
            else:
                cmd += " " + patch
        res, so, se = _exec_console_cmd(console, cmd)
        return _convert_pop_res(res, so, se)
    def do_push_to_patch(self, console, patch=None):
        cmd = "quilt push"
        if patch is not None:
            if patch is "":
                cmd += " -a"
            else:
                cmd += " " + patch
        res, so, se = _exec_console_cmd(console, cmd)
        return _convert_push_res(res, so, se)
    def do_refresh_patch(self, console, patch=None, force=False):
        cmd = "quilt refresh"
        if force:
            cmd += " -f"
        if patch is not None:
            cmd = " ".join([cmd, patch])
        res, so, se = _exec_console_cmd(console, cmd)
        if res != gquilt_const.OK:
            if re.search("Enforce refresh with -f", so + se):
                res = gquilt_const.ERROR_FORCE
            else:
                res = gquilt_const.ERROR
        return (res, so, se)
    def do_create_new_patch(self, console, name):
        return _exec_console_cmd(console, " ".join(["quilt", "new", name]))
    def do_import_patch(self, console, filename, patchname=None, force=False):
        if patchname:
            cmd = "quilt import -P %s " % patchname
        else:
            cmd = "quilt import "
        if force:
            cmd += "-f -d n "
        res, so, se = _exec_console_cmd(console, cmd + filename)
        return _convert_import_res(res, so, se)
    def do_merge_patch(self, console, patch):
        filename = _patch_file_name(patch)
        res, so, se = self.do_merge_patch_file(console, filename)
        if res == 0:
            self.do_delete_patch(console, patch)
        return (res, so, se)
    def do_merge_patch_file(self, console, filename):
        return _exec_console_cmd(console, " < ".join(["quilt fold", filename]))
    def do_delete_patch(self, console, patch):
        return _exec_console_cmd(console, " ".join(["quilt", "delete", patch]))
    def do_add_files_to_patch(self, console, filelist, patch=None):
        if patch == None:
            cmd = "quilt add"
        else:
            if _quilt_version_ge(0, 43):
                cmd = "quilt add -P " + patch
            else:
                cmd = "quilt add -p " + patch
        # quilt will screw up semi silently if you try to add directories to a patch
        for f in filelist:
            if os.path.isdir(f):
                return (gquilt_const.ERROR, "", f + ' is a directory.\n "quilt" does not handle adding directories to patches\n')
        return _exec_console_cmd(console, " ".join([cmd, " ".join(filelist)]))
    def do_remove_files_from_patch(self, console, filelist, patch=None):
        if patch == None:
            cmd = "quilt remove"
        else:
            if _quilt_version_ge(0, 43):
                cmd = "quilt remove -P " + patch
            else:
                cmd = "quilt remove -p " + patch
        # quilt will screw up semi silently if you try to remove directories to a patch
        for f in filelist:
            if os.path.isdir(f):
                return (gquilt_const.ERROR, "", f + ' is a directory.\n "quilt" does not handle removing directories from patches\n')
        return _exec_console_cmd(console, " ".join([cmd, " ".join(filelist)]))
    def do_exec_tool_cmd(self, console, cmd):
        return _exec_console_cmd(console, " ".join(["quilt", cmd]))