Source

repoman / repoman / cmdutil.py

Full commit
  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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
# vim: set fileencoding=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.
'''
Repoman
Command utility functions
'''


import codecs
import os.path
import re
import datetime
import tempfile
import shutil
import urllib2

import mercurial.hg
import mercurial.changegroup
import mercurial.commands
import mercurial.encoding
from mercurial.i18n import _
from mercurial.node import nullid
from mercurial import url

from repoman.forest import Forest
from repoman import util
from repoman.util import AmbiguousCommand, UnknownCommand

# TODO: Avoid using string-matching like this if possible.
nullidstr = '0' * 40


def modstr_tmpl(ui, modules, metadata=False, inout=False):
    maxlen = modules and max([len(mod) for mod in modules]) or 0
    if metadata:
        if inout:
            maxlen = max(maxlen, 14)
        else:
            maxlen = max(maxlen, 10)
    return ui.emph_str('%%-%ds' % maxlen) + '  '

def run_editor(forest, text):
    olddir = os.getcwd()
    os.chdir(forest.root)
    text = forest.ui.edit("\n".join(text), forest.ui.username())
    text = re.sub("(?m)^HG:.*\n", "", text)
    os.chdir(olddir)
    if not text.strip():
        raise util.Abort(_("empty commit message"))
    return text

def get_commit_message(forest, text=[''], extra=[]):
    text.extend([
        '',
        _("HG: Enter commit message.  Lines beginning with 'HG:' are removed."),
        _("HG: Leave message empty to abort commit."),
        "HG: --",
        _("HG: user: %s") % forest.ui.username()])
    if extra:
        text.extend(extra)
    text.append('')
    return run_editor(forest, text)

def get_branch_name_re_txt():
    return ur'^([\.a-zæøå0-9]([-\.,_a-zæøå0-9]*[a-zæøå0-9])?/)*([a-zæøå0-9]([-\.,_a-zæøå0-9]*[a-zæøå0-9])?)$'

def get_branch_name_re_errorhelp(name):
    return '%s: branch names must be lowercase, slash separated strings' % name

_branch_name_re = None

def parse_branches(names, exact=False, current=None, default=None):
    if not names:
        if default is None:
            b = [current] if current else names
            if not exact:
                return b, False
            return b
        else:
            names = default

    global _branch_name_re
    if not _branch_name_re:
        _branch_name_re = re.compile(get_branch_name_re_txt(), re.UNICODE)
    if isinstance(names, str):
        names = (names,)
    newnames = []
    for n in names:
        if n == '*':
            if exact:
                raise util.Abort('"*" (all branches) is not allowed in this context')
            return [], True
        if n == '.':
            if not current:
                raise util.Abort('"." (current branch) is not allowed in this context')
            n = current
        elif not _branch_name_re.match(util.tounicode(n)):
            raise util.Abort('%s: branch names must be lowercase, slash separated strings' % n)
        if n not in newnames:
            newnames.append(n)
    if not exact:
        return newnames, False
    return newnames

def build_alias_map(table):
    aliases = {}
    for c in table.iteritems():
        for a in c[1][1]:
            aliases[a] = c
    return aliases

def findcmd(cmd, table, aliases):
    if aliases.has_key(cmd):
        return aliases[cmd]
    else:
        cmds = []
        for c in table.iteritems():
            if(c[0].startswith(cmd)):
                cmds.append(c)
        if(len(cmds) == 1):
            return cmds[0]
        if(len(cmds) > 1):
            raise AmbiguousCommand(cmd, cmds)
        else:
            raise UnknownCommand(cmd)

def repository(ui, source, name):
    return mercurial.hg.repository(ui, '%s/%s' % (source, name))

def perform_clone(ui, source, name, base_dest, update=True, hide=False, rev=None):
    dest = os.path.join(base_dest, name)
    mercurial.hg.clone(ui, {}, '%s/%s' % (source, name), dest, update=update, rev=rev)
    if hide:
        util.hide(dest)

def preclone(ui, source, dest, symlink=False):
    ui.status('Cloning metadata\n')
    util.mkdir_rec(dest)
    lmd = '.repo'
    gmd = '.root'
    fui = ui.copy()
    fui.filter = ''
    perform_clone(fui, source, lmd, dest, hide=True)
    if symlink:
        destpath = os.path.join(dest, gmd)
        if not util.symlink(os.path.join(source, gmd), destpath):
            raise util.Abort('could not create symbolic link for forest metadata; check permissions')
        util.hide(destpath)
    else:
        perform_clone(fui, source, gmd, dest, hide=True)
    f = Forest(ui, dest)
    f.paths['clone'] = '.' if util.is_local(source) and not os.path.isabs(source) else source
    paths = relativize_paths(source, dest, f.paths)
    f.paths.clear()
    f.paths.update(paths)
    return f

def get_remote_info(ui, source):
    '''
    return information about a remote forest with minimal data transfer.
    currently, it returns the list of modules in the remote forest.
    '''
    tmpdir = tempfile.mkdtemp()
    lmd = '.repo'
    with silentui(ui):
        perform_clone(ui, source, lmd, tmpdir)
        modules = util.read_utf8(os.path.join(tmpdir, lmd, 'modules')).split()
    shutil.rmtree(tmpdir, ignore_errors=True)
    return modules

def pull(ui, repo, source, **opts):
    '''Pull changes from a remote repository.

    Custom version of mercurial.commands.pull.'''

    # TODO: allow passing nodes in rev, skipping the extra lookup below.

    source, branches = mercurial.hg.parseurl(ui.expandpath(source), opts.get('branch'))
    other = opts.get('other') or mercurial.hg.repository(mercurial.hg.remoteui(repo, opts), source)
    revs, checkout = mercurial.hg.addbranchrevs(repo, other, branches, opts.get('rev'))
    if revs:
        revs = [other.lookup(rev) for rev in revs]
    modheads = repo.pull(other, heads=revs, force=opts.get('force'))
    if opts.get('update'):
        rv = mercurial.commands.postincoming(ui, repo, modheads, True, checkout)
    else:
        rv = modheads
    if opts['rebase'] and len(repo.heads()) > 1:
        rebase_mod = util.get_mercurial_extension(ui, 'rebase')
        with quietui(ui, repo.ui, filter='saving bundle to '):
            rebase_mod.rebase(ui, repo)
    return rv

def unbundle(ui, repo, fname, **opts):
    lock = repo.lock()
    f = None
    try:
        f = open(fname, 'rb')
        gen = mercurial.changegroup.readbundle(f, fname)
        modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
    finally:
        if f:
            f.close()
        lock.release()
    if opts.get('update'):
        rv = mercurial.commands.postincoming(ui, repo, modheads, True, None)
    else:
        rv = modheads
    return rv

def pull_metadata(forest, source=None, terse=False):
    '''
    update global metadata by pulling in from the given (or default) source.
    '''
    ui = forest.ui
    if not terse:
        ui.write_module_header('(metadata)')
    tersefilter = '|\d+ files updated' if terse else ''
    repo = forest.gmd_repo
    with filterui(re.compile('^(pulling from |comparing with |searching for changes|adding |\\(run \'hg |not updating%s)' %
                             tersefilter), ui, repo.ui):
        pull(ui, repo, forest.getsource(forest.GMD, source), style='', template='',
             rev=None, force=None, bundle=None, update=True, rebase=True)
    if not terse:
        ui.write('\n')

def combine_changesets(repo, ctxs):
    '''
    combine the dirstate with a list of contexts, which must be ordered from
    newest to oldest (the wdir context must not be included).
    '''

    # Prepare
    p1, p2 = ctxs[-1].p1(), ctxs[-1].p2()
    ctxs = [p1] + list(reversed(ctxs)) + [repo[None]]
    modified, added, removed, forget = set(), set(), set(), set()
    copies = dict()
    wlock = repo.wlock()
    try:

        # Calculate cumulative changes
        numctxs = len(ctxs)
        for i in xrange(1, numctxs):
            ctx = ctxs[i]
            mod, add, rem = repo.status(ctxs[i-1], ctx)[:3]
            for f in add:
                if f in removed:
                    modified.add(f)
                    removed.discard(f)
                else:
                    added.add(f)
                    forget.discard(f)
                    copy = ctx[f].renamed()
                    if copy:
                        copy = copy[0]
                        while copy in copies:
                            copy = copies[copy]
                        copies[f] = copy
            for f in rem:
                if f not in added:
                    modified.discard(f)
                    removed.add(f)
                else:
                    added.discard(f)
                    forget.add(f)
                    if f in copies:
                        del copies[f]
            for f in mod:
                if f not in added:
                    modified.add(f)

        # Remove copied files where the source is lost
        for f in [dst for dst, src in copies.iteritems() if src not in p1]:
            del copies[f]

        # Adjust dirstate
        dirstate = repo.dirstate
        dirstate.setparents(p1.node(), p2.node())
        for f in added:
            dirstate.add(f)
            src = copies.get(f)
            if src:
                dirstate.copy(src, f)
        for f in removed:
            dirstate.remove(f)
        for f in modified:
            pl = dirstate._pl
            dirstate._pl = (pl[0], 'temp' if pl[1] == nullid else pl[1])
            dirstate.otherparent(f)
            dirstate._pl = pl
        for f in forget:
            if f in dirstate:
                dirstate.drop(f)

        dirstate.write()

    finally:
        wlock.release()

mq_mod = None
mq_opts = None

def strip(ui, repo, *nodes):
    global mq_mod, mq_opts
    if not mq_mod:
        mq_mod = util.get_mercurial_extension(ui, 'mq')
        mq_opts = util.get_mercurial_default_opts('strip', mq_mod.cmdtable)
    with quietui(ui, repo.ui, filter='saving bundle to '):
        for node in nodes:
            mq_mod.strip(ui, repo, str(node), **mq_opts)

def relativize_paths(source, dest, paths):
    newpaths = {}
    local = util.is_local(source)
    for k, p in paths.iteritems():
        if local:
            if util.is_local(p) and not os.path.isabs(p):
                p = os.path.relpath(source + '/' + p, dest)
            newpaths[k] = p
        else:
            if not util.is_local(p):
                newpaths[k] = p
    return newpaths

class filterui(object):
    def __init__(self, filter, *ui):
        self.ui = ui
        self.filter = filter
        if filter:
            self.orig_f = [u.filter for u in ui]

    def __enter__(self):
        for u in self.ui:
            u.filter = self.filter

    def __exit__(self, exc_type, exc_val, exc_tb):
        for i in xrange(len(self.ui)):
            self.ui[i].filter = self.orig_f[i]

class silentui(object):
    def __init__(self, *ui, **kwargs):
        self.ui = ui
        self.orig = [u.silent for u in ui]
        self.filter = kwargs.get('filter')
        if self.filter:
            self.orig_f = [u.filter for u in ui]

    def __enter__(self):
        for u in self.ui:
            if self.filter:
                u.filter = self.filter
            if not (u.debugflag or u.verbose):
                u.silent = True

    def __exit__(self, exc_type, exc_val, exc_tb):
        for i in xrange(len(self.ui)):
            self.ui[i].silent = self.orig[i]
            if self.filter:
                self.ui[i].filter = self.orig_f[i]

class quietui(object):
    def __init__(self, *ui, **kwargs):
        self.ui = ui
        self.orig = [u.quiet for u in ui]
        self.filter = kwargs.get('filter')
        if self.filter:
            self.orig_f = [u.filter for u in ui]

    def __enter__(self):
        for u in self.ui:
            if self.filter:
                u.filter = self.filter
            if not (u.debugflag or u.verbose):
                u.quiet = True

    def __exit__(self, exc_type, exc_val, exc_tb):
        for i in xrange(len(self.ui)):
            self.ui[i].quiet = self.orig[i]
            if self.filter:
                self.ui[i].filter = self.orig_f[i]

def get_headmaps(f, modules, current, branches):
    '''returns module -> branch -> [heads]'''
    headmaps = None
    if current:
        headmaps = {}
        for mod in modules:
            ctx = f[mod]['.']
            headmaps[mod] = {ctx.branch(): [ctx.node()]}
    elif branches:
        branchmaps = f.read_branches(branches)
        bmh_map = dict((b, f.branch_heads(b, bm)) for b, bm in branchmaps)
        headmaps = {}
        for mod in modules:
            headmaps[mod] = dict((b, bmh_map[b][mod]) for b in bmh_map if mod in bmh_map[b])
    return headmaps

def parse_date(datespec):
    if datespec.startswith('<'):
        dt = mercurial.util.parsedate(datespec[1:])
        spec = '<'
    elif datespec.startswith('>'):
        dt = mercurial.util.parsedate(datespec[1:])
        spec = '>'
    elif ' to ' in datespec:
        dt = [mercurial.util.parsedate(d) for d in datespec.split(' to ')]
        spec = 'r'
    else:
        dt = mercurial.util.parsedate(datespec)
        spec = 's'

    return (spec, dt)

def find_strip_bases(repo, csets):
    '''
    Given a repository and a list of nodes, find the minimal set of bases to use
    when stripping off the corresponding changesets, without losing any other
    changesets.

    Algorithm:
    1. loop from tip to minrev(csets): if r not in csets, remove parent(r)
    2. loop over csets: add to bases if parent(r) not in csets
    3. return bases
    '''
    cl = repo.changelog
    minrev = min(cl.rev(n) for n in csets)
    csetbin = set(csets)
    for r in xrange(len(cl) - 1, minrev - 1, -1):
        if cl.node(r) not in csetbin:
            for p in cl.parentrevs(r):
                if p != -1:
                    csetbin.discard(cl.node(p))
    bases = []
    for n in csetbin:
        p = cl.parents(n)
        if p[0] not in csetbin and p[1] not in csetbin:
            bases.append(n)
    return bases

def get_update_changeset_choice(forest, module, candidates):
    return forest.ui.prompt('\nEnter update choice (s to skip, q to abort):').rstrip()

# todo: refactor with command.update
def timeupdate(ui, f, datespec, **opts):
    spec, date = parse_date(datespec)
    delta = opts['delta']
    branch = opts['branch'] and opts['branch'] or f.branch
    nodes = f.branch_tips(branch)

    if spec == 'r':
        mindate = date[0][0]
        maxdate = date[1][0]
    elif spec == 's':
        mindate = date[0]
        maxdate = date[0]
    elif spec == '<':
        mindate = None
        maxdate = date[0]
    elif spec == '>':
        mindate = date[0]
        maxdate = None

    modules = sorted(set(f) & set(nodes))

    # check for modified files
    for mod in modules:
        repo = f[mod]
        if repo[None].files() or repo[None].deleted():
            raise util.Abort('changed files in %s' % mod)

    def find_candidates(head):
        yield head
        for anc in head.ancestors():
            if anc.branch() == branch:
                yield anc

    def is_candidate(ctx, delta=0):
        ctxd = ctx.date()[0]

        if mindate is None:
            return ctxd <= maxdate + delta
        elif maxdate is None:
            return ctxd >= mindate - delta
        else:
            return mindate - delta <= ctxd <= maxdate + delta

    def prune_candidates(repo, cands):
        if spec == '<':
            cand = lambda x: repo[x].date() <= maxdate - delta
            splice = lambda x: x[-2:] if x else []
        else:
            cand = lambda x: repo[x].date() <= mindate + delta
            splice = lambda x: x[:2] if x else []

        ccands = [rev for rev in cands if cand(rev)]
        if ccands:
            return ccands
        return splice(cands)

    choices = {}
    branchmaps = f.branch_info(branch)

    for mod in modules:
        repo = f[mod]
        if not len(repo):
            ui.write_module_header(mod)
            ui.write('skipped; no revisions.\n\n')
            continue

        meta_candidates = set([repo[branchmap[mod]].rev() for rev, branchmap in branchmaps if mod in branchmap])
        repo_candidates = set([r.rev() for r in find_candidates(repo[nodes[mod]])])
        candidates = sorted(meta_candidates | repo_candidates)

        cands = [rev for rev in candidates if is_candidate(repo[rev])]
        if spec in ['<', '>']:
            cands = prune_candidates(repo, cands)

        if not cands:
            cands = [rev for rev in candidates if is_candidate(repo[rev], delta)]
            if not cands:
                maxr = [rev for rev in candidates if repo[rev].date()[0] <= mindate]
                minr = [rev for rev in candidates if repo[rev].date()[0] >= maxdate]
                if not maxr and not minr:
                    cands = []
                elif not maxr:
                    cands = [min(minr)]
                elif not minr:
                    cands = [max(maxr)]
                else:
                    cands = [max(maxr), min(minr)]

        ui.write_module_header(mod)
        maxrevlen = len(str(len(cands)))
        line1fmt = '%%-%dd:  %%s  %%s  (rev %%d)  %%s\n' % (maxrevlen,)
        line2fmt = '%%%ds   %%s\n' % (maxrevlen,)
        for i, rev in enumerate(cands):
            ctx = repo[rev]
            ui.write(line1fmt % (i + 1, 
                mercurial.node.short(ctx.node()),
                mercurial.util.datestr(ctx.date(), '%Y-%m-%d %H:%M:%S %1%2'),
                rev, util.longuser(ctx.user())))
            ui.write(line2fmt % ('', ctx.description().splitlines()[0]))

        while True:
            choice = get_update_changeset_choice(f, mod, cands)
            if choice in ['q', 'Q']:
                return
            elif choice in ['s', 'S']:
                break
            else:
                try:
                    choice = int(choice)
                    if 1 <= choice <= len(cands):
                        break
                except Exception:
                    continue
        if choice in ['s', 'S']:
            continue

        ui.write('\n')
        choices[mod] = cands[choice - 1]

    if choices:
        modtxt = modstr_tmpl(ui, list(choices))
        ui.write_header('Updating modules to selected changesets\n')

        for mod in sorted(choices):
            ui.status(modtxt % mod)
            repo = f[mod]
            stats = mercurial.merge.update(repo, repo[choices[mod]].node(), False, True, None)
            mercurial.hg._showstats(repo, stats)
            repo.dirstate.setbranch(f.branch)


def _parse_configuration(data, f):
    return data.replace('{GMD}', f.gmd_path)

def update_configurations(ui, f):
    header = '########### DO NOT EDIT BELOW THIS LINE ###########'
    footer = '########### DO NOT EDIT ABOVE THIS LINE ###########'

    modconfig = f.module_configurations
    for mod in f:
        if mod not in modconfig or not os.path.exists(modconfig[mod]):
            continue
        with codecs.open(modconfig[mod], 'rb', 'utf-8') as fh:
            data = _parse_configuration(fh.read(), f)

        data = '\n%s\n%s\n%s\n' % (header, data, footer)

        repo = f[mod]
        try:
            with codecs.open(repo.join('hgrc'), 'rb', 'utf-8') as fh:
                origdata = fh.read()
        except UnicodeDecodeError:
            with codecs.open(repo.join('hgrc'), 'rb', 'cp1252') as fh:
                origdata = fh.read()

        idx1 = origdata.find(header)
        idx2 = origdata.find(footer, idx1)
        if idx1 != -1 and idx2 != -1:
            origdata = origdata[:idx1] + origdata[idx2 + len(footer):]

        with codecs.open(repo.join('hgrc'), 'wb', 'utf-8') as fh:
            fh.write(origdata)
            fh.write(data)

#
# internal wrappable hooks
#

postpullhooks = []

def post_pull_hook(ui, forest, firstrevs, branches, modmap):
    for postpullhook in postpullhooks:
        postpullhook(ui, forest, firstrevs, branches, modmap)

def backup_changes(repo, rev):
    stats = repo.status(rev)
    backup = stats[0] + stats[2]
    for b in backup:
        path = repo.wjoin(b)
        if os.path.isfile(path):
            mercurial.util.copyfile(path, path + '.orig')