repoman / repoman / util.py

  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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
# -*- coding: utf-8 -*-
#
# Copyright 2009-2012 Edlund A/S
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
'''
Utility functions that are shared across the entire library.
'''

import os
import time

import mercurial.extensions
from mercurial import encoding
from mercurial.match import match
import mercurial.cmdutil
import mercurial.scmutil
import mercurial.commands
from mercurial.error import Abort, AmbiguousCommand, UnknownCommand
from mercurial.error import SignatureError, RepoError, LookupError
from mercurial.util import unlink

class UnrelatedSolutionError(Exception):
    pass

class UnknownSolutionError(Exception):
    pass

class BranchUnknown(Exception):
    pass

class ModulesMissingError(Exception):
    pass

class FormatError(Exception):
    pass

def dict_trim(dict, keys):
     for k in set(dict) - set(keys):
        del dict[k]

def docmd_encoding(callable, enc='utf-8'):
    '''Execute code with hg's local encoding set to the given encoding,
    which defaults to utf-8.'''

    return callable()

def dict_update(dest, src):
    '''updates a dictionary, returning status

    Update a dictionary like dest.update(src), but returns True if any
    changes where made and False otherwise.'''

    changes = False
    for key, value in src.iteritems():
        oldv = dest.get(key)
        if oldv != value:
            changes = True
            dest[key] = value
    return changes

def mkdir_rec(path):
    '''creates directories recursively

    Creates the target directory and all intermediate directories as needed.
    No error is returned if any of the directories already exists.'''

    paths = path.split('/')
    full_path = ''
    for path in paths:
        full_path += path + '/'
        if not os.path.exists(full_path):
            os.mkdir(full_path)

def parse_branch(name=None, global_data=None, local_data=None):
    # the utf-8 encode is just to get away from a unicode string and
    # it is a safe target to use. the encoded value will be a changeset
    # identifier and thus never contain non-ascii characters

    class BaseBranchInfo(object):
        def __init__(self, g, l):
            self.g = g
            self.l = l

        def __getitem__(self, mod):
            if mod in self.g:
                return self.g[mod]
            if mod in self.l:
                return self.l[mod]
            raise KeyError()

        def __delitem__(self, mod):
            raise NotSupportedError()

        def __contains__(self, mod):
            return mod in self.g or mod in self.l

        def __iter__(self):
            for mod in self.g:
                yield mod
            for mod in self.l:
                yield mod

        def __setitem__(self, mod, hash):
            if mod in self.l:
                self.l[mod] = hash
            else:
                self.g[mod] = hash

        def iteritems(self):
            for mod, hash in self.g.iteritems():
                yield mod, hash
            for mod, hash in self.l.iteritems():
                yield mod, hash

        def get(self, mod, default=None):
            if mod in self.g:
                return self.g[mod]
            else:
                return self.l.get(mod, default)

        def iterkeys(self):
            for mod in self.g.iterkeys():
                yield mod
            for mod in self.l.iterkeys():
                yield mod

        def iterkeyslocal(self):
            for mod in self.l.iterkeys():
                yield mod

        def iterkeysglobal(self):
            for mod in self.g.iterkeys():
                yield mod

        def __nonzero__(self):
            return bool(self.g) or bool(self.l)

    class FilteredBranchInfo(BaseBranchInfo):
        def __init__(self, branchinfo, removemodule=None):
            BaseBranchInfo.__init__(self, {}, {})
            self.branchinfo = branchinfo
            self.name = branchinfo.name
            self.g = dict(branchinfo.g)
            self.l = dict(branchinfo.l)
            if removemodule:
                self._filter(removemodule)

        def _filter(self, mod):
            if mod in self.g:
                del self.g[mod]
            elif mod in self.l:
                del self.l[mod]

        def __delitem__(self, mod):
            self._filter(mod)

        def __repr__(self):
            return 'FilteredBranchInfo{Global=%s, Local=%s}' % (self.g, self.l)

    class BranchInfo(BaseBranchInfo):
        def __init__(self, name, global_data, local_data):
            BaseBranchInfo.__init__(self, {}, {})
            self.name = name
            self.g = self._parse(global_data)
            self.l = self._parse(local_data)
            self._validate()

        def _validate(self):
            for mod in self.l:
                if mod in self.g:
                    raise Abort('branch "%s" defines local branch information for module "%s" that is also a global module' % (
                        name, mod))

        def _parse(self, data):
            if data is None:
                return {}

            if type(data) is dict:
                return dict(data)

            return dict((k.encode(encoding.encoding), v.encode('utf-8'))
                for v, k in (
                    l.decode('utf-8-sig').strip().split() for l in data if l))

    return FilteredBranchInfo(BranchInfo(name, global_data, local_data))

def read_utf8(path):
    '''
    Reads an utf-8-sig encoded file and returns its contents.

    @type path: str
    @param path: The file path.

    @rtype: str
    @return: The encoding.encoding encoded contents of the specified file.
    '''

    return file(path).read().decode('utf-8-sig').encode(encoding.encoding)

def write_utf8(path, text):
    '''
    Writes text encoded in encoding.encoding to a file using
    utf-8-sig. The contents of the file will be overwritten.

    @type path: str
    @param path: The path of the file to write.
    @type text: str
    @param text: encoding.encoding encoded string to write to the
    file.
    '''

    file(path, 'wb').write(text.decode(encoding.encoding).encode('utf-8-sig'))

def write_default(path, text):
    file(path, 'wb').write(text)

def try_read_line(path, default=None):
    '''
    Reads the contents of the file if it exists or returns the default
    value.

    @type path: str
    @param path: The path of the file to write.
    @type default: str
    @param default: The default value to return in case the file does
    not exist.

    @rtype: str
    @return: The contents of the specified file or the default value.
    '''

    return os.path.isfile(path) and read_utf8(path).strip() or default

def try_read_lines(path):
    '''
    Reads the contents of the file if it exists or returns the empty
    list.

    @type path: str
    @param path: The path of the file to write.

    @rtype: list
    @return: The contents of the specified file or the empty list.
    '''

    return os.path.isfile(path) and [l.strip() for l in read_utf8(path).split('\n') if l] or []

def symlink(target, name):
    '''Creates a symbolic link (actually junction)'''
    if os.name == 'nt':
        return os.system('linkd "%s" "%s" >%s' % (name, target, os.devnull)) == 0
    os.symlink(os.path.abspath(target), name)
    return True

if os.name == 'nt':
    import win32file
    import pywintypes
    def get_proper_filename(path):
        '''returns the properly cased file name (not the path)'''
        try:
            files = win32file.FindFilesW(os.path.normpath(path))
            if files:
                return files[0][8].encode(encoding.encoding)
        except pywintypes.error:
            pass
        return None
else:
    def get_proper_filename(path):
        '''returns the properly cased file name (not the path)'''
        return os.path.exists(path) and os.path.basename(path) or None


def wrap(text, width, indent=0, start=0):
    #TODO: Bedre docstring
    '''
    Wraps text to a specific line width.
    '''

    prefix = [' ', '\n' + ' ' * indent]
    return reduce(lambda line, word: '%s%s%s' %
                   (line,
                    prefix[(len(line) - line.rfind('\n') - 1
                          + len(word.split('\n', 1)[0]
                               ) >= width - 1)],
                    word), [''] * start + text.split(' ')
                  )[start:]

def longuser(user):
    """Return the full user name of a user name or email address."""
    f = user.find('<')
    if f >= 0:
        return user[:f].strip()
    return user

def hide(path):
    '''
    Marks a file as hidden.

    Does nothing on non-Windows systems.
    '''

    try:
        import win32api
        import win32con

        win32api.SetFileAttributes(path, win32con.FILE_ATTRIBUTE_HIDDEN)
    except ImportError:
        pass

def write_rc_file(path, lines):
    '''
    Writes the specified lines to the specied file.

    The file is encoded as UTF-8 without signature to avoid problems with
    Mercurial (which does not seem to handle signatures).

    @type path: str
    @param path: The path to the configuration file.
    @type lines: list
    @param lines: The lines to write.
    '''
    data = "\n".join(lines)
    file(path, 'wb').write(data.encode('utf-8'))

def merge_into_rc_file(path, sectionname, hook):
    lines = [l.strip() for l in tounicode(file(path).read()).split('\n')]
    insection = False
    wassection = False
    out = []
    tail = []
    data = {}
    for l in lines:
        if insection:
            if l.startswith('['):
                insection = False
                result = hook(data)
                if not result:
                    return
                out.extend(result)
                out.extend(tail)
                tail = []
                data = {}
            else:
                tok = [t.strip() for t in l.split('=', 2)]
                if len(tok) == 2:
                    data[tok[0]] = tok[1]
                else: tail.append(l)
        if not insection:
            if not wassection and l == '[' + sectionname + ']':
                insection = True
                wassection = True
            out.append(l)
    if insection or not wassection:
        if not wassection:
            out.append('['+sectionname + ']')
        result = hook(data)
        if not result:
            return
        out.extend(result)
        out.extend(tail)
    write_rc_file(path, out)

def get_mercurial_default_opts(command, command_table=None, **opts):
    '''get default parameters for a mercurial command'''

    if command_table is None:
        command_table = mercurial.commands.table

    possible = mercurial.cmdutil.findpossible(command, command_table)
    if len(possible) != 1:
        raise Exception, 'unable to find mercurial command "%s"' % command
    d = dict((r[1].replace('-', '_'), r[2]) for r in
        possible[possible.keys()[0]][1][1])

    for opt in opts:
        d[opt] = opts[opt]

    return d

def get_mercurial_extension(ui, name):
    return mercurial.extensions.find(name)

def version():
    '''
    Retrieves the current version of repoman if possible.

    @rtype: str
    @return: The current version or unknown.
    '''

    try:
        from repoman import __version__ as _version
        return _version.version
    except ImportError:
        return 'unknown'

def iter_dict_sorted(dictionary):
    '''
    Provide an iterator over a dictionary that gives the keys in
    sorted order.
    '''

    keys = sorted(list(dictionary))

    for key in keys:
        yield (key, dictionary[key])

def _get_branch_file(base, group):
    path = os.path.join(base, group)
    if os.path.exists(path + '.b'):
        return path + '.b'
    return path

def read_rev_infos(base, groups, entries, suffix=''):
    '''
    Retrieves revision information for the given groups.
    '''

    for group in groups:
        filename = _get_branch_file(base, group)

        name = filename[len(base):].replace('\\', '/')

        if name.endswith('.b'):
            name = name[:-2]
        if name.startswith('/'):
            name = name[1:]

        for line in try_read_lines(filename):
            node, module = line.strip().split(' ')
            entry = { 'name': name + suffix, 'node': node }
            if module in entries:
                entries[module].append(entry)
            else:
                entries[module] = [entry]

    return entries

def read_tag_map(forest, groups, read_branches=False, read_tags=False):
    '''
    Retrieves the branches from the forest.
    '''

    if not groups:
        return {}
    entries = {}

    if read_branches:
        branchespath = forest.branches_gmd_path
        if os.path.exists(branchespath):
            entries = read_rev_infos(branchespath, groups, entries, '_base')

    return entries

def update_tags_from_map(forest, tagmap, reset=False):
    for mod in forest.modules:
        modpath = os.path.abspath(os.path.join(forest.path, mod))
        tagfile = os.path.join(os.path.join(modpath, '.hg'), 'localtags')
        l = tagmap.get(mod)
        if not l:
            if reset:
                write_default(tagfile, '')
            continue
        m = dict((x['name'], x['node']) for x in l)
        if not reset and os.path.exists(tagfile):
            l.extend([{'node': y[0], 'name': y[1]} for y in [x.strip().split(' ', 1) for x in try_read_lines(tagfile)] if y[1] not in m])
        write_default(tagfile, '\n'.join(['%(node)s %(name)s' % i for i in l]))

def update_tags(forest, groups):
    '''
    Update the tag/branch map of the forest according to a newly written
    file.
    '''

    tag_map = read_tag_map(forest, groups, read_branches=True, read_tags=True)
    return update_tags_from_map(forest, tag_map)

def rev_exists(repo, rev):
    try:
        repo.lookup(rev)
        return True
    except RepoError:
        return False

def is_local(path):
    '''
    Tests whether the given path is a local path or not.

    @type path: str
    @param path: The path to test.

    @rtype: bool
    @return: Whether the given path is a local path or not.
    '''

    return '://' not in path

def get_times():
    t = os.times()
    if t[4] == 0.0: # Windows leaves this as zero, so use time.clock()
        t = (t[0], t[1], t[2], t[3], time.clock())
    return t

def print_times(ui, oldtimes):
    s, t = oldtimes, get_times()
    ui.warn('Time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n' %
            (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))

def commit(repo, message, files=None, pathtype='abspath', date=None):
    '''Commits the given list of files. File names are (by default)
    relative to the repo root.'''

    if files is None:
        return docmd_encoding(lambda: repo.commit(message, date=date))
    else:
        return docmd_encoding(lambda:
            repo.commit(message, match=mercurial.scmutil.match(
                        repo[None], files, default=pathtype), date=date))

def tounicode(s):
    """
    Convert a string from the local character encoding to unicode.
    """
    if isinstance(s, unicode):
        return s
    for e in ('utf-8', encoding.encoding):
        try:
            return s.decode(e, 'strict')
        except UnicodeDecodeError:
            pass
    return s.decode(encoding.fallbackencoding, 'replace')

def sortmodules(modules):
    modules = list(modules)

    if any([x.__class__ is unicode for x in modules]):
        key = unicode.lower
    else:
        key = str.lower

    if os.name == 'nt':
        return sorted(modules, key=key)
    return sorted(modules)

def sort(l):
    return sortmodules(l)

def normpath(ui, p):
    if not is_local(p):
        return p
    if ui.configbool('ui', 'slash') and os.sep != '/':
        return mercurial.util.normpath(p)
    return p
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.