Exemple #1
0
def nclone(ui, source, dest=None, **opts):
    '''make a copy of an existing repository and all nested repositories

    Create a copy of an existing repository in a new directory.

    Look at the help of clone command for more informations.'''
    origsource = ui.expandpath(source)
    remotesource, remotebranch = hg.parseurl(origsource, opts.get('branch'))
    if hasattr(hg, 'peer'):
        remoterepo = hg.peer(ui, opts, remotesource)
        localrepo = remoterepo.local()
        if localrepo:
            remoterepo = localrepo
    else:
        remoterepo = hg.repository(hg.remoteui(ui, opts), remotesource)
    if dest is None:
        dest = hg.defaultdest(source)
        ui.status(_("destination directory: %s\n") % dest)
    for npath in remoterepo.nested:
        if npath == '.':
            npath = ''
        u = util.url(source)
        if u.scheme:
            nsource = '%s/%s' % (source, npath)
        else:
            nsource = os.path.join(source, npath)
        ndest = os.path.join(dest, npath)
        ui.status('[%s]\n' % os.path.normpath(
            os.path.join(os.path.basename(dest),
                ndest[len(dest) + 1:])))
        commands.clone(ui, nsource, dest=ndest, **opts)
        ui.status('\n')
Exemple #2
0
def convert(ui, src, dest=None, revmapfile=None, **opts):
    global orig_encoding
    orig_encoding = util._encoding
    util._encoding = 'UTF-8'

    if not dest:
        dest = hg.defaultdest(src) + "-hg"
        ui.status("assuming destination %s\n" % dest)

    destc = convertsink(ui, dest, opts.get('dest_type'))

    try:
        srcc = convertsource(ui, src, opts.get('source_type'),
                             opts.get('rev'))
    except Exception:
        for path in destc.created:
            shutil.rmtree(path, True)
        raise

    fmap = opts.get('filemap')
    if fmap:
        srcc = filemap.filemap_source(ui, srcc, fmap)
        destc.setfilemapmode(True)

    if not revmapfile:
        try:
            revmapfile = destc.revmapfile()
        except:
            revmapfile = os.path.join(destc, "map")

    c = converter(ui, srcc, destc, revmapfile, opts)
    c.convert()
Exemple #3
0
def convert(ui, src, dest=None, revmapfile=None, **opts):
    global orig_encoding
    orig_encoding = util._encoding
    util._encoding = 'UTF-8'

    if not dest:
        dest = hg.defaultdest(src) + "-hg"
        ui.status("assuming destination %s\n" % dest)

    destc = convertsink(ui, dest, opts.get('dest_type'))

    try:
        srcc = convertsource(ui, src, opts.get('source_type'), opts.get('rev'))
    except Exception:
        for path in destc.created:
            shutil.rmtree(path, True)
        raise

    fmap = opts.get('filemap')
    if fmap:
        srcc = filemap.filemap_source(ui, srcc, fmap)
        destc.setfilemapmode(True)

    if not revmapfile:
        try:
            revmapfile = destc.revmapfile()
        except:
            revmapfile = os.path.join(destc, "map")

    c = converter(ui, srcc, destc, revmapfile, opts)
    c.convert()
Exemple #4
0
def overrideclone(orig, ui, source, dest=None, **opts):
    d = dest
    if d is None:
        d = hg.defaultdest(source)
    if opts.get('all_largefiles') and not hg.islocal(d):
            raise util.Abort(_(
            '--all-largefiles is incompatible with non-local destination %s' %
            d))

    return orig(ui, source, dest, **opts)
def overrideclone(orig, ui, source, dest=None, **opts):
    d = dest
    if d is None:
        d = hg.defaultdest(source)
    if opts.get('all_largefiles') and not hg.islocal(d):
        raise util.Abort(
            _('--all-largefiles is incompatible with non-local destination %s'
              % d))

    return orig(ui, source, dest, **opts)
Exemple #6
0
def convert(ui, src, dest=None, revmapfile=None, **opts):
    opts = pycompat.byteskwargs(opts)
    global orig_encoding
    orig_encoding = encoding.encoding
    encoding.encoding = b'UTF-8'

    # support --authors as an alias for --authormap
    if not opts.get(b'authormap'):
        opts[b'authormap'] = opts.get(b'authors')

    if not dest:
        dest = hg.defaultdest(src) + b"-hg"
        ui.status(_(b"assuming destination %s\n") % dest)

    destc = convertsink(ui, dest, opts.get(b'dest_type'))
    destc = scmutil.wrapconvertsink(destc)

    try:
        srcc, defaultsort = convertsource(
            ui, src, opts.get(b'source_type'), opts.get(b'rev')
        )
    except Exception:
        for path in destc.created:
            shutil.rmtree(path, True)
        raise

    sortmodes = (b'branchsort', b'datesort', b'sourcesort', b'closesort')
    sortmode = [m for m in sortmodes if opts.get(m)]
    if len(sortmode) > 1:
        raise error.Abort(_(b'more than one sort mode specified'))
    if sortmode:
        sortmode = sortmode[0]
    else:
        sortmode = defaultsort

    if sortmode == b'sourcesort' and not srcc.hasnativeorder():
        raise error.Abort(
            _(b'--sourcesort is not supported by this data source')
        )
    if sortmode == b'closesort' and not srcc.hasnativeclose():
        raise error.Abort(
            _(b'--closesort is not supported by this data source')
        )

    fmap = opts.get(b'filemap')
    if fmap:
        srcc = filemap.filemap_source(ui, srcc, fmap)
        destc.setfilemapmode(True)

    if not revmapfile:
        revmapfile = destc.revmapfile()

    c = converter(ui, srcc, destc, revmapfile, opts)
    c.convert(sortmode)
Exemple #7
0
def clone(ui, source, dest=None, *subtreeargs, **opts):
    '''copy one or more existing repositories to create a tree'''
    global hg_clone
    if not hg_clone:
        hg_clone = compatible_clone()
    if subtreeargs:
        s = __builtin__.list(subtreeargs)
        s.extend(opts.get('subtrees')) # Note:  extend does not return a value
        opts['subtrees'] = s
    if dest is None:
        dest = hg.defaultdest(source)
    _clone(ui, source, dest, opts, opts.get('skiproot'))
    return 0
Exemple #8
0
def clone(ui, source, dest=None, *subtreeargs, **opts):
    '''copy one or more existing repositories to create a tree'''
    global hg_clone
    if not hg_clone:
        hg_clone = compatible_clone()
    if subtreeargs:
        s = __builtin__.list(subtreeargs)
        s.extend(opts.get('subtrees'))  # Note:  extend does not return a value
        opts['subtrees'] = s
    if dest is None:
        dest = hg.defaultdest(source)
    _clone(ui, source, dest, opts, opts.get('skiproot'))
    return 0
Exemple #9
0
def convert(ui, src, dest=None, revmapfile=None, **opts):
    global orig_encoding
    orig_encoding = encoding.encoding
    encoding.encoding = 'UTF-8'

    # support --authors as an alias for --authormap
    if not opts.get('authormap'):
        opts['authormap'] = opts.get('authors')

    if not dest:
        dest = hg.defaultdest(src) + "-hg"
        ui.status(_("assuming destination %s\n") % dest)

    destc = convertsink(ui, dest, opts.get('dest_type'))

    try:
        srcc, defaultsort = convertsource(ui, src, opts.get('source_type'),
                                          opts.get('rev'))
    except Exception:
        for path in destc.created:
            shutil.rmtree(path, True)
        raise

    sortmodes = ('branchsort', 'datesort', 'sourcesort', 'closesort')
    sortmode = [m for m in sortmodes if opts.get(m)]
    if len(sortmode) > 1:
        raise error.Abort(_('more than one sort mode specified'))
    if sortmode:
        sortmode = sortmode[0]
    else:
        sortmode = defaultsort

    if sortmode == 'sourcesort' and not srcc.hasnativeorder():
        raise error.Abort(_('--sourcesort is not supported by this data source')
                         )
    if sortmode == 'closesort' and not srcc.hasnativeclose():
        raise error.Abort(_('--closesort is not supported by this data source'))

    fmap = opts.get('filemap')
    if fmap:
        srcc = filemap.filemap_source(ui, srcc, fmap)
        destc.setfilemapmode(True)

    if not revmapfile:
        revmapfile = destc.revmapfile()

    c = converter(ui, srcc, destc, revmapfile, opts)
    c.convert(sortmode)
Exemple #10
0
def convert(ui, src, dest=None, revmapfile=None, **opts):
    global orig_encoding
    orig_encoding = encoding.encoding
    encoding.encoding = 'UTF-8'

    # support --authors as an alias for --authormap
    if not opts.get('authormap'):
        opts['authormap'] = opts.get('authors')

    if not dest:
        dest = hg.defaultdest(src) + "-hg"
        ui.status(_("assuming destination %s\n") % dest)

    destc = convertsink(ui, dest, opts.get('dest_type'))

    try:
        srcc, defaultsort = convertsource(ui, src, opts.get('source_type'),
                                          opts.get('rev'))
    except Exception:
        for path in destc.created:
            shutil.rmtree(path, True)
        raise

    sortmodes = ('branchsort', 'datesort', 'sourcesort', 'closesort')
    sortmode = [m for m in sortmodes if opts.get(m)]
    if len(sortmode) > 1:
        raise util.Abort(_('more than one sort mode specified'))
    sortmode = sortmode and sortmode[0] or defaultsort
    if sortmode == 'sourcesort' and not srcc.hasnativeorder():
        raise util.Abort(
            _('--sourcesort is not supported by this data source'))
    if sortmode == 'closesort' and not srcc.hasnativeclose():
        raise util.Abort(_('--closesort is not supported by this data source'))

    fmap = opts.get('filemap')
    if fmap:
        srcc = filemap.filemap_source(ui, srcc, fmap)
        destc.setfilemapmode(True)

    if not revmapfile:
        try:
            revmapfile = destc.revmapfile()
        except Exception:
            revmapfile = os.path.join(destc, "map")

    c = converter(ui, srcc, destc, revmapfile, opts)
    c.convert(sortmode)
Exemple #11
0
def gclone(ui, git_url, hg_repo_path=None):
    # determine new repo name
    if not hg_repo_path:
        hg_repo_path = hg.defaultdest(git_url)
        if hg_repo_path.endswith('.git'):
            hg_repo_path = hg_repo_path[:-4]
        hg_repo_path += '-hg'
    dest_repo = hg.repository(ui, hg_repo_path, create=True)

    # fetch the initial git data
    git = GitHandler(dest_repo, ui)
    git.remote_add('origin', git_url)
    git.fetch('origin')
    
    # checkout the tip
    node = git.remote_head('origin')
    hg.update(dest_repo, node)
Exemple #12
0
def _suggesteddest(src, basedest):
    if '://' in basedest:
        return basedest
    try:
        if not os.listdir(basedest):
            # premade empty directory, just use it
            return basedest
    except OSError:
        # guess existing base assuming "{basedest}/{name}"
        basedest = os.path.dirname(basedest)
    name = hglib.tounicode(hg.defaultdest(hglib.fromunicode(src, 'replace')))
    if not name or name == '.':
        return basedest
    newdest = os.path.join(basedest, name)
    if os.path.exists(newdest):
        newdest += '-clone'
    return newdest
Exemple #13
0
def _suggesteddest(src, basedest):
    if '://' in basedest:
        return basedest
    try:
        if not os.listdir(basedest):
            # premade empty directory, just use it
            return basedest
    except OSError:
        # guess existing base assuming "{basedest}/{name}"
        basedest = os.path.dirname(basedest)
    name = hglib.tounicode(hg.defaultdest(hglib.fromunicode(src, 'replace')))
    if not name or name == '.':
        return basedest
    newdest = os.path.join(basedest, name)
    if os.path.exists(newdest):
        newdest += '-clone'
    return newdest
Exemple #14
0
def share(orig, ui, source, *args, **kwargs):
    """Wraps hg.share to mark the firefoxtrees file as shared.

    The .hg/shared file lists things that are shared. We add firefoxtrees
    to it if we are a Firefox repo.
    """
    res = orig(ui, source, *args, **kwargs)

    # TODO Mercurial 3.7 introduces a standalone function that receives the
    # proper arguments so we can avoid this boilerplate.
    if isinstance(source, str):
        origsource = ui.expandpath(source)
        source, branches = hg.parseurl(origsource)
        srcrepo = hg.repository(ui, source)
    else:
        srcrepo = source.local()

    if not isfirefoxrepo(srcrepo):
        return res

    if args:
        dest = args[0]
    elif 'dest' in kwargs:
        dest = kwargs['dest']
    else:
        dest = None

    if not dest:
        dest = hg.defaultdest(source)
    else:
        dest = ui.expandpath(dest)

    try:
        from mercurial.vfs import vfs
    except ImportError:
        vfs = scmutil.vfs

    destwvfs = vfs(dest, realpath=True)
    r = hg.repository(ui, destwvfs.base)

    with r.wlock():
        with r.vfs('shared', 'ab') as fh:
            fh.write('firefoxtrees\n')

    return res
Exemple #15
0
def share(orig, ui, source, *args, **kwargs):
    """Wraps hg.share to mark the firefoxtrees file as shared.

    The .hg/shared file lists things that are shared. We add firefoxtrees
    to it if we are a Firefox repo.
    """
    res = orig(ui, source, *args, **kwargs)

    if not util.safehasattr(source, 'local'):
        origsource = ui.expandpath(source)
        source, branches = hg.parseurl(origsource)
        srcrepo = hg.repository(ui, source)
    else:
        srcrepo = source.local()

    if not isfirefoxrepo(srcrepo):
        return res

    if args:
        dest = args[0]
    elif 'dest' in kwargs:
        dest = kwargs['dest']
    else:
        dest = None

    if not dest:
        dest = hg.defaultdest(source)
    else:
        dest = ui.expandpath(dest)

    try:
        from mercurial.vfs import vfs
    except ImportError:
        vfs = scmutil.vfs

    destwvfs = vfs(dest, realpath=True)
    r = hg.repository(ui, destwvfs.base)

    with r.wlock():
        with r.vfs(b'shared', b'ab') as fh:
            fh.write(b'firefoxtrees\n')

    return res
Exemple #16
0
    def __init__(self, ui, path, create=True):
        dest = hg.defaultdest(path)

        if dest.endswith('.git'):
            dest = dest[:-4]

        # create the local hg repo on disk
        dest_repo = hg.repository(ui, dest, create=True)

        # fetch the initial git data
        git = GitHandler(dest_repo, ui)
        git.remote_add('origin', path)
        git.fetch('origin')

        # checkout the tip
        node = git.remote_head('origin')
        hg.update(dest_repo, node)

        # exit to stop normal `hg clone` flow
        raise SystemExit
def clone(ui, source, dest=None, **opts):
    """make a clone of an existing forest of repositories

    Create a clone of an existing forest in a new directory.

    Look at the help text for the clone command for more information.
    """
    die_on_numeric_revs(opts['rev'])
    source = ui.expandpath(source) or source
    islocalsrc = hg.islocal(source)
    if islocalsrc:
        source = os.path.abspath(urltopath(source))
    if dest:
        if hg.islocal(dest):
            dest = os.path.normpath(dest)
        else:
            pass
    else:
        dest = hg.defaultdest(source)
    toprepo = hg.repository(ui, source)
    forests = toprepo.forests(walkhgenabled(ui, opts['walkhg']))
    for rpath in forests:
        if rpath == '.':
            rpath = ''
        if islocalsrc:
            srcpath = source
            srcpath = os.path.join(source, util.localpath(rpath))
        else:
            srcpath = '/'.join((source, rpath))
        if rpath:
            destpath = os.path.join(dest, util.localpath(rpath))
        else:
            destpath = dest
        try:
            qclone(ui=ui,
                   source=srcpath, sroot=source,
                   dest=destpath, rpath=os.path.normpath(rpath),
                   opts=opts)
        except util.Abort, err:
            ui.warn(_("skipped: %s\n") % err)
        ui.status("\n")
Exemple #18
0
def nshare(ui, source, dest=None, noupdate=False):
    '''create a new shared repository and all nested repositories
    '''
    sourcerepo = hg.repository(ui, source)
    if dest is None:
        dest = hg.defaultdest(source)
        ui.status(_("destination directory: %s\n") % dest)
    for npath in sourcerepo.nested:
        if npath == '.':
            npath = ''
        u = util.url(source)
        if u.scheme:
            nsource = '%s/%s' % (source, npath)
        else:
            nsource = os.path.join(source, npath)
        ndest = os.path.join(dest, npath)
        ui.status('[%s]\n' % os.path.normpath(
            os.path.join(os.path.basename(dest),
                ndest[len(dest) + 1:])))
        hg.share(ui, nsource, ndest, not noupdate)
        ui.status('\n')
def share(orig, ui, source, *args, **kwargs):
    """Wraps hg.share to mark the firefoxtrees file as shared.

    The .hg/shared file lists things that are shared. We add firefoxtrees
    to it if we are a Firefox repo.
    """
    res = orig(ui, source, *args, **kwargs)

    # TODO Mercurial 3.7 introduces a standalone function that receives the
    # proper arguments so we can avoid this boilerplate.
    if isinstance(source, str):
        origsource = ui.expandpath(source)
        source, branches = hg.parseurl(origsource)
        srcrepo = hg.repository(ui, source)
    else:
        srcrepo = source.local()

    if not isfirefoxrepo(srcrepo):
        return res

    if args:
        dest = args[0]
    elif 'dest' in kwargs:
        dest = kwargs['dest']
    else:
        dest = None

    if not dest:
        dest = hg.defaultdest(source)
    else:
        dest = ui.expandpath(dest)

    destwvfs = scmutil.vfs(dest, realpath=True)
    r = hg.repository(ui, destwvfs.base)

    with r.vfs('shared', 'ab') as fh:
        fh.write('firefoxtrees\n')

    return res
Exemple #20
0
def convert(ui, src, dest=None, revmapfile=None, **opts):
    global orig_encoding
    orig_encoding = encoding.encoding
    encoding.encoding = "UTF-8"

    if not dest:
        dest = hg.defaultdest(src) + "-hg"
        ui.status(_("assuming destination %s\n") % dest)

    destc = convertsink(ui, dest, opts.get("dest_type"))

    try:
        srcc, defaultsort = convertsource(ui, src, opts.get("source_type"), opts.get("rev"))
    except Exception:
        for path in destc.created:
            shutil.rmtree(path, True)
        raise

    sortmodes = ("branchsort", "datesort", "sourcesort")
    sortmode = [m for m in sortmodes if opts.get(m)]
    if len(sortmode) > 1:
        raise util.Abort(_("more than one sort mode specified"))
    sortmode = sortmode and sortmode[0] or defaultsort
    if sortmode == "sourcesort" and not srcc.hasnativeorder():
        raise util.Abort(_("--sourcesort is not supported by this data source"))

    fmap = opts.get("filemap")
    if fmap:
        srcc = filemap.filemap_source(ui, srcc, fmap)
        destc.setfilemapmode(True)

    if not revmapfile:
        try:
            revmapfile = destc.revmapfile()
        except:
            revmapfile = os.path.join(destc, "map")

    c = converter(ui, srcc, destc, revmapfile, opts)
    c.convert(sortmode)
Exemple #21
0
def clone_cache_cmd(ui, source, dest=None, **opts):
    source_url = url(source)
    if source_url.fragment is not None:
        raise ValueError('Someone is being clever! We are not clever. Bail.')

    orig_source = source
    cache_source = os.path.join(CACHE, url_to_filename(source))
    was_cached = False
    clone_source = source
    if not opts.get('nocache'):
        was_cached = os.path.exists(cache_source)
        if was_cached:
            ui.status('cloning from cache {}\n'.format(cache_source))
            clone_source = cache_source
            if dest is None:
                dest = hg.defaultdest(source)
            if opts.get('rev'):
                ui.status('updating cache {} to rev {}\n'.format(cache_source, opts.get('rev')))
                cache_peer = hg.peer(ui, {}, cache_source)
                commands.pull(cache_peer.ui, cache_peer.local(), noupdate=True, rev=opts.get('rev'))
        else:
            ui.status('no cache found at {}, cloning from source {}\n'.format(
                cache_source, source))
    
    if opts.get('noupdate') and opts.get('updaterev'):
        raise util.Abort(_("cannot specify both --noupdate and --updaterev"))

    r = hg.clone(ui, opts, clone_source, dest,
                 pull=opts.get('pull'),
                 stream=opts.get('uncompressed'),
                 rev=opts.get('rev'),
                 update=opts.get('updaterev') or not opts.get('noupdate'),
                 branch=opts.get('branch'))

    if r is None:
        return True

    source_peer, dest_peer = r

    if was_cached:
        dest_repo = dest_peer.local()
        if dest_repo:
            orig_source = dest_repo.ui.expandpath(orig_source)
            abspath = orig_source
            if hg.islocal(orig_source):
                abspath = os.path.abspath(hg.util.urllocalpath(orig_source))

            u = url(abspath)
            u.passwd = None
            defaulturl = str(u)
            fp = dest_repo.opener("hgrc", "w", text=True)
            fp.write("[paths]\n")
            fp.write("default = %s\n" % defaulturl)
            fp.write('\n')
            fp.write('[clonecache]\n')
            fp.write('cache = %s\n' % cache_source)
            fp.close()

            dest_repo.ui.setconfig('paths', 'default', defaulturl, 'clone')

            commands.pull(dest_repo.ui, dest_repo)

            commands.update(ui, dest_repo)

    return False
Exemple #22
0
def freenetclone(orig, *args, **opts):
    def parsepushargs(ui, repo, path=None):
        return ui, repo, path

    def isfreenetpath(path):
        try:
            if path.startswith("freenet:") or path.startswith("USK@"):
                return True
        except AttributeError:
            return False
        return False
    ui, source, dest = parsepushargs(*args)
    # only act differently, if dest or source is an infocalypse repo.
    if not isfreenetpath(source) and not isfreenetpath(dest):
        return orig(*args, **opts)

    if not dest:
        if not isfreenetpath(source):
            dest = hg.defaultdest(source)
        else: # this is a freenet key.  It has a /# at the end and
              # could contain .R1 or .R0 as pure technical identifiers
              # which we do not need in the local name.
            segments = source.split("/")
            pathindex = -2
            try:
                int(segments[-1])
            except ValueError: # no number revision
                pathindex = -1
            dest = segments[pathindex]
            if dest.endswith(".R1") or dest.endswith(".R0"):
                dest = dest[:-3]

    # TODO: source holds the "repo" argument, but the naming is confusing in
    # the context of freenetpathtouri().
    # check whether to create, pull or copy
    pulluri, pushuri = None, None
    if isfreenetpath(source):
        pulluri = parse_repo_path(
            freenetpathtouri(ui, source, "pull", None, opts.get('truster')))

    if isfreenetpath(dest):
        pushuri = parse_repo_path(freenetpathtouri(ui, dest, "clone-push", fcphost = opts['fcphost'], fcpport = opts['fcpport']),
                                  assume_redundancy=True)

    # decide which infocalypse command to use.
    if pulluri and pushuri:
        action = "copy"
    elif pulluri:
        action = "pull"
    elif pushuri:
        action = "create"
    else: 
        raise util.Abort("""Can't clone without source and target. This message should not be reached. If you see it, this is a bug.""")

    if action == "copy":
        raise util.Abort("""Cloning without intermediate local repo not yet supported in the simplified commands. Use fn-copy directly.""")
    
    if action == "create":
        # if the pushuri is the short form (USK@/name/#), generate the key.
        if pushuri.startswith("USK@/"):
            ui.status("creating a new key for the repo. To use your default key, call fn-create.\n")
            from sitecmds import genkeypair
            fcphost, fcpport = opts["fcphost"], opts["fcpport"]
            if not fcphost:
                fcphost = DEFAULT_FCP_HOST
            if not fcpport:
                fcpport = DEFAULT_FCP_PORT
            
            # use redundant keys by default, except if explicitely requested otherwise.
            namepart = pushuri[5:]
            namepart = fixnamepart(namepart)
            insert, request = genkeypair(fcphost, fcpport)
            pushuri = "USK"+insert[3:]+namepart
        elif pushuri.endswith("/0"): # initial create, catch the no-.R1 error
            pass
            # this rewriting is dangerous here since it could make it
            # impossible to update old repos when they drop
            # out. Leaving it commented out for now. TODO: Always
            # treat a name without .R0 as requesting redundancy *in.
            # the backend*. Keep it as /name/#, but add /name.Rn/0
            # backup repos. Needs going into the backend.

            #namepart = pushuri.split("/")[-2] + "/0"
            #namepartpos = -len(namepart)
            #namepart2 = fixnamepart(namepart)
            # if namepart2 != namepart:
            # ui.status("changed the repo name to " + namepart2 + " to have more redundancy and longer lifetime. This is a small tweak on infocalypse to avoid the frequent error of forgetting to add .R1 to the name. If you really want no additional redundancy for your repo, use NAME.R0 or call hg fn-create directly.\n")
            #pushuri = pushuri[:namepartpos] + namepart
        opts["uri"] = pushuri
        repo = hg.repository(ui, ui.expandpath(source))
        # TODO: A local identity is looked up for the push URI,
        # but not returned, yet it is required to update configuration.
        # Expecting dest to be something like freenet://name@key/reponame
        local_identifier = strip_protocol(dest).split('/')[0]

        from wot_id import Local_WoT_ID
        from wot import get_fcpopts
        local_identity = Local_WoT_ID(local_identifier,
                                      get_fcpopts(fcphost=opts["fcphost"],
                                                  fcpport=opts["fcpport"]))

        infocalypse_create(ui, repo, local_identity, **opts)

        # TODO: Function for adding paths? It's currently here, for pull,
        # and in WoT pull URI resolution.
        with repo.opener("hgrc", "a", text=True) as f:
            f.write("""[paths]
default-push = freenet:{0}
""".format(pushuri))

    if action == "pull":
        if os.path.exists(dest):
            raise util.Abort(_("destination " + dest + " already exists."))
        # create the repo
        req = dispatch.request(["init", dest], ui=ui)
        dispatch.dispatch(req)
        # pull the data from freenet
        origdest = ui.expandpath(dest)
        dest, branch = hg.parseurl(origdest)
        destrepo = hg.repository(ui, dest)
        infocalypse_pull(ui, destrepo, aggressive=True, hash=None, uri=pulluri, **opts)
        # store the request uri for future updates
        _hgrc_template = """[paths]
default = freenet://{pulluri}

[ui]
username = anonymous

[alias]
clt = commit
ci = !$HG clt --date "$(date -u "+%Y-%m-%d %H:%M:%S +0000")" "$@"
commit = !$HG clt --date "$(date -u "+%Y-%m-%d %H:%M:%S +0000")" "$@"
"""
        # alternative: every commit is done at 09:42:30 (might be
        # confusing but should be safest): date -u "+%Y-%m-%d 09:42:30 +0000
        
        # second alternative: commit done at local time but with
        # timezone +0000 (could be correlated against forum entries
        # and such to find the real timezone): Leave out the -u
        with destrepo.opener("hgrc", "a", text=True) as f:
            f.write(_hgrc_template.format(pulluri=pulluri))
        
        ui.warn("As basic protection, infocalypse automatically \n"
                "  set the username 'anonymous' for commits in this repo, \n"
                "  changed the commands `commit` and `ci` to fake UTC time \n"
                "  and added `clt` which commits in the local timezone. \n"
                "  To change this, edit " 
                + str(os.path.join(destrepo.root, ".hg", "hgrc"))
                + "\n")
        # and update the repo
        return hg.update(destrepo, None)
Exemple #23
0
def freenetclone(orig, *args, **opts):
    def parsepushargs(ui, repo, path=None):
        return ui, repo, path

    def isfreenetpath(path):
        try:
            if path.startswith("freenet:") or path.startswith("USK@"):
                return True
        except AttributeError:
            return False
        return False

    ui, source, dest = parsepushargs(*args)
    # only act differently, if dest or source is an infocalypse repo.
    if not isfreenetpath(source) and not isfreenetpath(dest):
        return orig(*args, **opts)

    if not dest:
        if not isfreenetpath(source):
            dest = hg.defaultdest(source)
        else:  # this is a freenet key.  It has a /# at the end and
            # could contain .R1 or .R0 as pure technical identifiers
            # which we do not need in the local name.
            segments = source.split("/")
            pathindex = -2
            try:
                int(segments[-1])
            except ValueError:  # no number revision
                pathindex = -1
            dest = segments[pathindex]
            if dest.endswith(".R1") or dest.endswith(".R0"):
                dest = dest[:-3]

    # TODO: source holds the "repo" argument, but the naming is confusing in
    # the context of freenetpathtouri().
    # check whether to create, pull or copy
    pulluri, pushuri = None, None
    if isfreenetpath(source):
        pulluri = parse_repo_path(
            freenetpathtouri(ui, source, "pull", None, opts.get('truster')))

    if isfreenetpath(dest):
        pushuri = parse_repo_path(freenetpathtouri(ui,
                                                   dest,
                                                   "clone-push",
                                                   fcphost=opts['fcphost'],
                                                   fcpport=opts['fcpport']),
                                  assume_redundancy=True)

    # decide which infocalypse command to use.
    if pulluri and pushuri:
        action = "copy"
    elif pulluri:
        action = "pull"
    elif pushuri:
        action = "create"
    else:
        raise util.Abort(
            """Can't clone without source and target. This message should not be reached. If you see it, this is a bug."""
        )

    if action == "copy":
        raise util.Abort(
            """Cloning without intermediate local repo not yet supported in the simplified commands. Use fn-copy directly."""
        )

    if action == "create":
        # if the pushuri is the short form (USK@/name/#), generate the key.
        if pushuri.startswith("USK@/"):
            ui.status(
                "creating a new key for the repo. To use your default key, call fn-create.\n"
            )
            from sitecmds import genkeypair
            fcphost, fcpport = opts["fcphost"], opts["fcpport"]
            if not fcphost:
                fcphost = DEFAULT_FCP_HOST
            if not fcpport:
                fcpport = DEFAULT_FCP_PORT

            # use redundant keys by default, except if explicitely requested otherwise.
            namepart = pushuri[5:]
            namepart = fixnamepart(namepart)
            insert, request = genkeypair(fcphost, fcpport)
            pushuri = "USK" + insert[3:] + namepart
        elif pushuri.endswith("/0"):  # initial create, catch the no-.R1 error
            pass
            # this rewriting is dangerous here since it could make it
            # impossible to update old repos when they drop
            # out. Leaving it commented out for now. TODO: Always
            # treat a name without .R0 as requesting redundancy *in.
            # the backend*. Keep it as /name/#, but add /name.Rn/0
            # backup repos. Needs going into the backend.

            #namepart = pushuri.split("/")[-2] + "/0"
            #namepartpos = -len(namepart)
            #namepart2 = fixnamepart(namepart)
            # if namepart2 != namepart:
            # ui.status("changed the repo name to " + namepart2 + " to have more redundancy and longer lifetime. This is a small tweak on infocalypse to avoid the frequent error of forgetting to add .R1 to the name. If you really want no additional redundancy for your repo, use NAME.R0 or call hg fn-create directly.\n")
            #pushuri = pushuri[:namepartpos] + namepart
        opts["uri"] = pushuri
        repo = hg.repository(ui, ui.expandpath(source))
        # TODO: A local identity is looked up for the push URI,
        # but not returned, yet it is required to update configuration.
        # Expecting dest to be something like freenet://name@key/reponame
        local_identifier = strip_protocol(dest).split('/')[0]

        from wot_id import Local_WoT_ID
        from wot import get_fcpopts
        local_identity = Local_WoT_ID(
            local_identifier,
            get_fcpopts(fcphost=opts["fcphost"], fcpport=opts["fcpport"]))

        infocalypse_create(ui, repo, local_identity, **opts)

        # TODO: Function for adding paths? It's currently here, for pull,
        # and in WoT pull URI resolution.
        with repo.opener("hgrc", "a", text=True) as f:
            f.write("""[paths]
default-push = freenet:{0}
""".format(pushuri))

    if action == "pull":
        if os.path.exists(dest):
            raise util.Abort(_("destination " + dest + " already exists."))
        # create the repo
        req = dispatch.request(["init", dest], ui=ui)
        dispatch.dispatch(req)
        # pull the data from freenet
        origdest = ui.expandpath(dest)
        dest, branch = hg.parseurl(origdest)
        destrepo = hg.repository(ui, dest)
        infocalypse_pull(ui,
                         destrepo,
                         aggressive=True,
                         hash=None,
                         uri=pulluri,
                         **opts)
        # store the request uri for future updates
        _hgrc_template = """[paths]
default = freenet://{pulluri}

[ui]
username = anonymous

[alias]
clt = commit
ci = !$HG clt --date "$(date -u "+%Y-%m-%d %H:%M:%S +0000")" "$@"
commit = !$HG clt --date "$(date -u "+%Y-%m-%d %H:%M:%S +0000")" "$@"
"""
        # alternative: every commit is done at 09:42:30 (might be
        # confusing but should be safest): date -u "+%Y-%m-%d 09:42:30 +0000

        # second alternative: commit done at local time but with
        # timezone +0000 (could be correlated against forum entries
        # and such to find the real timezone): Leave out the -u
        with destrepo.opener("hgrc", "a", text=True) as f:
            f.write(_hgrc_template.format(pulluri=pulluri))

        ui.warn("As basic protection, infocalypse automatically \n"
                "  set the username 'anonymous' for commits in this repo, \n"
                "  changed the commands `commit` and `ci` to fake UTC time \n"
                "  and added `clt` which commits in the local timezone. \n"
                "  To change this, edit " +
                str(os.path.join(destrepo.root, ".hg", "hgrc")) + "\n")
        # and update the repo
        return hg.update(destrepo, None)