Source

hgtk / tortoisehg / util / hglib.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
# hglib.py - Mercurial API wrappers for TortoiseHg
#
# Copyright 2007 Steve Borho <steve@borho.org>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2, incorporated herein by reference.

import os
import sys
import shlex
import time
import inspect

from mercurial import ui, util, error, extensions, match, bundlerepo, cmdutil
from mercurial import dispatch, encoding, templatefilters, filemerge, scmutil
from mercurial.scmutil import updatedir

_encoding = encoding.encoding
_encodingmode = encoding.encodingmode
_fallbackencoding = encoding.fallbackencoding

# extensions which can cause problem with TortoiseHg
_extensions_blacklist = ('color', 'pager', 'progress')

from tortoisehg.util.hgversion import hgversion # used by other modules
from tortoisehg.util import paths

def tounicode(s):
    """
    Convert the encoding of string from MBCS to Unicode.

    Based on mercurial.util.tolocal().
    Return 'unicode' type string.
    """
    if isinstance(s, unicode):
        return s
    if isinstance(s, encoding.localstr):
        return s._utf8.decode('utf-8')
    for e in ('utf-8', _encoding):
        try:
            return s.decode(e, 'strict')
        except UnicodeDecodeError:
            pass
    return s.decode(_fallbackencoding, 'replace')

def toutf(s):
    """
    Convert the encoding of string from MBCS to UTF-8.

    Return 'str' type string.
    """
    if isinstance(s, encoding.localstr):
        return s._utf8
    return tounicode(s).encode('utf-8').replace('\0','')

def fromutf(s):
    """
    Convert the encoding of string from UTF-8 to MBCS

    Return 'str' type string.
    """
    return encoding.tolocal(s)

_tabwidth = None
def gettabwidth(ui):
    global _tabwidth
    if _tabwidth is not None:
        return _tabwidth
    tabwidth = ui.config('tortoisehg', 'tabwidth')
    try:
        tabwidth = int(tabwidth)
        if tabwidth < 1 or tabwidth > 16:
            tabwidth = 0
    except (ValueError, TypeError):
        tabwidth = 0
    _tabwidth = tabwidth
    return tabwidth

_maxdiff = None
def getmaxdiffsize(ui):
    global _maxdiff
    if _maxdiff is not None:
        return _maxdiff
    maxdiff = ui.config('tortoisehg', 'maxdiff')
    try:
        maxdiff = int(maxdiff)
        if maxdiff < 1:
            maxdiff = sys.maxint
    except (ValueError, TypeError):
        maxdiff = 1024 # 1MB by default
    _maxdiff = maxdiff * 1024
    return _maxdiff

_deadbranch = None
def getdeadbranch(ui):
    '''return a list of dead branch names in UTF-8'''
    global _deadbranch
    if _deadbranch is None:
        db = toutf(ui.config('tortoisehg', 'deadbranch', ''))
        dblist = [b.strip() for b in db.split(',')]
        _deadbranch = dblist
    return _deadbranch

def getlivebranch(repo):
    '''return a list of live branch names in UTF-8'''
    lives = []
    deads = getdeadbranch(repo.ui)
    cl = repo.changelog
    for branch, heads in repo.branchmap().iteritems():
        branch = toutf(branch)
        if branch in deads:
            # ignore branch names in tortoisehg.deadbranch
            continue
        bheads = [h for h in heads if ('close' not in cl.read(h)[5])]
        if not bheads:
            # ignore branches with all heads closed
            continue
        lives.append(branch.replace('\0', ''))
    return lives

def getlivebheads(repo):
    '''return a list of revs of live branch heads'''
    bheads = []
    for b, ls in repo.branchmap().iteritems():
        bheads += [repo[x] for x in ls]
    heads = [x.rev() for x in bheads if not x.extra().get('close')]
    heads.sort()
    heads.reverse()
    return heads

_hidetags = None
def gethidetags(ui):
    global _hidetags
    if _hidetags is None:
        tags = toutf(ui.config('tortoisehg', 'hidetags', ''))
        taglist = [t.strip() for t in tags.split()]
        _hidetags = taglist
    return _hidetags

def getfilteredtags(repo):
    filtered = []
    hides = gethidetags(repo.ui)
    for tag in list(repo.tags()):
        if tag not in hides:
            filtered.append(tag)
    return filtered

def diffexpand(line):
    'Expand tabs in a line of diff/patch text'
    if _tabwidth is None:
        gettabwidth(ui.ui())
    if not _tabwidth or len(line) < 2:
        return line
    return line[0] + line[1:].expandtabs(_tabwidth)

_fontconfig = None
def getfontconfig(_ui=None):
    global _fontconfig
    if _fontconfig is None:
        if _ui is None:
            _ui = ui.ui()
        # defaults
        _fontconfig = {'fontcomment': 'monospace 10',
                       'fontdiff': 'monospace 10',
                       'fontlist': 'sans 9',
                       'fontlog': 'monospace 10'}
        # overwrite defaults with configured values
        for name, val in _ui.configitems('gtools'):
            if val and name.startswith('font'):
                _fontconfig[name] = val
    return _fontconfig

def invalidaterepo(repo):
    repo.dirstate.invalidate()
    for attr in ('_bookmarks', '_bookmarkcurrent'):
        if attr in repo.__dict__:
            delattr(repo, attr)
    if isinstance(repo, bundlerepo.bundlerepository):
        # Work around a bug in hg-1.3.  repo.invalidate() breaks
        # overlay bundlerepos
        return
    repo.invalidate()
    if 'mq' in repo.__dict__: #do not create if it does not exist
        repo.mq.invalidate()

def allextensions():
    """Return the {name: shortdesc} dict of known extensions

    shortdesc is in local encoding.
    """
    enabledexts = extensions.enabled()[0]
    disabledexts = extensions.disabled()[0]
    exts = (disabledexts or {}).copy()
    exts.update(enabledexts)
    return exts

def validateextensions(enabledexts):
    """Report extensions which should be disabled

    Returns the dict {name: message} of extensions expected to be disabled.
    message is 'utf-8'-encoded string.
    """
    from tortoisehg.util.i18n import _  # avoid cyclic dependency
    exts = {}
    if os.name != 'posix':
        exts['inotify'] = _('inotify is not supported on this platform')
    if 'win32text' in enabledexts:
        exts['eol'] = _('eol is incompatible with win32text')
    if 'eol' in enabledexts:
        exts['win32text'] = _('win32text is incompatible with eol')
    return exts

def loadextension(ui, name):
    # Between Mercurial revisions 1.2 and 1.3, extensions.load() stopped
    # calling uisetup() after loading an extension.  This could do
    # unexpected things if you use an hg version < 1.3
    extensions.load(ui, name, None)
    mod = extensions.find(name)
    uisetup = getattr(mod, 'uisetup', None)
    if uisetup:
        uisetup(ui)

def _loadextensionwithblacklist(orig, ui, name, path):
    if name.startswith('hgext.') or name.startswith('hgext/'):
        shortname = name[6:]
    else:
        shortname = name
    if shortname in _extensions_blacklist and not path:  # only bundled ext
        return

    return orig(ui, name, path)

def wrapextensionsloader():
    """Wrap extensions.load(ui, name) for blacklist to take effect"""
    extensions.wrapfunction(extensions, 'load',
                            _loadextensionwithblacklist)

def canonpaths(list):
    'Get canonical paths (relative to root) for list of files'
    # This is a horrible hack.  Please remove this when HG acquires a
    # decent case-folding solution.
    canonpats = []
    cwd = os.getcwd()
    root = paths.find_root(cwd)
    for f in list:
        try:
            canonpats.append(scmutil.canonpath(root, cwd, f))
        except error.Abort:
            # Attempt to resolve case folding conflicts.
            fu = f.upper()
            cwdu = cwd.upper()
            if fu.startswith(cwdu):
                canonpats.append(scmutil.canonpath(root, cwd, f[len(cwd+os.sep):]))
            else:
                # May already be canonical
                canonpats.append(f)
    return canonpats

def escapepath(path):
    'Before passing a file path to hg API, it may need escaping'
    p = path
    if '[' in p or '{' in p or '*' in p or '?' in p:
        return 'path:' + p
    else:
        return p

def normpats(pats):
    'Normalize file patterns'
    normpats = []
    for pat in pats:
        kind, p = match._patsplit(pat, None)
        if kind:
            normpats.append(pat)
        else:
            if '[' in p or '{' in p or '*' in p or '?' in p:
                normpats.append('glob:' + p)
            else:
                normpats.append('path:' + p)
    return normpats


def mergetools(ui, values=None):
    'returns the configured merge tools and the internal ones'
    if values == None:
        values = []
    seen = values[:]
    for key, value in ui.configitems('merge-tools'):
        t = key.split('.')[0]
        if t not in seen:
            seen.append(t)
            # Ensure the tool is installed
            if filemerge._findtool(ui, t):
                values.append(t)
    values.append('internal:merge')
    values.append('internal:prompt')
    values.append('internal:dump')
    values.append('internal:local')
    values.append('internal:other')
    values.append('internal:fail')
    return values


_difftools = None
def difftools(ui):
    global _difftools
    if _difftools:
        return _difftools

    def fixup_extdiff(diffopts):
        if '$child' not in diffopts:
            diffopts.append('$parent1')
            diffopts.append('$child')
        if '$parent2' in diffopts:
            mergeopts = diffopts[:]
            diffopts.remove('$parent2')
        else:
            mergeopts = []
        return diffopts, mergeopts

    tools = {}
    for cmd, path in ui.configitems('extdiff'):
        if cmd.startswith('cmd.'):
            cmd = cmd[4:]
            if not path:
                path = cmd
            diffopts = ui.config('extdiff', 'opts.' + cmd, '')
            diffopts = shlex.split(diffopts)
            diffopts, mergeopts = fixup_extdiff(diffopts)
            tools[cmd] = [path, diffopts, mergeopts]
        elif cmd.startswith('opts.'):
            continue
        else:
            # command = path opts
            if path:
                diffopts = shlex.split(path)
                path = diffopts.pop(0)
            else:
                path, diffopts = cmd, []
            diffopts, mergeopts = fixup_extdiff(diffopts)
            tools[cmd] = [path, diffopts, mergeopts]
    mt = []
    mergetools(ui, mt)
    for t in mt:
        if t.startswith('internal:'):
            continue
        dopts = ui.config('merge-tools', t + '.diffargs', '')
        mopts = ui.config('merge-tools', t + '.diff3args', '')
        dopts, mopts = shlex.split(dopts), shlex.split(mopts)
        tools[t] = [filemerge._findtool(ui, t), dopts, mopts]
    _difftools = tools
    return tools


def hgcmd_toq(q, label, args):
    '''
    Run an hg command in a background thread, pipe all output to a Queue
    object.  Assumes command is completely noninteractive.
    '''
    class Qui(ui.ui):
        def __init__(self, src=None):
            super(Qui, self).__init__(src)
            self.setconfig('ui', 'interactive', 'off')

        def write(self, *args, **opts):
            if self._buffers:
                self._buffers[-1].extend([str(a) for a in args])
            else:
                for a in args:
                    if label:
                        q.put((str(a), opts.get('label', '')))
                    else:
                        q.put(str(a))

        def plain(self, feature=None):
            return True

    u = Qui()
    oldterm = os.environ.get('TERM')
    os.environ['TERM'] = 'dumb'
    request = dispatch.request(list(args), ui=u)
    ret = dispatch._dispatch(request)
    if oldterm:
        os.environ['TERM'] = oldterm
    return ret

def get_reponame(repo):
    if repo.ui.config('tortoisehg', 'fullpath', False):
        name = repo.root
    elif repo.ui.config('web', 'name', False):
        name = repo.ui.config('web', 'name')
    else:
        name = os.path.basename(repo.root)
    return toutf(name)

def displaytime(date):
    return util.datestr(date, '%Y-%m-%d %H:%M:%S %1%2')

def utctime(date):
    return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(date[0]))

def age(date):
    return templatefilters.age(date)

def username(user):
    author = templatefilters.person(user)
    if not author:
        author = util.shortuser(user)
    return author

def validate_synch_path(path, repo):
    '''
    Validate the path that must be used to sync operations (pull,
    push, outgoing and incoming)
    '''
    return_path = path
    for alias, path_aux in repo.ui.configitems('paths'):
        if path == alias:
            return_path = path_aux
        elif path == util.hidepassword(path_aux):
            return_path = path_aux
    return return_path

def is_rev_current(repo, rev):
    '''
    Returns True if the revision indicated by 'rev' is the current
    working directory parent.

    If rev is '' or None, it is assumed to mean 'tip'.
    '''
    if rev in ('', None):
        rev = 'tip'
    rev = repo.lookup(rev)
    parents = repo.parents()

    if len(parents) > 1:
        return False

    return rev == parents[0].node()

def is_descriptor(obj, attr):
    """
    Returns True if obj.attr is a descriptor - ie, accessing
    the attribute will actually invoke the '__get__' method of
    some object.

    Returns False if obj.attr exists, but is not a descriptor,
    and None if obj.attr was not found at all.
    """
    for cls in inspect.getmro(obj.__class__):
        if attr in cls.__dict__:
            return hasattr(cls.__dict__[attr], '__get__')
    return None

def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
           opts=None):
    '''
    export changesets as hg patches.

    Mercurial moved patch.export to cmdutil.export after version 1.5
    (change e764f24a45ee in mercurial).
    '''

    return cmdutil.export(repo, revs, template, fp, switch_parent, opts)
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.