File: utils.py

package info (click to toggle)
stgit 0.18-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,728 kB
  • ctags: 1,741
  • sloc: python: 10,106; sh: 4,939; lisp: 2,678; makefile: 130; perl: 42
file content (366 lines) | stat: -rw-r--r-- 11,195 bytes parent folder | download
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
"""Common utility functions
"""

import errno, os, os.path, re, sys, tempfile
from stgit.exception import *
from stgit.config import config
from stgit.out import *

__copyright__ = """
Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>

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

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, see http://www.gnu.org/licenses/.
"""

def mkdir_file(filename, mode):
    """Opens filename with the given mode, creating the directory it's
    in if it doesn't already exist."""
    create_dirs(os.path.dirname(filename))
    return file(filename, mode)

def read_strings(filename):
    """Reads the lines from a file
    """
    f = file(filename, 'r')
    lines = [line.strip() for line in f.readlines()]
    f.close()
    return lines

def read_string(filename, multiline = False):
    """Reads the first line from a file
    """
    f = file(filename, 'r')
    if multiline:
        result = f.read()
    else:
        result = f.readline().strip()
    f.close()
    return result

def write_strings(filename, lines):
    """Write 'lines' sequence to file
    """
    f = file(filename, 'w+')
    f.writelines([line + '\n' for line in lines])
    f.close()

def write_string(filename, line, multiline = False):
    """Writes 'line' to file and truncates it
    """
    f = mkdir_file(filename, 'w+')
    if multiline:
        f.write(line)
    else:
        print >> f, line
    f.close()

def append_strings(filename, lines):
    """Appends 'lines' sequence to file
    """
    f = mkdir_file(filename, 'a+')
    for line in lines:
        print >> f, line
    f.close()

def append_string(filename, line):
    """Appends 'line' to file
    """
    f = mkdir_file(filename, 'a+')
    print >> f, line
    f.close()

def insert_string(filename, line):
    """Inserts 'line' at the beginning of the file
    """
    f = mkdir_file(filename, 'r+')
    lines = f.readlines()
    f.seek(0); f.truncate()
    print >> f, line
    f.writelines(lines)
    f.close()

def create_empty_file(name):
    """Creates an empty file
    """
    mkdir_file(name, 'w+').close()

def list_files_and_dirs(path):
    """Return the sets of filenames and directory names in a
    directory."""
    files, dirs = [], []
    for fd in os.listdir(path):
        full_fd = os.path.join(path, fd)
        if os.path.isfile(full_fd):
            files.append(fd)
        elif os.path.isdir(full_fd):
            dirs.append(fd)
    return files, dirs

def walk_tree(basedir):
    """Starting in the given directory, iterate through all its
    subdirectories. For each subdirectory, yield the name of the
    subdirectory (relative to the base directory), the list of
    filenames in the subdirectory, and the list of directory names in
    the subdirectory."""
    subdirs = ['']
    while subdirs:
        subdir = subdirs.pop()
        files, dirs = list_files_and_dirs(os.path.join(basedir, subdir))
        for d in dirs:
            subdirs.append(os.path.join(subdir, d))
        yield subdir, files, dirs

def strip_prefix(prefix, string):
    """Return string, without the prefix. Blow up if string doesn't
    start with prefix."""
    assert string.startswith(prefix)
    return string[len(prefix):]

def strip_suffix(suffix, string):
    """Return string, without the suffix. Blow up if string doesn't
    end with suffix."""
    assert string.endswith(suffix)
    return string[:-len(suffix)]

def remove_file_and_dirs(basedir, file):
    """Remove join(basedir, file), and then remove the directory it
    was in if empty, and try the same with its parent, until we find a
    nonempty directory or reach basedir."""
    os.remove(os.path.join(basedir, file))
    try:
        os.removedirs(os.path.join(basedir, os.path.dirname(file)))
    except OSError:
        # file's parent dir may not be empty after removal
        pass

def create_dirs(directory):
    """Create the given directory, if the path doesn't already exist."""
    if directory and not os.path.isdir(directory):
        create_dirs(os.path.dirname(directory))
        try:
            os.mkdir(directory)
        except OSError, e:
            if e.errno != errno.EEXIST:
                raise e

def rename(basedir, file1, file2):
    """Rename join(basedir, file1) to join(basedir, file2), not
    leaving any empty directories behind and creating any directories
    necessary."""
    full_file2 = os.path.join(basedir, file2)
    create_dirs(os.path.dirname(full_file2))
    os.rename(os.path.join(basedir, file1), full_file2)
    try:
        os.removedirs(os.path.join(basedir, os.path.dirname(file1)))
    except OSError:
        # file1's parent dir may not be empty after move
        pass

class EditorException(StgException):
    pass

def get_editor():
    for editor in [os.environ.get('GIT_EDITOR'),
                   config.get('stgit.editor'), # legacy
                   config.get('core.editor'),
                   os.environ.get('VISUAL'),
                   os.environ.get('EDITOR'),
                   'editor']:
        if editor:
            return editor

def call_editor(filename):
    """Run the editor on the specified filename."""
    cmd = '%s %s' % (get_editor(), filename)
    out.start('Invoking the editor: "%s"' % cmd)
    err = os.system(cmd)
    if err:
        raise EditorException, 'editor failed, exit code: %d' % err
    out.done()

def get_hook(repository, hook_name, extra_env={}):
    hook_path = os.path.join(repository.directory, 'hooks', hook_name)
    if not (os.path.isfile(hook_path) and os.access(hook_path, os.X_OK)):
        return None

    default_iw = repository.default_iw
    prefix_dir = os.path.relpath(os.getcwd(), default_iw.cwd)
    if prefix_dir == os.curdir:
        prefix = ''
    else:
        prefix = os.path.join(prefix_dir, '')
    extra_env = add_dict(extra_env, {'GIT_PREFIX': prefix})

    def hook(*parameters):
        argv = [hook_path]
        argv.extend(parameters)

        # On Windows, run the hook using "bash" explicitly
        if os.name != 'posix':
            argv.insert(0, 'bash')

        default_iw.run(argv, extra_env).run()

    hook.__name__ = hook_name
    return hook

def run_hook_on_string(hook, s, *args):
    if hook is not None:
        temp = tempfile.NamedTemporaryFile('wb', delete=False)
        try:
            try:
                temp.write(s)
            finally:
                temp.close()

            hook(temp.name, *args)

            output = open(temp.name, 'rb')
            try:
                s = output.read()
            finally:
                output.close()
        finally:
            os.unlink(temp.name)

    return s

def edit_string(s, filename):
    f = file(filename, 'w')
    f.write(s)
    f.close()
    call_editor(filename)
    f = file(filename)
    s = f.read()
    f.close()
    os.remove(filename)
    return s

def append_comment(s, comment, separator = '---'):
    return ('%s\n\n%s\nEverything following the line with "%s" will be'
            ' ignored\n\n%s' % (s, separator, separator, comment))

def strip_comment(s, separator = '---'):
    try:
        return s[:s.index('\n%s\n' % separator)]
    except ValueError:
        return s

def find_patch_name(patchname, unacceptable):
    """Find a patch name which is acceptable."""
    if unacceptable(patchname):
        suffix = 0
        while unacceptable('%s-%d' % (patchname, suffix)):
            suffix += 1
        patchname = '%s-%d' % (patchname, suffix)
    return patchname

def patch_name_from_msg(msg):
    """Return a string to be used as a patch name. This is generated
    from the top line of the string passed as argument."""
    if not msg:
        return None

    name_len = config.getint('stgit.namelength')
    if not name_len:
        name_len = 30

    subject_line = msg.split('\n', 1)[0].lstrip().lower()
    words = re.sub('[\W]+', ' ', subject_line).split()

    # use loop to avoid truncating the last name
    name = words and words[0] or 'unknown'
    for word in words[1:]:
        new = name + '-' + word
        if len(new) > name_len:
            break
        name = new

    return name

def make_patch_name(msg, unacceptable, default_name = 'patch'):
    """Return a patch name generated from the given commit message,
    guaranteed to make unacceptable(name) be false. If the commit
    message is empty, base the name on default_name instead."""
    patchname = patch_name_from_msg(msg)
    if not patchname:
        patchname = default_name
    return find_patch_name(patchname, unacceptable)

# any and all functions are builtin in Python 2.5 and higher, but not
# in 2.4.
if 'any' in dir(__builtins__):
    any = getattr(__builtins__, 'any')
else:
    def any(bools):
        for b in bools:
            if b:
                return True
        return False

if 'all' in dir(__builtins__):
    all = getattr(__builtins__, 'all')
else:
    def all(bools):
        for b in bools:
            if not b:
                return False
        return True

def add_sign_line(desc, sign_str, name, email):
    if not sign_str:
        return desc
    sign_str = '%s: %s <%s>' % (sign_str, name, email)
    if sign_str in desc:
        return desc
    desc = desc.rstrip()
    preamble, lastblank, lastpara = desc.rpartition('\n\n')
    is_signoff = re.compile(r'[A-Z][a-z]*(-[A-Za-z][a-z]*)*: ').match
    if not (lastblank and all(is_signoff(l) for l in lastpara.split('\n'))):
        desc = desc + '\n'
    return '%s\n%s\n' % (desc, sign_str)

def parse_name_email(address):
    """Return a tuple consisting of the name and email parsed from a
    standard 'name <email>' or 'email (name)' string."""
    address = re.sub(r'[\\"]', r'\\\g<0>', address)
    str_list = re.findall(r'^(.*)\s*<(.*)>\s*$', address)
    if not str_list:
        str_list = re.findall(r'^(.*)\s*\((.*)\)\s*$', address)
        if not str_list:
            return None
        return (str_list[0][1], str_list[0][0])
    return str_list[0]

def parse_name_email_date(address):
    """Return a tuple consisting of the name, email and date parsed
    from a 'name <email> date' string."""
    address = re.sub(r'[\\"]', r'\\\g<0>', address)
    str_list = re.findall('^(.*)\s*<(.*)>\s*(.*)\s*$', address)
    if not str_list:
        return None
    return str_list[0]

# Exit codes.
STGIT_SUCCESS = 0        # everything's OK
STGIT_GENERAL_ERROR = 1  # seems to be non-command-specific error
STGIT_COMMAND_ERROR = 2  # seems to be a command that failed
STGIT_CONFLICT = 3       # merge conflict, otherwise OK
STGIT_BUG_ERROR = 4      # a bug in StGit

def add_dict(d1, d2):
    """Return a new dict with the contents of both d1 and d2. In case of
    conflicting mappings, d2 takes precedence."""
    d = dict(d1)
    d.update(d2)
    return d