def put(self, source, hash):
     if self.sendfile(source, hash):
         raise error.Abort(
             _(b'remotestore: could not put %s to remote store %s') %
             (source, urlutil.hidepassword(self.url)))
     self.ui.debug(
         _(b'remotestore: put %s to remote store %s\n') %
         (source, urlutil.hidepassword(self.url)))
 def longmessage(self):
     return _(b"error getting id %s from url %s for file %s: %s\n") % (
         self.hash,
         urlutil.hidepassword(self.url),
         self.filename,
         self.detail,
     )
def openstore(repo=None, remote=None, put=False, ui=None):
    if ui is None:
        ui = repo.ui

    if not remote:
        lfpullsource = getattr(repo, 'lfpullsource', None)
        if put:
            path = urlutil.get_unique_push_path(
                b'lfpullsource', repo, ui, lfpullsource
            )
        else:
            path, _branches = urlutil.get_unique_pull_path(
                b'lfpullsource', repo, ui, lfpullsource
            )

        # XXX we should not explicitly pass b'default', as this will result in
        # b'default' being returned if no `paths.default` was defined. We
        # should explicitely handle the lack of value instead.
        if repo is None:
            path, _branches = urlutil.get_unique_pull_path(
                b'lfs', repo, ui, b'default'
            )
            remote = hg.peer(repo or ui, {}, path)
        elif path == b'default-push' or path == b'default':
            remote = repo
        else:
            path, _branches = urlutil.parseurl(path)
            remote = hg.peer(repo or ui, {}, path)

    # The path could be a scheme so use Mercurial's normal functionality
    # to resolve the scheme to a repository and use its path
    path = util.safehasattr(remote, b'url') and remote.url() or remote.path

    match = _scheme_re.match(path)
    if not match:  # regular filesystem path
        scheme = b'file'
    else:
        scheme = match.group(1)

    try:
        storeproviders = _storeprovider[scheme]
    except KeyError:
        raise error.Abort(_(b'unsupported URL scheme %r') % scheme)

    for classobj in storeproviders:
        try:
            return classobj(ui, repo, remote)
        except lfutil.storeprotonotcapable:
            pass

    raise error.Abort(
        _(b'%s does not appear to be a largefile store')
        % urlutil.hidepassword(path)
    )
def _getoutgoing(repo, dest, revs):
    '''Return the revisions present locally but not in dest'''
    ui = repo.ui
    paths = urlutil.get_push_paths(repo, ui, [dest])
    safe_paths = [urlutil.hidepassword(p.rawloc) for p in paths]
    ui.status(_(b'comparing with %s\n') % b','.join(safe_paths))

    revs = [r for r in revs if r >= 0]
    if not revs:
        revs = [repo.changelog.tiprev()]
    revs = repo.revs(b'outgoing(%s) and ::%ld', dest or b'', revs)
    if not revs:
        ui.status(_(b"no changes found\n"))
    return revs
    def _getfile(self, tmpfile, filename, hash):
        try:
            chunks = self._get(hash)
        except urlerr.httperror as e:
            # 401s get converted to error.Aborts; everything else is fine being
            # turned into a StoreError
            raise basestore.StoreError(filename, hash, self.url,
                                       stringutil.forcebytestr(e))
        except urlerr.urlerror as e:
            # This usually indicates a connection problem, so don't
            # keep trying with the other files... they will probably
            # all fail too.
            raise error.Abort(b'%s: %s' %
                              (urlutil.hidepassword(self.url), e.reason))
        except IOError as e:
            raise basestore.StoreError(filename, hash, self.url,
                                       stringutil.forcebytestr(e))

        return lfutil.copyandhash(chunks, tmpfile)
    def get(self, files):
        """Get the specified largefiles from the store and write to local
        files under repo.root.  files is a list of (filename, hash)
        tuples.  Return (success, missing), lists of files successfully
        downloaded and those not found in the store.  success is a list
        of (filename, hash) tuples; missing is a list of filenames that
        we could not get.  (The detailed error message will already have
        been presented to the user, so missing is just supplied as a
        summary.)"""
        success = []
        missing = []
        ui = self.ui

        at = 0
        available = self.exists({hash for (_filename, hash) in files})
        with ui.makeprogress(_(b'getting largefiles'),
                             unit=_(b'files'),
                             total=len(files)) as progress:
            for filename, hash in files:
                progress.update(at)
                at += 1
                ui.note(_(b'getting %s:%s\n') % (filename, hash))

                if not available.get(hash):
                    ui.warn(
                        _(b'%s: largefile %s not available from %s\n') %
                        (filename, hash, urlutil.hidepassword(self.url)))
                    missing.append(filename)
                    continue

                if self._gethash(filename, hash):
                    success.append((filename, hash))
                else:
                    missing.append(filename)

        return (success, missing)
Beispiel #7
0
def trackedcmd(ui, repo, remotepath=None, *pats, **opts):
    """show or change the current narrowspec

    With no argument, shows the current narrowspec entries, one per line. Each
    line will be prefixed with 'I' or 'X' for included or excluded patterns,
    respectively.

    The narrowspec is comprised of expressions to match remote files and/or
    directories that should be pulled into your client.
    The narrowspec has *include* and *exclude* expressions, with excludes always
    trumping includes: that is, if a file matches an exclude expression, it will
    be excluded even if it also matches an include expression.
    Excluding files that were never included has no effect.

    Each included or excluded entry is in the format described by
    'hg help patterns'.

    The options allow you to add or remove included and excluded expressions.

    If --clear is specified, then all previous includes and excludes are DROPPED
    and replaced by the new ones specified to --addinclude and --addexclude.
    If --clear is specified without any further options, the narrowspec will be
    empty and will not match any files.

    If --auto-remove-includes is specified, then those includes that don't match
    any files modified by currently visible local commits (those not shared by
    the remote) will be added to the set of explicitly specified includes to
    remove.

    --import-rules accepts a path to a file containing rules, allowing you to
    add --addinclude, --addexclude rules in bulk. Like the other include and
    exclude switches, the changes are applied immediately.
    """
    opts = pycompat.byteskwargs(opts)
    if requirements.NARROW_REQUIREMENT not in repo.requirements:
        raise error.InputError(
            _(b'the tracked command is only supported on '
              b'repositories cloned with --narrow'))

    # Before supporting, decide whether it "hg tracked --clear" should mean
    # tracking no paths or all paths.
    if opts[b'clear']:
        raise error.InputError(_(b'the --clear option is not yet supported'))

    # import rules from a file
    newrules = opts.get(b'import_rules')
    if newrules:
        try:
            filepath = os.path.join(encoding.getcwd(), newrules)
            fdata = util.readfile(filepath)
        except IOError as inst:
            raise error.StorageError(
                _(b"cannot read narrowspecs from '%s': %s") %
                (filepath, encoding.strtolocal(inst.strerror)))
        includepats, excludepats, profiles = sparse.parseconfig(
            ui, fdata, b'narrow')
        if profiles:
            raise error.InputError(
                _(b"including other spec files using '%include' "
                  b"is not supported in narrowspec"))
        opts[b'addinclude'].extend(includepats)
        opts[b'addexclude'].extend(excludepats)

    addedincludes = narrowspec.parsepatterns(opts[b'addinclude'])
    removedincludes = narrowspec.parsepatterns(opts[b'removeinclude'])
    addedexcludes = narrowspec.parsepatterns(opts[b'addexclude'])
    removedexcludes = narrowspec.parsepatterns(opts[b'removeexclude'])
    autoremoveincludes = opts[b'auto_remove_includes']

    update_working_copy = opts[b'update_working_copy']
    only_show = not (addedincludes or removedincludes or addedexcludes
                     or removedexcludes or newrules or autoremoveincludes
                     or update_working_copy)

    oldincludes, oldexcludes = repo.narrowpats

    # filter the user passed additions and deletions into actual additions and
    # deletions of excludes and includes
    addedincludes -= oldincludes
    removedincludes &= oldincludes
    addedexcludes -= oldexcludes
    removedexcludes &= oldexcludes

    widening = addedincludes or removedexcludes
    narrowing = removedincludes or addedexcludes

    # Only print the current narrowspec.
    if only_show:
        ui.pager(b'tracked')
        fm = ui.formatter(b'narrow', opts)
        for i in sorted(oldincludes):
            fm.startitem()
            fm.write(b'status', b'%s ', b'I', label=b'narrow.included')
            fm.write(b'pat', b'%s\n', i, label=b'narrow.included')
        for i in sorted(oldexcludes):
            fm.startitem()
            fm.write(b'status', b'%s ', b'X', label=b'narrow.excluded')
            fm.write(b'pat', b'%s\n', i, label=b'narrow.excluded')
        fm.end()
        return 0

    if update_working_copy:
        with repo.wlock(), repo.lock(), repo.transaction(
                b'narrow-wc'), repo.dirstate.parentchange():
            narrowspec.updateworkingcopy(repo)
            narrowspec.copytoworkingcopy(repo)
        return 0

    if not (widening or narrowing or autoremoveincludes):
        ui.status(_(b"nothing to widen or narrow\n"))
        return 0

    with repo.wlock(), repo.lock():
        cmdutil.bailifchanged(repo)

        # Find the revisions we have in common with the remote. These will
        # be used for finding local-only changes for narrowing. They will
        # also define the set of revisions to update for widening.
        r = urlutil.get_unique_pull_path(b'tracked', repo, ui, remotepath)
        url, branches = r
        ui.status(_(b'comparing with %s\n') % urlutil.hidepassword(url))
        remote = hg.peer(repo, opts, url)

        try:
            # check narrow support before doing anything if widening needs to be
            # performed. In future we should also abort if client is ellipses and
            # server does not support ellipses
            if (widening
                    and wireprototypes.NARROWCAP not in remote.capabilities()):
                raise error.Abort(_(b"server does not support narrow clones"))

            commoninc = discovery.findcommonincoming(repo, remote)

            if autoremoveincludes:
                outgoing = discovery.findcommonoutgoing(repo,
                                                        remote,
                                                        commoninc=commoninc)
                ui.status(_(b'looking for unused includes to remove\n'))
                localfiles = set()
                for n in itertools.chain(outgoing.missing, outgoing.excluded):
                    localfiles.update(repo[n].files())
                suggestedremovals = []
                for include in sorted(oldincludes):
                    match = narrowspec.match(repo.root, [include], oldexcludes)
                    if not any(match(f) for f in localfiles):
                        suggestedremovals.append(include)
                if suggestedremovals:
                    for s in suggestedremovals:
                        ui.status(b'%s\n' % s)
                    if (ui.promptchoice(
                            _(b'remove these unused includes (yn)?'
                              b'$$ &Yes $$ &No')) == 0):
                        removedincludes.update(suggestedremovals)
                        narrowing = True
                else:
                    ui.status(_(b'found no unused includes\n'))

            if narrowing:
                newincludes = oldincludes - removedincludes
                newexcludes = oldexcludes | addedexcludes
                _narrow(
                    ui,
                    repo,
                    remote,
                    commoninc,
                    oldincludes,
                    oldexcludes,
                    newincludes,
                    newexcludes,
                    opts[b'force_delete_local_changes'],
                    opts[b'backup'],
                )
                # _narrow() updated the narrowspec and _widen() below needs to
                # use the updated values as its base (otherwise removed includes
                # and addedexcludes will be lost in the resulting narrowspec)
                oldincludes = newincludes
                oldexcludes = newexcludes

            if widening:
                newincludes = oldincludes | addedincludes
                newexcludes = oldexcludes - removedexcludes
                _widen(
                    ui,
                    repo,
                    remote,
                    commoninc,
                    oldincludes,
                    oldexcludes,
                    newincludes,
                    newexcludes,
                )
        finally:
            remote.close()

    return 0
Beispiel #8
0
def fetch(ui, repo, source=b'default', **opts):
    """pull changes from a remote repository, merge new changes if needed.

    This finds all changes from the repository at the specified path
    or URL and adds them to the local repository.

    If the pulled changes add a new branch head, the head is
    automatically merged, and the result of the merge is committed.
    Otherwise, the working directory is updated to include the new
    changes.

    When a merge is needed, the working directory is first updated to
    the newly pulled changes. Local changes are then merged into the
    pulled changes. To switch the merge order, use --switch-parent.

    See :hg:`help dates` for a list of formats valid for -d/--date.

    Returns 0 on success.
    """

    opts = pycompat.byteskwargs(opts)
    date = opts.get(b'date')
    if date:
        opts[b'date'] = dateutil.parsedate(date)

    parent = repo.dirstate.p1()
    branch = repo.dirstate.branch()
    try:
        branchnode = repo.branchtip(branch)
    except error.RepoLookupError:
        branchnode = None
    if parent != branchnode:
        raise error.Abort(
            _(b'working directory not at branch tip'),
            hint=_(b"use 'hg update' to check out branch tip"),
        )

    wlock = lock = None
    try:
        wlock = repo.wlock()
        lock = repo.lock()

        cmdutil.bailifchanged(repo)

        bheads = repo.branchheads(branch)
        bheads = [head for head in bheads if len(repo[head].children()) == 0]
        if len(bheads) > 1:
            raise error.Abort(
                _(
                    b'multiple heads in this branch '
                    b'(use "hg heads ." and "hg merge" to merge)'
                )
            )

        path = urlutil.get_unique_pull_path(b'fetch', repo, ui, source)[0]
        other = hg.peer(repo, opts, path)
        ui.status(_(b'pulling from %s\n') % urlutil.hidepassword(path))
        revs = None
        if opts[b'rev']:
            try:
                revs = [other.lookup(rev) for rev in opts[b'rev']]
            except error.CapabilityError:
                err = _(
                    b"other repository doesn't support revision lookup, "
                    b"so a rev cannot be specified."
                )
                raise error.Abort(err)

        # Are there any changes at all?
        modheads = exchange.pull(repo, other, heads=revs).cgresult
        if modheads == 0:
            return 0

        # Is this a simple fast-forward along the current branch?
        newheads = repo.branchheads(branch)
        newchildren = repo.changelog.nodesbetween([parent], newheads)[2]
        if len(newheads) == 1 and len(newchildren):
            if newchildren[0] != parent:
                return hg.update(repo, newchildren[0])
            else:
                return 0

        # Are there more than one additional branch heads?
        newchildren = [n for n in newchildren if n != parent]
        newparent = parent
        if newchildren:
            newparent = newchildren[0]
            hg.clean(repo, newparent)
        newheads = [n for n in newheads if n != newparent]
        if len(newheads) > 1:
            ui.status(
                _(
                    b'not merging with %d other new branch heads '
                    b'(use "hg heads ." and "hg merge" to merge them)\n'
                )
                % (len(newheads) - 1)
            )
            return 1

        if not newheads:
            return 0

        # Otherwise, let's merge.
        err = False
        if newheads:
            # By default, we consider the repository we're pulling
            # *from* as authoritative, so we merge our changes into
            # theirs.
            if opts[b'switch_parent']:
                firstparent, secondparent = newparent, newheads[0]
            else:
                firstparent, secondparent = newheads[0], newparent
                ui.status(
                    _(b'updating to %d:%s\n')
                    % (repo.changelog.rev(firstparent), short(firstparent))
                )
            hg.clean(repo, firstparent)
            p2ctx = repo[secondparent]
            ui.status(
                _(b'merging with %d:%s\n') % (p2ctx.rev(), short(secondparent))
            )
            err = hg.merge(p2ctx, remind=False)

        if not err:
            # we don't translate commit messages
            message = cmdutil.logmessage(ui, opts) or (
                b'Automated merge with %s' % urlutil.removeauth(other.url())
            )
            editopt = opts.get(b'edit') or opts.get(b'force_editor')
            editor = cmdutil.getcommiteditor(edit=editopt, editform=b'fetch')
            n = repo.commit(
                message, opts[b'user'], opts[b'date'], editor=editor
            )
            ui.status(
                _(b'new changeset %d:%s merges remote changes with local\n')
                % (repo.changelog.rev(n), short(n))
            )

        return err

    finally:
        release(lock, wlock)
 def __str__(self):
     return b"%s: %s" % (urlutil.hidepassword(self.url), self.detail)