{
    "file_diffs": [
        {
            "old_file_content": "# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-\n# ex: set sts=4 ts=4 sw=4 noet:\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n#   See COPYING file distributed along with the datalad package for the\n#   copyright and license terms.\n#\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n\"\"\"Plumbing command for dataset installation\"\"\"\n\n\nimport logging\nimport re\nfrom os.path import expanduser\nfrom collections import OrderedDict\nfrom urllib.parse import unquote as urlunquote\n\nfrom datalad.interface.base import Interface\nfrom datalad.interface.utils import eval_results\nfrom datalad.interface.base import build_doc\nfrom datalad.interface.results import get_status_dict\nfrom datalad.interface.common_opts import (\n    location_description,\n    reckless_opt,\n)\nfrom datalad.log import log_progress\nfrom datalad.support.gitrepo import (\n    GitRepo,\n)\nfrom datalad.cmd import (\n    CommandError,\n)\nfrom datalad.support.annexrepo import AnnexRepo\nfrom datalad.support.constraints import (\n    EnsureNone,\n    EnsureStr,\n    EnsureKeyChoice,\n)\nfrom datalad.support.param import Parameter\nfrom datalad.support.network import (\n    get_local_file_url,\n    URL,\n    RI,\n    DataLadRI,\n    PathRI,\n)\nfrom datalad.dochelpers import (\n    exc_str,\n    single_or_plural,\n)\nfrom datalad.utils import (\n    rmtree,\n    assure_bool,\n    knows_annex,\n    Path,\n)\n\nfrom datalad.distribution.dataset import (\n    Dataset,\n    datasetmethod,\n    resolve_path,\n    require_dataset,\n    EnsureDataset,\n)\nfrom datalad.distribution.utils import (\n    _get_flexible_source_candidates,\n)\nfrom datalad.utils import (\n    check_symlink_capability\n)\n\n__docformat__ = 'restructuredtext'\n\nlgr = logging.getLogger('datalad.core.distributed.clone')\n\n\n@build_doc\nclass Clone(Interface):\n    \"\"\"Obtain a dataset (copy) from a URL or local directory\n\n    The purpose of this command is to obtain a new clone (copy) of a dataset\n    and place it into a not-yet-existing or empty directory. As such `clone`\n    provides a strict subset of the functionality offered by `install`. Only a\n    single dataset can be obtained, and immediate recursive installation of\n    subdatasets is not supported. However, once a (super)dataset is installed\n    via `clone`, any content, including subdatasets can be obtained by a\n    subsequent `get` command.\n\n    Primary differences over a direct `git clone` call are 1) the automatic\n    initialization of a dataset annex (pure Git repositories are equally\n    supported); 2) automatic registration of the newly obtained dataset as a\n    subdataset (submodule), if a parent dataset is specified; 3) support\n    for additional resource identifiers (DataLad resource identifiers as used\n    on datasets.datalad.org, and RIA store URLs as used for store.datalad.org\n    - optionally in specific versions as identified by a branch or a tag; see\n    examples); and 4) automatic configurable generation of alternative access\n    URL for common cases (such as appending '.git' to the URL in case the\n    accessing the base URL failed).\n\n    || PYTHON >>By default, the command returns a single Dataset instance for\n    an installed dataset, regardless of whether it was newly installed ('ok'\n    result), or found already installed from the specified source ('notneeded'\n    result).<< PYTHON ||\n\n    .. seealso::\n\n      :ref:`handbook:3-001`\n        More information on Remote Indexed Archive (RIA) stores\n    \"\"\"\n    # by default ignore everything but install results\n    # i.e. no \"add to super dataset\"\n    result_filter = EnsureKeyChoice('action', ('install',))\n    # very frequently this command will yield exactly one installed dataset\n    # spare people the pain of going through a list by default\n    return_type = 'item-or-list'\n    # as discussed in #1409 and #1470, we want to return dataset instances\n    # matching what is actually available after command completion (and\n    # None for any failed dataset installation)\n    result_xfm = 'successdatasets-or-none'\n\n    _examples_ = [\n        dict(text=\"Install a dataset from Github into the current directory\",\n             code_py=\"clone(\"\n             \"source='https://github.com/datalad-datasets/longnow\"\n             \"-podcasts.git')\",\n             code_cmd=\"datalad clone \"\n             \"https://github.com/datalad-datasets/longnow-podcasts.git\"),\n        dict(text=\"Install a dataset into a specific directory\",\n             code_py=\"\"\"\\\n             clone(source='https://github.com/datalad-datasets/longnow-podcasts.git',\n                   path='myfavpodcasts')\"\"\",\n             code_cmd=\"\"\"\\\n             datalad clone https://github.com/datalad-datasets/longnow-podcasts.git \\\\\n             myfavpodcasts\"\"\"),\n        dict(text=\"Install a dataset as a subdataset into the current dataset\",\n             code_py=\"\"\"\\\n             clone(dataset='.',\n                   source='https://github.com/datalad-datasets/longnow-podcasts.git')\"\"\",\n             code_cmd=\"datalad clone -d . \"\n             \"https://github.com/datalad-datasets/longnow-podcasts.git\"),\n        dict(text=\"Install the main superdataset from datasets.datalad.org\",\n             code_py=\"clone(source='///')\",\n             code_cmd=\"datalad clone ///\"),\n        dict(text=\"Install a dataset identified by its ID from store.datalad.org\",\n             code_py=\"clone(source='ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561')\",\n             code_cmd=\"datalad clone ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561\"),\n        dict(\n            text=\"Install a dataset in a specific version as identified by a\"\n                 \"branch or tag name from store.datalad.org\",\n            code_py=\"clone(source='ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561@myidentifier')\",\n            code_cmd=\"datalad clone ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561@myidentifier\"),\n        dict(\n            text=\"Install a dataset with group-write access permissions\",\n            code_py=\\\n            \"clone(source='http://example.com/dataset', reckless='shared-group')\",\n            code_cmd=\\\n            \"datalad clone http://example.com/dataset --reckless shared-group\"),\n    ]\n\n    _params_ = dict(\n        dataset=Parameter(\n            args=(\"-d\", \"--dataset\"),\n            doc=\"\"\"(parent) dataset to clone into. If given, the newly cloned\n            dataset is registered as a subdataset of the parent. Also, if given,\n            relative paths are interpreted as being relative to the parent\n            dataset, and not relative to the working directory.\"\"\",\n            constraints=EnsureDataset() | EnsureNone()),\n        source=Parameter(\n            args=(\"source\",),\n            metavar='SOURCE',\n            doc=\"\"\"URL, DataLad resource identifier, local path or instance of\n            dataset to be cloned\"\"\",\n            constraints=EnsureStr() | EnsureNone()),\n        path=Parameter(\n            args=(\"path\",),\n            metavar='PATH',\n            nargs=\"?\",\n            doc=\"\"\"path to clone into.  If no `path` is provided a\n            destination path will be derived from a source URL\n            similar to :command:`git clone`\"\"\"),\n        description=location_description,\n        reckless=reckless_opt,\n    )\n\n    @staticmethod\n    @datasetmethod(name='clone')\n    @eval_results\n    def __call__(\n            source,\n            path=None,\n            dataset=None,\n            description=None,\n            reckless=None):\n        # did we explicitly get a dataset to install into?\n        # if we got a dataset, path will be resolved against it.\n        # Otherwise path will be resolved first.\n        ds = require_dataset(\n            dataset, check_installed=True, purpose='cloning') \\\n            if dataset is not None else dataset\n        refds_path = ds.path if ds else None\n\n        # legacy compatibility\n        if reckless is True:\n            # so that we can forget about how things used to be\n            reckless = 'auto'\n        if reckless is None and ds:\n            # if reckless is not explicitly given, but we operate on a\n            # superdataset, query whether it has been instructed to operate\n            # in a reckless mode, and inherit it for the coming clone\n            reckless = ds.config.get('datalad.clone.reckless', None)\n\n        if isinstance(source, Dataset):\n            source = source.path\n\n        if source == path:\n            # even if they turn out to be identical after resolving symlinks\n            # and more sophisticated witchcraft, it would still happily say\n            # \"it appears to be already installed\", so we just catch an\n            # obviously pointless input combination\n            raise ValueError(\n                \"clone `source` and destination `path` are identical [{}]. \"\n                \"If you are trying to add a subdataset simply use `save`\".format(\n                    path))\n\n        if path is not None:\n            path = resolve_path(path, dataset)\n\n        # derive target from source:\n        if path is None:\n            # we got nothing but a source. do something similar to git clone\n            # and derive the path from the source and continue\n            # since this is a relative `path`, resolve it:\n            # we are not going to reuse the decoded URL, as this is done for\n            # all source candidates in clone_dataset(), we just use to determine\n            # a destination path here in order to perform a bunch of additional\n            # checks that shall not pollute the helper function\n            source_ = decode_source_spec(\n                source, cfg=None if ds is None else ds.config)\n            path = resolve_path(source_['default_destpath'], dataset)\n            lgr.debug(\"Determined clone target path from source\")\n        lgr.debug(\"Resolved clone target path to: '%s'\", path)\n\n        # there is no other way -- my intoxicated brain tells me\n        assert(path is not None)\n\n        result_props = dict(\n            action='install',\n            logger=lgr,\n            refds=refds_path,\n            source_url=source)\n\n        try:\n            # this will implicitly cause pathlib to run a bunch of checks\n            # whether the present path makes any sense on the platform\n            # we are running on -- we don't care if the path actually\n            # exists at this point, but we want to abort early if the path\n            # spec is determined to be useless\n            path.exists()\n        except OSError as e:\n            yield get_status_dict(\n                status='error',\n                path=path,\n                message=('cannot handle target path: %s', exc_str(e)),\n                **result_props)\n            return\n\n        destination_dataset = Dataset(path)\n        result_props['ds'] = destination_dataset\n\n        if ds is not None and ds.pathobj not in path.parents:\n            yield get_status_dict(\n                status='error',\n                message=(\"clone target path '%s' not in specified target dataset '%s'\",\n                         path, ds),\n                **result_props)\n            return\n\n        # perform the actual cloning operation\n        yield from clone_dataset(\n            [source],\n            destination_dataset,\n            reckless,\n            description,\n            result_props,\n            cfg=None if ds is None else ds.config,\n        )\n\n        # TODO handle any 'version' property handling and verification using a dedicated\n        # public helper\n\n        if ds is not None:\n            # we created a dataset in another dataset\n            # -> make submodule\n            for r in ds.save(\n                    path,\n                    return_type='generator',\n                    result_filter=None,\n                    result_xfm=None,\n                    on_failure='ignore'):\n                yield r\n\n\ndef clone_dataset(\n        srcs,\n        destds,\n        reckless=None,\n        description=None,\n        result_props=None,\n        cfg=None):\n    \"\"\"Internal helper to perform cloning without sanity checks (assumed done)\n\n    This helper does not handle any saving of subdataset modification or adding\n    in a superdataset.\n\n    Parameters\n    ----------\n    srcs : list\n      Any suitable clone source specifications (paths, URLs)\n    destds : Dataset\n      Dataset instance for the clone destination\n    reckless : {None, 'auto', 'ephemeral', 'shared-...'}, optional\n      Mode switch to put cloned dataset into unsafe/throw-away configurations, i.e.\n      sacrifice data safety for performance or resource footprint.\n    description : str, optional\n      Location description for the annex of the dataset clone (if there is any).\n    result_props : dict, optional\n      Default properties for any yielded result, passed on to get_status_dict().\n    cfg : ConfigManager, optional\n      Configuration will be queried from this instance (i.e. from a particular\n      dataset). If None is given, the global DataLad configuration will be\n      queried.\n\n    Yields\n    ------\n    dict\n      DataLad result records\n    \"\"\"\n    if not result_props:\n        # in case the caller had no specific idea on how results should look\n        # like, provide sensible defaults\n        result_props = dict(\n            action='install',\n            logger=lgr,\n            ds=destds,\n        )\n\n    dest_path = destds.pathobj\n\n    # decode all source candidate specifications\n    candidate_sources = [decode_source_spec(s, cfg=cfg) for s in srcs]\n\n    # now expand the candidate sources with additional variants of the decoded\n    # giturl, while duplicating the other properties in the additional records\n    # for simplicity. The hope is to overcome a few corner cases and be more\n    # robust than git clone\n    candidate_sources = [\n        dict(props, giturl=s) for props in candidate_sources\n        for s in _get_flexible_source_candidates(props['giturl'])\n    ]\n\n    # important test! based on this `rmtree` will happen below after failed clone\n    dest_path_existed = dest_path.exists()\n    if dest_path_existed and any(dest_path.iterdir()):\n        if destds.is_installed():\n            # check if dest was cloned from the given source before\n            # this is where we would have installed this from\n            # this is where it was actually installed from\n            track_name, track_url = _get_tracking_source(destds)\n            try:\n                # this will get us track_url in system native path conventions,\n                # whenever it is a path (and not a URL)\n                # this is needed to match it to any potentially incoming local\n                # source path in the 'notneeded' test below\n                track_path = str(Path(track_url))\n            except Exception:\n                # this should never happen, because Path() will let any non-path stringification\n                # pass through unmodified, but we do not want any potential crash due to\n                # pathlib behavior changes\n                lgr.debug(\"Unexpected behavior of pathlib!\")\n                track_path = None\n            for cand in candidate_sources:\n                src = cand['giturl']\n                if track_url == src \\\n                        or get_local_file_url(track_url, compatibility='git') == src \\\n                        or track_path == expanduser(src):\n                    yield get_status_dict(\n                        status='notneeded',\n                        message=(\"dataset %s was already cloned from '%s'\",\n                                 destds,\n                                 src),\n                        **result_props)\n                    return\n        # anything else is an error\n        yield get_status_dict(\n            status='error',\n            message='target path already exists and not empty, refuse to clone into target path',\n            **result_props)\n        return\n\n    log_progress(\n        lgr.info,\n        'cloneds',\n        'Cloning dataset to %s', destds,\n        total=len(candidate_sources),\n        label='Clone attempt',\n        unit=' Candidate locations',\n    )\n    error_msgs = OrderedDict()  # accumulate all error messages formatted per each url\n    for cand in candidate_sources:\n        log_progress(\n            lgr.info,\n            'cloneds',\n            'Attempting to clone from %s to %s', cand['giturl'], dest_path,\n            update=1,\n            increment=True)\n\n        clone_opts = {}\n\n        if cand.get('version', None):\n            clone_opts['branch'] = cand['version']\n        try:\n            # TODO for now GitRepo.clone() cannot handle Path instances, and PY35\n            # doesn't make it happen seemlessly\n            GitRepo.clone(\n                path=str(dest_path),\n                url=cand['giturl'],\n                clone_options=clone_opts,\n                create=True)\n\n        except CommandError as e:\n            e_stderr = e.stderr\n\n            error_msgs[cand['giturl']] = e\n            lgr.debug(\"Failed to clone from URL: %s (%s)\",\n                      cand['giturl'], exc_str(e))\n            if dest_path.exists():\n                lgr.debug(\"Wiping out unsuccessful clone attempt at: %s\",\n                          dest_path)\n                # We must not just rmtree since it might be curdir etc\n                # we should remove all files/directories under it\n                # TODO stringification can be removed once patlib compatible\n                # or if PY35 is no longer supported\n                rmtree(str(dest_path), children_only=dest_path_existed)\n\n            if 'could not create work tree' in e_stderr.lower():\n                # this cannot be fixed by trying another URL\n                re_match = re.match(r\".*fatal: (.*)$\", e_stderr,\n                                    flags=re.MULTILINE | re.DOTALL)\n                # cancel progress bar\n                log_progress(\n                    lgr.info,\n                    'cloneds',\n                    'Completed clone attempts for %s', destds\n                )\n                yield get_status_dict(\n                    status='error',\n                    message=re_match.group(1).strip()\n                    if re_match else \"stderr: \" + e_stderr,\n                    **result_props)\n                return\n            # next candidate\n            continue\n\n        result_props['source'] = cand\n        # do not bother with other sources if succeeded\n        break\n\n    log_progress(\n        lgr.info,\n        'cloneds',\n        'Completed clone attempts for %s', destds\n    )\n\n    if not destds.is_installed():\n        if len(error_msgs):\n            if all(not e.stdout and not e.stderr for e in error_msgs.values()):\n                # there is nothing we can learn from the actual exception,\n                # the exit code is uninformative, the command is predictable\n                error_msg = \"Failed to clone from all attempted sources: %s\"\n                error_args = list(error_msgs.keys())\n            else:\n                error_msg = \"Failed to clone from any candidate source URL. \" \\\n                            \"Encountered errors per each url were:\\n- %s\"\n                error_args = '\\n- '.join(\n                    '{}\\n  {}'.format(url, exc_str(exc))\n                    for url, exc in error_msgs.items()\n                )\n        else:\n            # yoh: Not sure if we ever get here but I felt that there could\n            #      be a case when this might happen and original error would\n            #      not be sufficient to troubleshoot what is going on.\n            error_msg = \"Awkward error -- we failed to clone properly. \" \\\n                        \"Although no errors were encountered, target \" \\\n                        \"dataset at %s seems to be not fully installed. \" \\\n                        \"The 'succesful' source was: %s\"\n            error_args = (destds.path, cand['giturl'])\n        yield get_status_dict(\n            status='error',\n            message=(error_msg, error_args),\n            **result_props)\n        return\n\n    if not cand.get(\"version\"):\n        postclone_check_head(destds)\n\n    # act on --reckless=shared-...\n    # must happen prior git-annex-init, where we can cheaply alter the repo\n    # setup through safe re-init'ing\n    if reckless and reckless.startswith('shared-'):\n        lgr.debug('Reinit %s to enable shared access permissions', destds)\n        destds.repo.call_git(['init', '--shared={}'.format(reckless[7:])])\n\n    yield from postclonecfg_annexdataset(\n        destds,\n        reckless,\n        description)\n\n    # perform any post-processing that needs to know details of the clone\n    # source\n    if result_props['source']['type'] == 'ria':\n        yield from postclonecfg_ria(destds, result_props['source'])\n\n    # yield successful clone of the base dataset now, as any possible\n    # subdataset clone down below will not alter the Git-state of the\n    # parent\n    yield get_status_dict(status='ok', **result_props)\n\n\ndef postclone_check_head(ds):\n    repo = ds.repo\n    if not repo.commit_exists(\"HEAD\"):\n        # HEAD points to an unborn branch. A likely cause of this is that the\n        # remote's main branch is something other than master but HEAD wasn't\n        # adjusted accordingly.\n        #\n        # Let's choose the most recently updated remote ref (according to\n        # commit date). In the case of a submodule, switching to a ref with\n        # commits prevents .update_submodule() from failing. It is likely that\n        # the ref includes the registered commit, but we don't have the\n        # information here to know for sure. If it doesn't, .update_submodule()\n        # will check out a detached HEAD.\n        remote_branches = (\n            b[\"refname:strip=2\"] for b in repo.for_each_ref_(\n                fields=\"refname:strip=2\", sort=\"-committerdate\",\n                pattern=\"refs/remotes/origin\"))\n        for rbranch in remote_branches:\n            if rbranch in [\"origin/git-annex\", \"HEAD\"]:\n                continue\n            repo.call_git([\"checkout\", \"-b\", rbranch[7:],  # drop \"origin/\"\n                           \"--track\", rbranch])\n            lgr.debug(\"Checked out local branch from %s\", rbranch)\n            return\n        lgr.warning(\"Cloned %s but could not find a branch \"\n                    \"with commits\", ds.path)\n\n\ndef postclonecfg_ria(ds, props):\n    \"\"\"Configure a dataset freshly cloned from a RIA store\"\"\"\n    # RIA uses hashdir mixed, copying data to it via git-annex (if cloned via\n    # ssh) would make it see a bare repo and establish a hashdir lower annex\n    # object tree.\n    # Moreover, we want the RIA remote to receive all data for the store, so its\n    # objects could be moved into archives (the main point of a RIA store).\n    ds.config.set(\n        'remote.origin.annex-ignore', 'true',\n        where='local')\n\n    # chances are that if this dataset came from a RIA store, its subdatasets\n    # may live there too. Place a subdataset source candidate config that makes\n    # get probe this RIA store when obtaining subdatasets\n    ds.config.set(\n        # we use the label 'origin' for this candidate in order to not have to\n        # generate a complicated name from the actual source specification\n        'datalad.get.subdataset-source-candidate-origin',\n        # use the entire original URL, up to the fragment + plus dataset ID\n        # placeholder, this should make things work with any store setup we\n        # support (paths, ports, ...)\n        props['source'].split('#', maxsplit=1)[0] + '#{id}',\n        where='local')\n\n    # setup publication dependency, if a corresponding special remote exists\n    # and was enabled (there could be RIA stores that actually only have repos)\n    # make this function be a generator\n    ria_remotes = [s for s in ds.siblings('query', result_renderer='disabled')\n                   if s.get('annex-externaltype', None) == 'ora'\n    ]\n    if not ria_remotes:\n        lgr.debug(\"Found no RIA special remote\")\n    elif len(ria_remotes) == 1:\n        yield from ds.siblings('configure',\n                               name='origin',\n                               publish_depends=ria_remotes[0]['name'],\n                               result_filter=None,\n                               result_renderer='disabled')\n    else:\n        lgr.warning(\"Found multiple RIA remotes. Couldn't decide which \"\n                    \"publishing to origin should depend on: %s\",\n                    [r['name'] for r in ria_remotes])\n\n\ndef postclonecfg_annexdataset(ds, reckless, description=None):\n    \"\"\"If ds \"knows annex\" -- annex init it, set into reckless etc\n\n    Provides additional tune up to a possibly an annex repo, e.g.\n    \"enables\" reckless mode, sets up description\n    \"\"\"\n    # in any case check whether we need to annex-init the installed thing:\n    if not knows_annex(ds.path):\n        # not for us\n        return\n\n    # init annex when traces of a remote annex can be detected\n    if reckless == 'auto':\n        lgr.debug(\n            \"Instruct annex to hardlink content in %s from local \"\n            \"sources, if possible (reckless)\", ds.path)\n        ds.config.set(\n            'annex.hardlink', 'true', where='local', reload=True)\n\n    lgr.debug(\"Initializing annex repo at %s\", ds.path)\n    # Note, that we cannot enforce annex-init via AnnexRepo().\n    # If such an instance already exists, its __init__ will not be executed.\n    # Therefore do quick test once we have an object and decide whether to call\n    # its _init().\n    #\n    # Additionally, call init if we need to add a description (see #1403),\n    # since AnnexRepo.__init__ can only do it with create=True\n    repo = AnnexRepo(ds.path, init=True)\n    if not repo.is_initialized() or description:\n        repo._init(description=description)\n    if reckless == 'auto' or (reckless and reckless.startswith('shared-')):\n        repo._run_annex_command('untrust', annex_options=['here'])\n\n    elif reckless == 'ephemeral':\n        # with ephemeral we declare 'here' as 'dead' right away, whenever\n        # we symlink origin's annex, since availability from 'here' should\n        # not be propagated for an ephemeral clone when we publish back to\n        # origin.\n        # This will cause stuff like this for a locally present annexed file:\n        # % git annex whereis d1\n        # whereis d1 (0 copies) failed\n        # BUT this works:\n        # % git annex find . --not --in here\n        # % git annex find . --in here\n        # d1\n\n        # we don't want annex copy-to origin\n        ds.config.set(\n            'remote.origin.annex-ignore', 'true',\n            where='local')\n\n        ds.repo.set_remote_dead('here')\n\n        if check_symlink_capability(ds.repo.dot_git / 'dl_link_test',\n                                    ds.repo.dot_git / 'dl_target_test'):\n            # symlink the annex to avoid needless copies in an emphemeral clone\n            annex_dir = ds.repo.dot_git / 'annex'\n            origin_annex_url = ds.config.get(\"remote.origin.url\", None)\n            origin_git_path = None\n            if origin_annex_url:\n                try:\n                    # Deal with file:// scheme URLs as well as plain paths.\n                    # If origin isn't local, we have nothing to do.\n                    origin_git_path = Path(RI(origin_annex_url).localpath)\n                    if origin_git_path.name != '.git':\n                        origin_git_path /= '.git'\n                except ValueError:\n                    # Note, that accessing localpath on a non-local RI throws\n                    # ValueError rather than resulting in an AttributeError.\n                    # TODO: Warning level okay or is info level sufficient?\n                    # Note, that setting annex-dead is independent of\n                    # symlinking .git/annex. It might still make sense to\n                    # have an ephemeral clone that doesn't propagate its avail.\n                    # info. Therefore don't fail altogether.\n                    lgr.warning(\"reckless=ephemeral mode: origin doesn't seem \"\n                                \"local: %s\\nno symlinks being used\",\n                                origin_annex_url)\n            if origin_git_path:\n                # TODO make sure that we do not delete any unique data\n                rmtree(str(annex_dir)) \\\n                    if not annex_dir.is_symlink() else annex_dir.unlink()\n                annex_dir.symlink_to(origin_git_path / 'annex',\n                                     target_is_directory=True)\n        else:\n            # TODO: What level? + note, that annex-dead is independ\n            lgr.warning(\"reckless=ephemeral mode: Unable to create symlinks on \"\n                        \"this file system.\")\n\n    if reckless:\n        # we successfully dealt with reckless here.\n        # store the reckless setting in the dataset to make it\n        # known to later clones of subdatasets via get()\n        ds.config.set(\n            'datalad.clone.reckless', reckless,\n            where='local',\n            reload=True)\n\n    srs = {True: [], False: []}  # special remotes by \"autoenable\" key\n    remote_uuids = None  # might be necessary to discover known UUIDs\n\n    # Note: The purpose of this function is to inform the user. So if something\n    # looks misconfigured, we'll warn and move on to the next item.\n    for uuid, config in repo.get_special_remotes().items():\n        sr_name = config.get('name', None)\n        if sr_name is None:\n            lgr.warning(\n                'Ignoring special remote %s because it does not have a name. '\n                'Known information: %s',\n                uuid, config)\n            continue\n        sr_autoenable = config.get('autoenable', False)\n        try:\n            sr_autoenable = assure_bool(sr_autoenable)\n        except ValueError:\n            lgr.warning(\n                'Failed to process \"autoenable\" value %r for sibling %s in '\n                'dataset %s as bool.'\n                'You might need to enable it later manually and/or fix it up to'\n                ' avoid this message in the future.',\n                sr_autoenable, sr_name, ds.path)\n            continue\n\n        # determine whether there is a registered remote with matching UUID\n        if uuid:\n            if remote_uuids is None:\n                remote_uuids = {\n                    # Check annex-config-uuid first. For sameas annex remotes,\n                    # this will point to the UUID for the configuration (i.e.\n                    # the key returned by get_special_remotes) rather than the\n                    # shared UUID.\n                    (repo.config.get('remote.%s.annex-config-uuid' % r) or\n                     repo.config.get('remote.%s.annex-uuid' % r))\n                    for r in repo.get_remotes()\n                }\n            if uuid not in remote_uuids:\n                srs[sr_autoenable].append(sr_name)\n\n    if srs[True]:\n        lgr.debug(\n            \"configuration for %s %s added because of autoenable,\"\n            \" but no UUIDs for them yet known for dataset %s\",\n            # since we are only at debug level, we could call things their\n            # proper names\n            single_or_plural(\"special remote\",\n                             \"special remotes\", len(srs[True]), True),\n            \", \".join(srs[True]),\n            ds.path\n        )\n\n    if srs[False]:\n        # if has no auto-enable special remotes\n        lgr.info(\n            'access to %s %s not auto-enabled, enable with:\\n'\n            '\\t\\tdatalad siblings -d \"%s\" enable -s %s',\n            # but since humans might read it, we better confuse them with our\n            # own terms!\n            single_or_plural(\"dataset sibling\",\n                             \"dataset siblings\", len(srs[False]), True),\n            \", \".join(srs[False]),\n            ds.path,\n            srs[False][0] if len(srs[False]) == 1 else \"SIBLING\",\n        )\n\n    # we have just cloned the repo, so it has 'origin', configure any\n    # reachable origin of origins\n    yield from configure_origins(ds, ds)\n\n\n_handle_possible_annex_dataset = postclonecfg_annexdataset\n\n\ndef configure_origins(cfgds, probeds, label=None):\n    \"\"\"Configure any discoverable local dataset 'origin' sibling as a remote\n\n    Parameters\n    ----------\n    cfgds : Dataset\n      Dataset to receive the remote configurations\n    probeds : Dataset\n      Dataset to start looking for 'origin' remotes. May be identical with\n      `cfgds`.\n    label : int, optional\n      Each discovered 'origin' will be configured as a remote under the name\n      'origin-<label>'. If no label is given, '2' will be used by default,\n      given that there is typically a 'origin' remote already.\n    \"\"\"\n    if label is None:\n        label = 1\n    # let's look at the URL for that remote and see if it is a local\n    # dataset\n    origin_url = probeds.config.get('remote.origin.url')\n    if not origin_url:\n        # no origin, nothing to do\n        return\n    if not cfgds.config.obtain(\n            'datalad.install.inherit-local-origin',\n            default=True):\n        # no inheritance wanted\n        return\n    if not isinstance(RI(origin_url), PathRI):\n        # not local path\n        return\n\n    # no need to reconfigure original/direct origin again\n    if cfgds != probeds:\n        # prevent duplicates\n        known_remote_urls = set(\n            cfgds.config.get(r + '.url', None)\n            for r in cfgds.config.sections()\n            if r.startswith('remote.')\n        )\n        if origin_url not in known_remote_urls:\n            yield from cfgds.siblings(\n                'configure',\n                # no chance for conflict, can only be the second configured\n                # remote\n                name='origin-{}'.format(label),\n                url=origin_url,\n                # fetch to get all annex info\n                fetch=True,\n                result_renderer='disabled',\n                on_failure='ignore',\n            )\n    # and dive deeper\n    # given the clone source is a local dataset, we can have a\n    # cheap look at it, and configure its own 'origin' as a remote\n    # (if there is any), and benefit from additional annex availability\n    yield from configure_origins(\n        cfgds,\n        Dataset(probeds.pathobj / origin_url),\n        label=label + 1)\n\n\ndef _get_tracking_source(ds):\n    \"\"\"Returns name and url of a potential configured source\n    tracking remote\"\"\"\n    vcs = ds.repo\n    # if we have a remote, let's check the location of that remote\n    # for the presence of the desired submodule\n\n    remote_name, tracking_branch = vcs.get_tracking_branch()\n    if not remote_name and isinstance(vcs, AnnexRepo):\n        # maybe cloned from a source repo that was in adjusted mode\n        # https://github.com/datalad/datalad/issues/3969\n        remote_name, tracking_branch = vcs.get_tracking_branch(\n            corresponding=False)\n    # TODO: better default `None`? Check where we might rely on '':\n    remote_url = ''\n    if remote_name:\n        remote_url = vcs.get_remote_url(remote_name, push=False)\n\n    return remote_name, remote_url\n\n\ndef _get_installationpath_from_url(url):\n    \"\"\"Returns a relative path derived from the trailing end of a URL\n\n    This can be used to determine an installation path of a Dataset\n    from a URL, analog to what `git clone` does.\n    \"\"\"\n    ri = RI(url)\n    if isinstance(ri, (URL, DataLadRI)):  # decode only if URL\n        path = ri.path.rstrip('/')\n        path = urlunquote(path) if path else ri.hostname\n        if '/' in path:\n            path = path.split('/')\n            if path[-1] == '.git':\n                path = path[-2]\n            else:\n                path = path[-1]\n    else:\n        path = Path(url).parts[-1]\n    if path.endswith('.git'):\n        path = path[:-4]\n    return path\n\n\ndef decode_source_spec(spec, cfg=None):\n    \"\"\"Decode information from a clone source specification\n\n    Parameters\n    ----------\n    spec : str\n      Any supported clone source specification\n    cfg : ConfigManager, optional\n      Configuration will be queried from the instance (i.e. from a particular\n      dataset). If None is given, the global DataLad configuration will be\n      queried.\n\n    Returns\n    -------\n    dict\n      The value of each decoded property is stored under its own key in this\n      dict. By default the following keys are return: 'type', a specification\n      type label {'giturl', 'dataladri', 'ria'}; 'source' the original\n      source specification; 'giturl' a URL for the source that is a suitable\n      source argument for git-clone; 'version' a version-identifer, if present\n      (None else); 'default_destpath' a relative path that that can be used as\n      a clone destination.\n    \"\"\"\n    if cfg is None:\n        from datalad import cfg\n    # standard property dict composition\n    props = dict(\n        source=spec,\n        version=None,\n    )\n\n    # Git never gets to see these URLs, so let's manually apply any\n    # rewrite configuration Git might know about.\n    # Note: We need to rewrite before parsing, otherwise parsing might go wrong.\n    # This is particularly true for insteadOf labels replacing even the URL\n    # scheme.\n    spec = cfg.rewrite_url(spec)\n    # common starting point is a RI instance, support for accepting an RI\n    # instance is kept for backward-compatibility reasons\n    source_ri = RI(spec) if not isinstance(spec, RI) else spec\n\n    # scenario switch, each case must set 'giturl' at the very minimum\n    if isinstance(source_ri, DataLadRI):\n        # we have got our DataLadRI as the source, so expand it\n        props['type'] = 'dataladri'\n        props['giturl'] = source_ri.as_git_url()\n    elif isinstance(source_ri, URL) and source_ri.scheme.startswith('ria+'):\n        # parse a RIA URI\n        dsid, version = source_ri.fragment.split('@', maxsplit=1) \\\n            if '@' in source_ri.fragment else (source_ri.fragment, None)\n        uuid_regex = r'[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}'\n        if not re.match(uuid_regex, dsid):\n            raise ValueError('RIA URI does not contain a valid dataset ID: {}'.format(spec))\n        # now we cancel the fragment in the original URL, but keep everthing else\n        # in order to be able to support the various combinations of ports, paths,\n        # and everything else\n        source_ri.fragment = ''\n        # strip the custom protocol and go with standard one\n        source_ri.scheme = source_ri.scheme[4:]\n        # take any existing path, and add trace to dataset within the store\n        source_ri.path = '{urlpath}{urldelim}{trace}'.format(\n            urlpath=source_ri.path if source_ri.path else '',\n            urldelim='' if not source_ri.path or source_ri.path.endswith('/') else '/',\n            trace='{}/{}'.format(dsid[:3], dsid[3:]),\n        )\n        props.update(\n            type='ria',\n            giturl=str(source_ri),\n            version=version,\n            default_destpath=dsid,\n        )\n    else:\n        # let's assume that anything else is a URI that Git can handle\n        props['type'] = 'giturl'\n        # use original input verbatim\n        props['giturl'] = spec\n\n    if 'default_destpath' not in props:\n        # if we still have no good idea on where a dataset could be cloned to if no\n        # path was given, do something similar to git clone and derive the path from\n        # the source\n        props['default_destpath'] = _get_installationpath_from_url(props['giturl'])\n\n    return props\n",
            "new_file_content": "# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-\n# ex: set sts=4 ts=4 sw=4 noet:\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n#   See COPYING file distributed along with the datalad package for the\n#   copyright and license terms.\n#\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n\"\"\"Plumbing command for dataset installation\"\"\"\n\n\nimport logging\nimport re\nfrom os.path import expanduser\nfrom collections import OrderedDict\nfrom urllib.parse import unquote as urlunquote\n\nfrom datalad.interface.base import Interface\nfrom datalad.interface.utils import eval_results\nfrom datalad.interface.base import build_doc\nfrom datalad.interface.results import get_status_dict\nfrom datalad.interface.common_opts import (\n    location_description,\n    reckless_opt,\n)\nfrom datalad.log import log_progress\nfrom datalad.support.gitrepo import (\n    GitRepo,\n)\nfrom datalad.cmd import (\n    CommandError,\n)\nfrom datalad.support.annexrepo import AnnexRepo\nfrom datalad.support.constraints import (\n    EnsureNone,\n    EnsureStr,\n    EnsureKeyChoice,\n)\nfrom datalad.support.param import Parameter\nfrom datalad.support.network import (\n    get_local_file_url,\n    URL,\n    RI,\n    DataLadRI,\n    PathRI,\n)\nfrom datalad.dochelpers import (\n    exc_str,\n    single_or_plural,\n)\nfrom datalad.utils import (\n    rmtree,\n    assure_bool,\n    knows_annex,\n    Path,\n)\n\nfrom datalad.distribution.dataset import (\n    Dataset,\n    datasetmethod,\n    resolve_path,\n    require_dataset,\n    EnsureDataset,\n)\nfrom datalad.distribution.utils import (\n    _get_flexible_source_candidates,\n)\nfrom datalad.utils import (\n    check_symlink_capability\n)\n\n__docformat__ = 'restructuredtext'\n\nlgr = logging.getLogger('datalad.core.distributed.clone')\n\n\n@build_doc\nclass Clone(Interface):\n    \"\"\"Obtain a dataset (copy) from a URL or local directory\n\n    The purpose of this command is to obtain a new clone (copy) of a dataset\n    and place it into a not-yet-existing or empty directory. As such `clone`\n    provides a strict subset of the functionality offered by `install`. Only a\n    single dataset can be obtained, and immediate recursive installation of\n    subdatasets is not supported. However, once a (super)dataset is installed\n    via `clone`, any content, including subdatasets can be obtained by a\n    subsequent `get` command.\n\n    Primary differences over a direct `git clone` call are 1) the automatic\n    initialization of a dataset annex (pure Git repositories are equally\n    supported); 2) automatic registration of the newly obtained dataset as a\n    subdataset (submodule), if a parent dataset is specified; 3) support\n    for additional resource identifiers (DataLad resource identifiers as used\n    on datasets.datalad.org, and RIA store URLs as used for store.datalad.org\n    - optionally in specific versions as identified by a branch or a tag; see\n    examples); and 4) automatic configurable generation of alternative access\n    URL for common cases (such as appending '.git' to the URL in case the\n    accessing the base URL failed).\n\n    || PYTHON >>By default, the command returns a single Dataset instance for\n    an installed dataset, regardless of whether it was newly installed ('ok'\n    result), or found already installed from the specified source ('notneeded'\n    result).<< PYTHON ||\n\n    .. seealso::\n\n      :ref:`handbook:3-001`\n        More information on Remote Indexed Archive (RIA) stores\n    \"\"\"\n    # by default ignore everything but install results\n    # i.e. no \"add to super dataset\"\n    result_filter = EnsureKeyChoice('action', ('install',))\n    # very frequently this command will yield exactly one installed dataset\n    # spare people the pain of going through a list by default\n    return_type = 'item-or-list'\n    # as discussed in #1409 and #1470, we want to return dataset instances\n    # matching what is actually available after command completion (and\n    # None for any failed dataset installation)\n    result_xfm = 'successdatasets-or-none'\n\n    _examples_ = [\n        dict(text=\"Install a dataset from Github into the current directory\",\n             code_py=\"clone(\"\n             \"source='https://github.com/datalad-datasets/longnow\"\n             \"-podcasts.git')\",\n             code_cmd=\"datalad clone \"\n             \"https://github.com/datalad-datasets/longnow-podcasts.git\"),\n        dict(text=\"Install a dataset into a specific directory\",\n             code_py=\"\"\"\\\n             clone(source='https://github.com/datalad-datasets/longnow-podcasts.git',\n                   path='myfavpodcasts')\"\"\",\n             code_cmd=\"\"\"\\\n             datalad clone https://github.com/datalad-datasets/longnow-podcasts.git \\\\\n             myfavpodcasts\"\"\"),\n        dict(text=\"Install a dataset as a subdataset into the current dataset\",\n             code_py=\"\"\"\\\n             clone(dataset='.',\n                   source='https://github.com/datalad-datasets/longnow-podcasts.git')\"\"\",\n             code_cmd=\"datalad clone -d . \"\n             \"https://github.com/datalad-datasets/longnow-podcasts.git\"),\n        dict(text=\"Install the main superdataset from datasets.datalad.org\",\n             code_py=\"clone(source='///')\",\n             code_cmd=\"datalad clone ///\"),\n        dict(text=\"Install a dataset identified by a literal alias from store.datalad.org\",\n             code_py=\"clone(source='ria+http://store.datalad.org#~hcp-openaccess')\",\n             code_cmd=\"datalad clone ria+http://store.datalad.org#~hcp-openaccess\"),\n        dict(\n            text=\"Install a dataset in a specific version as identified by a\"\n                 \"branch or tag name from store.datalad.org\",\n            code_py=\"clone(source='ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561@myidentifier')\",\n            code_cmd=\"datalad clone ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561@myidentifier\"),\n        dict(\n            text=\"Install a dataset with group-write access permissions\",\n            code_py=\\\n            \"clone(source='http://example.com/dataset', reckless='shared-group')\",\n            code_cmd=\\\n            \"datalad clone http://example.com/dataset --reckless shared-group\"),\n    ]\n\n    _params_ = dict(\n        dataset=Parameter(\n            args=(\"-d\", \"--dataset\"),\n            doc=\"\"\"(parent) dataset to clone into. If given, the newly cloned\n            dataset is registered as a subdataset of the parent. Also, if given,\n            relative paths are interpreted as being relative to the parent\n            dataset, and not relative to the working directory.\"\"\",\n            constraints=EnsureDataset() | EnsureNone()),\n        source=Parameter(\n            args=(\"source\",),\n            metavar='SOURCE',\n            doc=\"\"\"URL, DataLad resource identifier, local path or instance of\n            dataset to be cloned\"\"\",\n            constraints=EnsureStr() | EnsureNone()),\n        path=Parameter(\n            args=(\"path\",),\n            metavar='PATH',\n            nargs=\"?\",\n            doc=\"\"\"path to clone into.  If no `path` is provided a\n            destination path will be derived from a source URL\n            similar to :command:`git clone`\"\"\"),\n        description=location_description,\n        reckless=reckless_opt,\n    )\n\n    @staticmethod\n    @datasetmethod(name='clone')\n    @eval_results\n    def __call__(\n            source,\n            path=None,\n            dataset=None,\n            description=None,\n            reckless=None):\n        # did we explicitly get a dataset to install into?\n        # if we got a dataset, path will be resolved against it.\n        # Otherwise path will be resolved first.\n        ds = require_dataset(\n            dataset, check_installed=True, purpose='cloning') \\\n            if dataset is not None else dataset\n        refds_path = ds.path if ds else None\n\n        # legacy compatibility\n        if reckless is True:\n            # so that we can forget about how things used to be\n            reckless = 'auto'\n        if reckless is None and ds:\n            # if reckless is not explicitly given, but we operate on a\n            # superdataset, query whether it has been instructed to operate\n            # in a reckless mode, and inherit it for the coming clone\n            reckless = ds.config.get('datalad.clone.reckless', None)\n\n        if isinstance(source, Dataset):\n            source = source.path\n\n        if source == path:\n            # even if they turn out to be identical after resolving symlinks\n            # and more sophisticated witchcraft, it would still happily say\n            # \"it appears to be already installed\", so we just catch an\n            # obviously pointless input combination\n            raise ValueError(\n                \"clone `source` and destination `path` are identical [{}]. \"\n                \"If you are trying to add a subdataset simply use `save`\".format(\n                    path))\n\n        if path is not None:\n            path = resolve_path(path, dataset)\n\n        # derive target from source:\n        if path is None:\n            # we got nothing but a source. do something similar to git clone\n            # and derive the path from the source and continue\n            # since this is a relative `path`, resolve it:\n            # we are not going to reuse the decoded URL, as this is done for\n            # all source candidates in clone_dataset(), we just use to determine\n            # a destination path here in order to perform a bunch of additional\n            # checks that shall not pollute the helper function\n            source_ = decode_source_spec(\n                source, cfg=None if ds is None else ds.config)\n            path = resolve_path(source_['default_destpath'], dataset)\n            lgr.debug(\"Determined clone target path from source\")\n        lgr.debug(\"Resolved clone target path to: '%s'\", path)\n\n        # there is no other way -- my intoxicated brain tells me\n        assert(path is not None)\n\n        result_props = dict(\n            action='install',\n            logger=lgr,\n            refds=refds_path,\n            source_url=source)\n\n        try:\n            # this will implicitly cause pathlib to run a bunch of checks\n            # whether the present path makes any sense on the platform\n            # we are running on -- we don't care if the path actually\n            # exists at this point, but we want to abort early if the path\n            # spec is determined to be useless\n            path.exists()\n        except OSError as e:\n            yield get_status_dict(\n                status='error',\n                path=path,\n                message=('cannot handle target path: %s', exc_str(e)),\n                **result_props)\n            return\n\n        destination_dataset = Dataset(path)\n        result_props['ds'] = destination_dataset\n\n        if ds is not None and ds.pathobj not in path.parents:\n            yield get_status_dict(\n                status='error',\n                message=(\"clone target path '%s' not in specified target dataset '%s'\",\n                         path, ds),\n                **result_props)\n            return\n\n        # perform the actual cloning operation\n        yield from clone_dataset(\n            [source],\n            destination_dataset,\n            reckless,\n            description,\n            result_props,\n            cfg=None if ds is None else ds.config,\n        )\n\n        # TODO handle any 'version' property handling and verification using a dedicated\n        # public helper\n\n        if ds is not None:\n            # we created a dataset in another dataset\n            # -> make submodule\n            for r in ds.save(\n                    path,\n                    return_type='generator',\n                    result_filter=None,\n                    result_xfm=None,\n                    on_failure='ignore'):\n                yield r\n\n\ndef clone_dataset(\n        srcs,\n        destds,\n        reckless=None,\n        description=None,\n        result_props=None,\n        cfg=None):\n    \"\"\"Internal helper to perform cloning without sanity checks (assumed done)\n\n    This helper does not handle any saving of subdataset modification or adding\n    in a superdataset.\n\n    Parameters\n    ----------\n    srcs : list\n      Any suitable clone source specifications (paths, URLs)\n    destds : Dataset\n      Dataset instance for the clone destination\n    reckless : {None, 'auto', 'ephemeral', 'shared-...'}, optional\n      Mode switch to put cloned dataset into unsafe/throw-away configurations, i.e.\n      sacrifice data safety for performance or resource footprint.\n    description : str, optional\n      Location description for the annex of the dataset clone (if there is any).\n    result_props : dict, optional\n      Default properties for any yielded result, passed on to get_status_dict().\n    cfg : ConfigManager, optional\n      Configuration will be queried from this instance (i.e. from a particular\n      dataset). If None is given, the global DataLad configuration will be\n      queried.\n\n    Yields\n    ------\n    dict\n      DataLad result records\n    \"\"\"\n    if not result_props:\n        # in case the caller had no specific idea on how results should look\n        # like, provide sensible defaults\n        result_props = dict(\n            action='install',\n            logger=lgr,\n            ds=destds,\n        )\n\n    dest_path = destds.pathobj\n\n    # decode all source candidate specifications\n    candidate_sources = [decode_source_spec(s, cfg=cfg) for s in srcs]\n\n    # now expand the candidate sources with additional variants of the decoded\n    # giturl, while duplicating the other properties in the additional records\n    # for simplicity. The hope is to overcome a few corner cases and be more\n    # robust than git clone\n    candidate_sources = [\n        dict(props, giturl=s) for props in candidate_sources\n        for s in _get_flexible_source_candidates(props['giturl'])\n    ]\n\n    # important test! based on this `rmtree` will happen below after failed clone\n    dest_path_existed = dest_path.exists()\n    if dest_path_existed and any(dest_path.iterdir()):\n        if destds.is_installed():\n            # check if dest was cloned from the given source before\n            # this is where we would have installed this from\n            # this is where it was actually installed from\n            track_name, track_url = _get_tracking_source(destds)\n            try:\n                # this will get us track_url in system native path conventions,\n                # whenever it is a path (and not a URL)\n                # this is needed to match it to any potentially incoming local\n                # source path in the 'notneeded' test below\n                track_path = str(Path(track_url))\n            except Exception:\n                # this should never happen, because Path() will let any non-path stringification\n                # pass through unmodified, but we do not want any potential crash due to\n                # pathlib behavior changes\n                lgr.debug(\"Unexpected behavior of pathlib!\")\n                track_path = None\n            for cand in candidate_sources:\n                src = cand['giturl']\n                if track_url == src \\\n                        or get_local_file_url(track_url, compatibility='git') == src \\\n                        or track_path == expanduser(src):\n                    yield get_status_dict(\n                        status='notneeded',\n                        message=(\"dataset %s was already cloned from '%s'\",\n                                 destds,\n                                 src),\n                        **result_props)\n                    return\n        # anything else is an error\n        yield get_status_dict(\n            status='error',\n            message='target path already exists and not empty, refuse to clone into target path',\n            **result_props)\n        return\n\n    log_progress(\n        lgr.info,\n        'cloneds',\n        'Cloning dataset to %s', destds,\n        total=len(candidate_sources),\n        label='Clone attempt',\n        unit=' Candidate locations',\n    )\n    error_msgs = OrderedDict()  # accumulate all error messages formatted per each url\n    for cand in candidate_sources:\n        log_progress(\n            lgr.info,\n            'cloneds',\n            'Attempting to clone from %s to %s', cand['giturl'], dest_path,\n            update=1,\n            increment=True)\n\n        clone_opts = {}\n\n        if cand.get('version', None):\n            clone_opts['branch'] = cand['version']\n        try:\n            # TODO for now GitRepo.clone() cannot handle Path instances, and PY35\n            # doesn't make it happen seemlessly\n            GitRepo.clone(\n                path=str(dest_path),\n                url=cand['giturl'],\n                clone_options=clone_opts,\n                create=True)\n\n        except CommandError as e:\n            e_stderr = e.stderr\n\n            error_msgs[cand['giturl']] = e\n            lgr.debug(\"Failed to clone from URL: %s (%s)\",\n                      cand['giturl'], exc_str(e))\n            if dest_path.exists():\n                lgr.debug(\"Wiping out unsuccessful clone attempt at: %s\",\n                          dest_path)\n                # We must not just rmtree since it might be curdir etc\n                # we should remove all files/directories under it\n                # TODO stringification can be removed once patlib compatible\n                # or if PY35 is no longer supported\n                rmtree(str(dest_path), children_only=dest_path_existed)\n\n            if 'could not create work tree' in e_stderr.lower():\n                # this cannot be fixed by trying another URL\n                re_match = re.match(r\".*fatal: (.*)$\", e_stderr,\n                                    flags=re.MULTILINE | re.DOTALL)\n                # cancel progress bar\n                log_progress(\n                    lgr.info,\n                    'cloneds',\n                    'Completed clone attempts for %s', destds\n                )\n                yield get_status_dict(\n                    status='error',\n                    message=re_match.group(1).strip()\n                    if re_match else \"stderr: \" + e_stderr,\n                    **result_props)\n                return\n            # next candidate\n            continue\n\n        result_props['source'] = cand\n        # do not bother with other sources if succeeded\n        break\n\n    log_progress(\n        lgr.info,\n        'cloneds',\n        'Completed clone attempts for %s', destds\n    )\n\n    if not destds.is_installed():\n        if len(error_msgs):\n            if all(not e.stdout and not e.stderr for e in error_msgs.values()):\n                # there is nothing we can learn from the actual exception,\n                # the exit code is uninformative, the command is predictable\n                error_msg = \"Failed to clone from all attempted sources: %s\"\n                error_args = list(error_msgs.keys())\n            else:\n                error_msg = \"Failed to clone from any candidate source URL. \" \\\n                            \"Encountered errors per each url were:\\n- %s\"\n                error_args = '\\n- '.join(\n                    '{}\\n  {}'.format(url, exc_str(exc))\n                    for url, exc in error_msgs.items()\n                )\n        else:\n            # yoh: Not sure if we ever get here but I felt that there could\n            #      be a case when this might happen and original error would\n            #      not be sufficient to troubleshoot what is going on.\n            error_msg = \"Awkward error -- we failed to clone properly. \" \\\n                        \"Although no errors were encountered, target \" \\\n                        \"dataset at %s seems to be not fully installed. \" \\\n                        \"The 'succesful' source was: %s\"\n            error_args = (destds.path, cand['giturl'])\n        yield get_status_dict(\n            status='error',\n            message=(error_msg, error_args),\n            **result_props)\n        return\n\n    if not cand.get(\"version\"):\n        postclone_check_head(destds)\n\n    # act on --reckless=shared-...\n    # must happen prior git-annex-init, where we can cheaply alter the repo\n    # setup through safe re-init'ing\n    if reckless and reckless.startswith('shared-'):\n        lgr.debug('Reinit %s to enable shared access permissions', destds)\n        destds.repo.call_git(['init', '--shared={}'.format(reckless[7:])])\n\n    yield from postclonecfg_annexdataset(\n        destds,\n        reckless,\n        description)\n\n    # perform any post-processing that needs to know details of the clone\n    # source\n    if result_props['source']['type'] == 'ria':\n        yield from postclonecfg_ria(destds, result_props['source'])\n\n    # yield successful clone of the base dataset now, as any possible\n    # subdataset clone down below will not alter the Git-state of the\n    # parent\n    yield get_status_dict(status='ok', **result_props)\n\n\ndef postclone_check_head(ds):\n    repo = ds.repo\n    if not repo.commit_exists(\"HEAD\"):\n        # HEAD points to an unborn branch. A likely cause of this is that the\n        # remote's main branch is something other than master but HEAD wasn't\n        # adjusted accordingly.\n        #\n        # Let's choose the most recently updated remote ref (according to\n        # commit date). In the case of a submodule, switching to a ref with\n        # commits prevents .update_submodule() from failing. It is likely that\n        # the ref includes the registered commit, but we don't have the\n        # information here to know for sure. If it doesn't, .update_submodule()\n        # will check out a detached HEAD.\n        remote_branches = (\n            b[\"refname:strip=2\"] for b in repo.for_each_ref_(\n                fields=\"refname:strip=2\", sort=\"-committerdate\",\n                pattern=\"refs/remotes/origin\"))\n        for rbranch in remote_branches:\n            if rbranch in [\"origin/git-annex\", \"HEAD\"]:\n                continue\n            repo.call_git([\"checkout\", \"-b\", rbranch[7:],  # drop \"origin/\"\n                           \"--track\", rbranch])\n            lgr.debug(\"Checked out local branch from %s\", rbranch)\n            return\n        lgr.warning(\"Cloned %s but could not find a branch \"\n                    \"with commits\", ds.path)\n\n\ndef postclonecfg_ria(ds, props):\n    \"\"\"Configure a dataset freshly cloned from a RIA store\"\"\"\n    # RIA uses hashdir mixed, copying data to it via git-annex (if cloned via\n    # ssh) would make it see a bare repo and establish a hashdir lower annex\n    # object tree.\n    # Moreover, we want the RIA remote to receive all data for the store, so its\n    # objects could be moved into archives (the main point of a RIA store).\n    ds.config.set(\n        'remote.origin.annex-ignore', 'true',\n        where='local')\n\n    # chances are that if this dataset came from a RIA store, its subdatasets\n    # may live there too. Place a subdataset source candidate config that makes\n    # get probe this RIA store when obtaining subdatasets\n    ds.config.set(\n        # we use the label 'origin' for this candidate in order to not have to\n        # generate a complicated name from the actual source specification\n        'datalad.get.subdataset-source-candidate-origin',\n        # use the entire original URL, up to the fragment + plus dataset ID\n        # placeholder, this should make things work with any store setup we\n        # support (paths, ports, ...)\n        props['source'].split('#', maxsplit=1)[0] + '#{id}',\n        where='local')\n\n    # setup publication dependency, if a corresponding special remote exists\n    # and was enabled (there could be RIA stores that actually only have repos)\n    # make this function be a generator\n    ria_remotes = [s for s in ds.siblings('query', result_renderer='disabled')\n                   if s.get('annex-externaltype', None) == 'ora'\n    ]\n    if not ria_remotes:\n        lgr.debug(\"Found no RIA special remote\")\n    elif len(ria_remotes) == 1:\n        yield from ds.siblings('configure',\n                               name='origin',\n                               publish_depends=ria_remotes[0]['name'],\n                               result_filter=None,\n                               result_renderer='disabled')\n    else:\n        lgr.warning(\"Found multiple RIA remotes. Couldn't decide which \"\n                    \"publishing to origin should depend on: %s\",\n                    [r['name'] for r in ria_remotes])\n\n\ndef postclonecfg_annexdataset(ds, reckless, description=None):\n    \"\"\"If ds \"knows annex\" -- annex init it, set into reckless etc\n\n    Provides additional tune up to a possibly an annex repo, e.g.\n    \"enables\" reckless mode, sets up description\n    \"\"\"\n    # in any case check whether we need to annex-init the installed thing:\n    if not knows_annex(ds.path):\n        # not for us\n        return\n\n    # init annex when traces of a remote annex can be detected\n    if reckless == 'auto':\n        lgr.debug(\n            \"Instruct annex to hardlink content in %s from local \"\n            \"sources, if possible (reckless)\", ds.path)\n        ds.config.set(\n            'annex.hardlink', 'true', where='local', reload=True)\n\n    lgr.debug(\"Initializing annex repo at %s\", ds.path)\n    # Note, that we cannot enforce annex-init via AnnexRepo().\n    # If such an instance already exists, its __init__ will not be executed.\n    # Therefore do quick test once we have an object and decide whether to call\n    # its _init().\n    #\n    # Additionally, call init if we need to add a description (see #1403),\n    # since AnnexRepo.__init__ can only do it with create=True\n    repo = AnnexRepo(ds.path, init=True)\n    if not repo.is_initialized() or description:\n        repo._init(description=description)\n    if reckless == 'auto' or (reckless and reckless.startswith('shared-')):\n        repo._run_annex_command('untrust', annex_options=['here'])\n\n    elif reckless == 'ephemeral':\n        # with ephemeral we declare 'here' as 'dead' right away, whenever\n        # we symlink origin's annex, since availability from 'here' should\n        # not be propagated for an ephemeral clone when we publish back to\n        # origin.\n        # This will cause stuff like this for a locally present annexed file:\n        # % git annex whereis d1\n        # whereis d1 (0 copies) failed\n        # BUT this works:\n        # % git annex find . --not --in here\n        # % git annex find . --in here\n        # d1\n\n        # we don't want annex copy-to origin\n        ds.config.set(\n            'remote.origin.annex-ignore', 'true',\n            where='local')\n\n        ds.repo.set_remote_dead('here')\n\n        if check_symlink_capability(ds.repo.dot_git / 'dl_link_test',\n                                    ds.repo.dot_git / 'dl_target_test'):\n            # symlink the annex to avoid needless copies in an emphemeral clone\n            annex_dir = ds.repo.dot_git / 'annex'\n            origin_annex_url = ds.config.get(\"remote.origin.url\", None)\n            origin_git_path = None\n            if origin_annex_url:\n                try:\n                    # Deal with file:// scheme URLs as well as plain paths.\n                    # If origin isn't local, we have nothing to do.\n                    origin_git_path = Path(RI(origin_annex_url).localpath)\n                    if origin_git_path.name != '.git':\n                        origin_git_path /= '.git'\n                except ValueError:\n                    # Note, that accessing localpath on a non-local RI throws\n                    # ValueError rather than resulting in an AttributeError.\n                    # TODO: Warning level okay or is info level sufficient?\n                    # Note, that setting annex-dead is independent of\n                    # symlinking .git/annex. It might still make sense to\n                    # have an ephemeral clone that doesn't propagate its avail.\n                    # info. Therefore don't fail altogether.\n                    lgr.warning(\"reckless=ephemeral mode: origin doesn't seem \"\n                                \"local: %s\\nno symlinks being used\",\n                                origin_annex_url)\n            if origin_git_path:\n                # TODO make sure that we do not delete any unique data\n                rmtree(str(annex_dir)) \\\n                    if not annex_dir.is_symlink() else annex_dir.unlink()\n                annex_dir.symlink_to(origin_git_path / 'annex',\n                                     target_is_directory=True)\n        else:\n            # TODO: What level? + note, that annex-dead is independ\n            lgr.warning(\"reckless=ephemeral mode: Unable to create symlinks on \"\n                        \"this file system.\")\n\n    if reckless:\n        # we successfully dealt with reckless here.\n        # store the reckless setting in the dataset to make it\n        # known to later clones of subdatasets via get()\n        ds.config.set(\n            'datalad.clone.reckless', reckless,\n            where='local',\n            reload=True)\n\n    srs = {True: [], False: []}  # special remotes by \"autoenable\" key\n    remote_uuids = None  # might be necessary to discover known UUIDs\n\n    # Note: The purpose of this function is to inform the user. So if something\n    # looks misconfigured, we'll warn and move on to the next item.\n    for uuid, config in repo.get_special_remotes().items():\n        sr_name = config.get('name', None)\n        if sr_name is None:\n            lgr.warning(\n                'Ignoring special remote %s because it does not have a name. '\n                'Known information: %s',\n                uuid, config)\n            continue\n        sr_autoenable = config.get('autoenable', False)\n        try:\n            sr_autoenable = assure_bool(sr_autoenable)\n        except ValueError:\n            lgr.warning(\n                'Failed to process \"autoenable\" value %r for sibling %s in '\n                'dataset %s as bool.'\n                'You might need to enable it later manually and/or fix it up to'\n                ' avoid this message in the future.',\n                sr_autoenable, sr_name, ds.path)\n            continue\n\n        # determine whether there is a registered remote with matching UUID\n        if uuid:\n            if remote_uuids is None:\n                remote_uuids = {\n                    # Check annex-config-uuid first. For sameas annex remotes,\n                    # this will point to the UUID for the configuration (i.e.\n                    # the key returned by get_special_remotes) rather than the\n                    # shared UUID.\n                    (repo.config.get('remote.%s.annex-config-uuid' % r) or\n                     repo.config.get('remote.%s.annex-uuid' % r))\n                    for r in repo.get_remotes()\n                }\n            if uuid not in remote_uuids:\n                srs[sr_autoenable].append(sr_name)\n\n    if srs[True]:\n        lgr.debug(\n            \"configuration for %s %s added because of autoenable,\"\n            \" but no UUIDs for them yet known for dataset %s\",\n            # since we are only at debug level, we could call things their\n            # proper names\n            single_or_plural(\"special remote\",\n                             \"special remotes\", len(srs[True]), True),\n            \", \".join(srs[True]),\n            ds.path\n        )\n\n    if srs[False]:\n        # if has no auto-enable special remotes\n        lgr.info(\n            'access to %s %s not auto-enabled, enable with:\\n'\n            '\\t\\tdatalad siblings -d \"%s\" enable -s %s',\n            # but since humans might read it, we better confuse them with our\n            # own terms!\n            single_or_plural(\"dataset sibling\",\n                             \"dataset siblings\", len(srs[False]), True),\n            \", \".join(srs[False]),\n            ds.path,\n            srs[False][0] if len(srs[False]) == 1 else \"SIBLING\",\n        )\n\n    # we have just cloned the repo, so it has 'origin', configure any\n    # reachable origin of origins\n    yield from configure_origins(ds, ds)\n\n\n_handle_possible_annex_dataset = postclonecfg_annexdataset\n\n\ndef configure_origins(cfgds, probeds, label=None):\n    \"\"\"Configure any discoverable local dataset 'origin' sibling as a remote\n\n    Parameters\n    ----------\n    cfgds : Dataset\n      Dataset to receive the remote configurations\n    probeds : Dataset\n      Dataset to start looking for 'origin' remotes. May be identical with\n      `cfgds`.\n    label : int, optional\n      Each discovered 'origin' will be configured as a remote under the name\n      'origin-<label>'. If no label is given, '2' will be used by default,\n      given that there is typically a 'origin' remote already.\n    \"\"\"\n    if label is None:\n        label = 1\n    # let's look at the URL for that remote and see if it is a local\n    # dataset\n    origin_url = probeds.config.get('remote.origin.url')\n    if not origin_url:\n        # no origin, nothing to do\n        return\n    if not cfgds.config.obtain(\n            'datalad.install.inherit-local-origin',\n            default=True):\n        # no inheritance wanted\n        return\n    if not isinstance(RI(origin_url), PathRI):\n        # not local path\n        return\n\n    # no need to reconfigure original/direct origin again\n    if cfgds != probeds:\n        # prevent duplicates\n        known_remote_urls = set(\n            cfgds.config.get(r + '.url', None)\n            for r in cfgds.config.sections()\n            if r.startswith('remote.')\n        )\n        if origin_url not in known_remote_urls:\n            yield from cfgds.siblings(\n                'configure',\n                # no chance for conflict, can only be the second configured\n                # remote\n                name='origin-{}'.format(label),\n                url=origin_url,\n                # fetch to get all annex info\n                fetch=True,\n                result_renderer='disabled',\n                on_failure='ignore',\n            )\n    # and dive deeper\n    # given the clone source is a local dataset, we can have a\n    # cheap look at it, and configure its own 'origin' as a remote\n    # (if there is any), and benefit from additional annex availability\n    yield from configure_origins(\n        cfgds,\n        Dataset(probeds.pathobj / origin_url),\n        label=label + 1)\n\n\ndef _get_tracking_source(ds):\n    \"\"\"Returns name and url of a potential configured source\n    tracking remote\"\"\"\n    vcs = ds.repo\n    # if we have a remote, let's check the location of that remote\n    # for the presence of the desired submodule\n\n    remote_name, tracking_branch = vcs.get_tracking_branch()\n    if not remote_name and isinstance(vcs, AnnexRepo):\n        # maybe cloned from a source repo that was in adjusted mode\n        # https://github.com/datalad/datalad/issues/3969\n        remote_name, tracking_branch = vcs.get_tracking_branch(\n            corresponding=False)\n    # TODO: better default `None`? Check where we might rely on '':\n    remote_url = ''\n    if remote_name:\n        remote_url = vcs.get_remote_url(remote_name, push=False)\n\n    return remote_name, remote_url\n\n\ndef _get_installationpath_from_url(url):\n    \"\"\"Returns a relative path derived from the trailing end of a URL\n\n    This can be used to determine an installation path of a Dataset\n    from a URL, analog to what `git clone` does.\n    \"\"\"\n    ri = RI(url)\n    if isinstance(ri, (URL, DataLadRI)):  # decode only if URL\n        path = ri.path.rstrip('/')\n        path = urlunquote(path) if path else ri.hostname\n        if '/' in path:\n            path = path.split('/')\n            if path[-1] == '.git':\n                path = path[-2]\n            else:\n                path = path[-1]\n    else:\n        path = Path(url).parts[-1]\n    if path.endswith('.git'):\n        path = path[:-4]\n    return path\n\n\ndef decode_source_spec(spec, cfg=None):\n    \"\"\"Decode information from a clone source specification\n\n    Parameters\n    ----------\n    spec : str\n      Any supported clone source specification\n    cfg : ConfigManager, optional\n      Configuration will be queried from the instance (i.e. from a particular\n      dataset). If None is given, the global DataLad configuration will be\n      queried.\n\n    Returns\n    -------\n    dict\n      The value of each decoded property is stored under its own key in this\n      dict. By default the following keys are return: 'type', a specification\n      type label {'giturl', 'dataladri', 'ria'}; 'source' the original\n      source specification; 'giturl' a URL for the source that is a suitable\n      source argument for git-clone; 'version' a version-identifer, if present\n      (None else); 'default_destpath' a relative path that that can be used as\n      a clone destination.\n    \"\"\"\n    if cfg is None:\n        from datalad import cfg\n    # standard property dict composition\n    props = dict(\n        source=spec,\n        version=None,\n    )\n\n    # Git never gets to see these URLs, so let's manually apply any\n    # rewrite configuration Git might know about.\n    # Note: We need to rewrite before parsing, otherwise parsing might go wrong.\n    # This is particularly true for insteadOf labels replacing even the URL\n    # scheme.\n    spec = cfg.rewrite_url(spec)\n    # common starting point is a RI instance, support for accepting an RI\n    # instance is kept for backward-compatibility reasons\n    source_ri = RI(spec) if not isinstance(spec, RI) else spec\n\n    # scenario switch, each case must set 'giturl' at the very minimum\n    if isinstance(source_ri, DataLadRI):\n        # we have got our DataLadRI as the source, so expand it\n        props['type'] = 'dataladri'\n        props['giturl'] = source_ri.as_git_url()\n    elif isinstance(source_ri, URL) and source_ri.scheme.startswith('ria+'):\n        # parse a RIA URI\n        dsid, version = source_ri.fragment.split('@', maxsplit=1) \\\n            if '@' in source_ri.fragment else (source_ri.fragment, None)\n        uuid_regex = r'[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}'\n        if re.match(uuid_regex, dsid):\n            trace = '{}/{}'.format(dsid[:3], dsid[3:])\n            default_destpath = dsid\n        elif dsid.startswith('~'):\n            trace = 'alias/{}'.format(dsid[1:])\n            default_destpath = dsid[1:]\n        else:\n            raise ValueError(\n                'RIA URI not recognized, no valid dataset ID or other supported '\n                'scheme: {}'.format(spec))\n        # now we cancel the fragment in the original URL, but keep everthing else\n        # in order to be able to support the various combinations of ports, paths,\n        # and everything else\n        source_ri.fragment = ''\n        # strip the custom protocol and go with standard one\n        source_ri.scheme = source_ri.scheme[4:]\n        # take any existing path, and add trace to dataset within the store\n        source_ri.path = '{urlpath}{urldelim}{trace}'.format(\n            urlpath=source_ri.path if source_ri.path else '',\n            urldelim='' if not source_ri.path or source_ri.path.endswith('/') else '/',\n            trace=trace,\n        )\n        props.update(\n            type='ria',\n            giturl=str(source_ri),\n            version=version,\n            default_destpath=default_destpath,\n        )\n    else:\n        # let's assume that anything else is a URI that Git can handle\n        props['type'] = 'giturl'\n        # use original input verbatim\n        props['giturl'] = spec\n\n    if 'default_destpath' not in props:\n        # if we still have no good idea on where a dataset could be cloned to if no\n        # path was given, do something similar to git clone and derive the path from\n        # the source\n        props['default_destpath'] = _get_installationpath_from_url(props['giturl'])\n\n    return props\n",
            "header": {
                "file": {
                    "path": "datalad/core/distributed/clone.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "e84f8f1d6",
                "new_commit_hash": "41e2dce9f",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/datalad/core/distributed/clone.py"
            },
            "plus_file": {
                "path": "b/datalad/core/distributed/clone.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 141,
                            "length": 9
                        },
                        "new_range": {
                            "start": 141,
                            "length": 9
                        },
                        "section": "class Clone(Interface):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        dict(text=\"Install the main superdataset from datasets.datalad.org\",",
                                "type": "context"
                            },
                            {
                                "content": "             code_py=\"clone(source='///')\",",
                                "type": "context"
                            },
                            {
                                "content": "             code_cmd=\"datalad clone ///\"),",
                                "type": "context"
                            },
                            {
                                "content": "        dict(text=\"Install a dataset identified by its ID from store.datalad.org\",",
                                "type": "deleted"
                            },
                            {
                                "content": "             code_py=\"clone(source='ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561')\",",
                                "type": "deleted"
                            },
                            {
                                "content": "             code_cmd=\"datalad clone ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561\"),",
                                "type": "deleted"
                            },
                            {
                                "content": "        dict(text=\"Install a dataset identified by a literal alias from store.datalad.org\",",
                                "type": "added"
                            },
                            {
                                "content": "             code_py=\"clone(source='ria+http://store.datalad.org#~hcp-openaccess')\",",
                                "type": "added"
                            },
                            {
                                "content": "             code_cmd=\"datalad clone ria+http://store.datalad.org#~hcp-openaccess\"),",
                                "type": "added"
                            },
                            {
                                "content": "        dict(",
                                "type": "context"
                            },
                            {
                                "content": "            text=\"Install a dataset in a specific version as identified by a\"",
                                "type": "context"
                            },
                            {
                                "content": "                 \"branch or tag name from store.datalad.org\",",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "datalad/core/distributed/clone.py",
                            "type": "class",
                            "name": "Clone",
                            "content": "class Clone(Interface):\n    \"\"\"Obtain a dataset (copy) from a URL or local directory\n\n    The purpose of this command is to obtain a new clone (copy) of a dataset\n    and place it into a not-yet-existing or empty directory. As such `clone`\n    provides a strict subset of the functionality offered by `install`. Only a\n    single dataset can be obtained, and immediate recursive installation of\n    subdatasets is not supported. However, once a (super)dataset is installed\n    via `clone`, any content, including subdatasets can be obtained by a\n    subsequent `get` command.\n\n    Primary differences over a direct `git clone` call are 1) the automatic\n    initialization of a dataset annex (pure Git repositories are equally\n    supported); 2) automatic registration of the newly obtained dataset as a\n    subdataset (submodule), if a parent dataset is specified; 3) support\n    for additional resource identifiers (DataLad resource identifiers as used\n    on datasets.datalad.org, and RIA store URLs as used for store.datalad.org\n    - optionally in specific versions as identified by a branch or a tag; see\n    examples); and 4) automatic configurable generation of alternative access\n    URL for common cases (such as appending '.git' to the URL in case the\n    accessing the base URL failed).\n\n    || PYTHON >>By default, the command returns a single Dataset instance for\n    an installed dataset, regardless of whether it was newly installed ('ok'\n    result), or found already installed from the specified source ('notneeded'\n    result).<< PYTHON ||\n\n    .. seealso::\n\n      :ref:`handbook:3-001`\n        More information on Remote Indexed Archive (RIA) stores\n    \"\"\"\n    # by default ignore everything but install results\n    # i.e. no \"add to super dataset\"\n    result_filter = EnsureKeyChoice('action', ('install',))\n    # very frequently this command will yield exactly one installed dataset\n    # spare people the pain of going through a list by default\n    return_type = 'item-or-list'\n    # as discussed in #1409 and #1470, we want to return dataset instances\n    # matching what is actually available after command completion (and\n    # None for any failed dataset installation)\n    result_xfm = 'successdatasets-or-none'\n\n    _examples_ = [\n        dict(text=\"Install a dataset from Github into the current directory\",\n             code_py=\"clone(\"\n             \"source='https://github.com/datalad-datasets/longnow\"\n             \"-podcasts.git')\",\n             code_cmd=\"datalad clone \"\n             \"https://github.com/datalad-datasets/longnow-podcasts.git\"),\n        dict(text=\"Install a dataset into a specific directory\",\n             code_py=\"\"\"\\\n             clone(source='https://github.com/datalad-datasets/longnow-podcasts.git',\n                   path='myfavpodcasts')\"\"\",\n             code_cmd=\"\"\"\\\n             datalad clone https://github.com/datalad-datasets/longnow-podcasts.git \\\\\n             myfavpodcasts\"\"\"),\n        dict(text=\"Install a dataset as a subdataset into the current dataset\",\n             code_py=\"\"\"\\\n             clone(dataset='.',\n                   source='https://github.com/datalad-datasets/longnow-podcasts.git')\"\"\",\n             code_cmd=\"datalad clone -d . \"\n             \"https://github.com/datalad-datasets/longnow-podcasts.git\"),\n        dict(text=\"Install the main superdataset from datasets.datalad.org\",\n             code_py=\"clone(source='///')\",\n             code_cmd=\"datalad clone ///\"),\n        dict(text=\"Install a dataset identified by its ID from store.datalad.org\",\n             code_py=\"clone(source='ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561')\",\n             code_cmd=\"datalad clone ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561\"),\n        dict(\n            text=\"Install a dataset in a specific version as identified by a\"\n                 \"branch or tag name from store.datalad.org\",\n            code_py=\"clone(source='ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561@myidentifier')\",\n            code_cmd=\"datalad clone ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561@myidentifier\"),\n        dict(\n            text=\"Install a dataset with group-write access permissions\",\n            code_py=\\\n            \"clone(source='http://example.com/dataset', reckless='shared-group')\",\n            code_cmd=\\\n            \"datalad clone http://example.com/dataset --reckless shared-group\"),\n    ]\n\n    _params_ = dict(\n        dataset=Parameter(\n            args=(\"-d\", \"--dataset\"),\n            doc=\"\"\"(parent) dataset to clone into. If given, the newly cloned\n            dataset is registered as a subdataset of the parent. Also, if given,\n            relative paths are interpreted as being relative to the parent\n            dataset, and not relative to the working directory.\"\"\",\n            constraints=EnsureDataset() | EnsureNone()),\n        source=Parameter(\n            args=(\"source\",),\n            metavar='SOURCE',\n            doc=\"\"\"URL, DataLad resource identifier, local path or instance of\n            dataset to be cloned\"\"\",\n            constraints=EnsureStr() | EnsureNone()),\n        path=Parameter(\n            args=(\"path\",),\n            metavar='PATH',\n            nargs=\"?\",\n            doc=\"\"\"path to clone into.  If no `path` is provided a\n            destination path will be derived from a source URL\n            similar to :command:`git clone`\"\"\"),\n        description=location_description,\n        reckless=reckless_opt,\n    )\n\n    @staticmethod\n    @datasetmethod(name='clone')\n    @eval_results\n    def __call__(\n            source,\n            path=None,\n            dataset=None,\n            description=None,\n            reckless=None):\n        # did we explicitly get a dataset to install into?\n        # if we got a dataset, path will be resolved against it.\n        # Otherwise path will be resolved first.\n        ds = require_dataset(\n            dataset, check_installed=True, purpose='cloning') \\\n            if dataset is not None else dataset\n        refds_path = ds.path if ds else None\n\n        # legacy compatibility\n        if reckless is True:\n            # so that we can forget about how things used to be\n            reckless = 'auto'\n        if reckless is None and ds:\n            # if reckless is not explicitly given, but we operate on a\n            # superdataset, query whether it has been instructed to operate\n            # in a reckless mode, and inherit it for the coming clone\n            reckless = ds.config.get('datalad.clone.reckless', None)\n\n        if isinstance(source, Dataset):\n            source = source.path\n\n        if source == path:\n            # even if they turn out to be identical after resolving symlinks\n            # and more sophisticated witchcraft, it would still happily say\n            # \"it appears to be already installed\", so we just catch an\n            # obviously pointless input combination\n            raise ValueError(\n                \"clone `source` and destination `path` are identical [{}]. \"\n                \"If you are trying to add a subdataset simply use `save`\".format(\n                    path))\n\n        if path is not None:\n            path = resolve_path(path, dataset)\n\n        # derive target from source:\n        if path is None:\n            # we got nothing but a source. do something similar to git clone\n            # and derive the path from the source and continue\n            # since this is a relative `path`, resolve it:\n            # we are not going to reuse the decoded URL, as this is done for\n            # all source candidates in clone_dataset(), we just use to determine\n            # a destination path here in order to perform a bunch of additional\n            # checks that shall not pollute the helper function\n            source_ = decode_source_spec(\n                source, cfg=None if ds is None else ds.config)\n            path = resolve_path(source_['default_destpath'], dataset)\n            lgr.debug(\"Determined clone target path from source\")\n        lgr.debug(\"Resolved clone target path to: '%s'\", path)\n\n        # there is no other way -- my intoxicated brain tells me\n        assert(path is not None)\n\n        result_props = dict(\n            action='install',\n            logger=lgr,\n            refds=refds_path,\n            source_url=source)\n\n        try:\n            # this will implicitly cause pathlib to run a bunch of checks\n            # whether the present path makes any sense on the platform\n            # we are running on -- we don't care if the path actually\n            # exists at this point, but we want to abort early if the path\n            # spec is determined to be useless\n            path.exists()\n        except OSError as e:\n            yield get_status_dict(\n                status='error',\n                path=path,\n                message=('cannot handle target path: %s', exc_str(e)),\n                **result_props)\n            return\n\n        destination_dataset = Dataset(path)\n        result_props['ds'] = destination_dataset\n\n        if ds is not None and ds.pathobj not in path.parents:\n            yield get_status_dict(\n                status='error',\n                message=(\"clone target path '%s' not in specified target dataset '%s'\",\n                         path, ds),\n                **result_props)\n            return\n\n        # perform the actual cloning operation\n        yield from clone_dataset(\n            [source],\n            destination_dataset,\n            reckless,\n            description,\n            result_props,\n            cfg=None if ds is None else ds.config,\n        )\n\n        # TODO handle any 'version' property handling and verification using a dedicated\n        # public helper\n\n        if ds is not None:\n            # we created a dataset in another dataset\n            # -> make submodule\n            for r in ds.save(\n                    path,\n                    return_type='generator',\n                    result_filter=None,\n                    result_xfm=None,\n                    on_failure='ignore'):\n                yield r",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 78,
                            "end_lineno": 300,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 926,
                            "length": 8
                        },
                        "new_range": {
                            "start": 926,
                            "length": 16
                        },
                        "section": "def decode_source_spec(spec, cfg=None):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        dsid, version = source_ri.fragment.split('@', maxsplit=1) \\",
                                "type": "context"
                            },
                            {
                                "content": "            if '@' in source_ri.fragment else (source_ri.fragment, None)",
                                "type": "context"
                            },
                            {
                                "content": "        uuid_regex = r'[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}'",
                                "type": "context"
                            },
                            {
                                "content": "        if not re.match(uuid_regex, dsid):",
                                "type": "deleted"
                            },
                            {
                                "content": "            raise ValueError('RIA URI does not contain a valid dataset ID: {}'.format(spec))",
                                "type": "deleted"
                            },
                            {
                                "content": "        if re.match(uuid_regex, dsid):",
                                "type": "added"
                            },
                            {
                                "content": "            trace = '{}/{}'.format(dsid[:3], dsid[3:])",
                                "type": "added"
                            },
                            {
                                "content": "            default_destpath = dsid",
                                "type": "added"
                            },
                            {
                                "content": "        elif dsid.startswith('~'):",
                                "type": "added"
                            },
                            {
                                "content": "            trace = 'alias/{}'.format(dsid[1:])",
                                "type": "added"
                            },
                            {
                                "content": "            default_destpath = dsid[1:]",
                                "type": "added"
                            },
                            {
                                "content": "        else:",
                                "type": "added"
                            },
                            {
                                "content": "            raise ValueError(",
                                "type": "added"
                            },
                            {
                                "content": "                'RIA URI not recognized, no valid dataset ID or other supported '",
                                "type": "added"
                            },
                            {
                                "content": "                'scheme: {}'.format(spec))",
                                "type": "added"
                            },
                            {
                                "content": "        # now we cancel the fragment in the original URL, but keep everthing else",
                                "type": "context"
                            },
                            {
                                "content": "        # in order to be able to support the various combinations of ports, paths,",
                                "type": "context"
                            },
                            {
                                "content": "        # and everything else",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "datalad/core/distributed/clone.py",
                            "type": "function",
                            "name": "decode_source_spec",
                            "content": "def decode_source_spec(spec, cfg=None):\n    \"\"\"Decode information from a clone source specification\n\n    Parameters\n    ----------\n    spec : str\n      Any supported clone source specification\n    cfg : ConfigManager, optional\n      Configuration will be queried from the instance (i.e. from a particular\n      dataset). If None is given, the global DataLad configuration will be\n      queried.\n\n    Returns\n    -------\n    dict\n      The value of each decoded property is stored under its own key in this\n      dict. By default the following keys are return: 'type', a specification\n      type label {'giturl', 'dataladri', 'ria'}; 'source' the original\n      source specification; 'giturl' a URL for the source that is a suitable\n      source argument for git-clone; 'version' a version-identifer, if present\n      (None else); 'default_destpath' a relative path that that can be used as\n      a clone destination.\n    \"\"\"\n    if cfg is None:\n        from datalad import cfg\n    # standard property dict composition\n    props = dict(\n        source=spec,\n        version=None,\n    )\n\n    # Git never gets to see these URLs, so let's manually apply any\n    # rewrite configuration Git might know about.\n    # Note: We need to rewrite before parsing, otherwise parsing might go wrong.\n    # This is particularly true for insteadOf labels replacing even the URL\n    # scheme.\n    spec = cfg.rewrite_url(spec)\n    # common starting point is a RI instance, support for accepting an RI\n    # instance is kept for backward-compatibility reasons\n    source_ri = RI(spec) if not isinstance(spec, RI) else spec\n\n    # scenario switch, each case must set 'giturl' at the very minimum\n    if isinstance(source_ri, DataLadRI):\n        # we have got our DataLadRI as the source, so expand it\n        props['type'] = 'dataladri'\n        props['giturl'] = source_ri.as_git_url()\n    elif isinstance(source_ri, URL) and source_ri.scheme.startswith('ria+'):\n        # parse a RIA URI\n        dsid, version = source_ri.fragment.split('@', maxsplit=1) \\\n            if '@' in source_ri.fragment else (source_ri.fragment, None)\n        uuid_regex = r'[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}'\n        if not re.match(uuid_regex, dsid):\n            raise ValueError('RIA URI does not contain a valid dataset ID: {}'.format(spec))\n        # now we cancel the fragment in the original URL, but keep everthing else\n        # in order to be able to support the various combinations of ports, paths,\n        # and everything else\n        source_ri.fragment = ''\n        # strip the custom protocol and go with standard one\n        source_ri.scheme = source_ri.scheme[4:]\n        # take any existing path, and add trace to dataset within the store\n        source_ri.path = '{urlpath}{urldelim}{trace}'.format(\n            urlpath=source_ri.path if source_ri.path else '',\n            urldelim='' if not source_ri.path or source_ri.path.endswith('/') else '/',\n            trace='{}/{}'.format(dsid[:3], dsid[3:]),\n        )\n        props.update(\n            type='ria',\n            giturl=str(source_ri),\n            version=version,\n            default_destpath=dsid,\n        )\n    else:\n        # let's assume that anything else is a URI that Git can handle\n        props['type'] = 'giturl'\n        # use original input verbatim\n        props['giturl'] = spec\n\n    if 'default_destpath' not in props:\n        # if we still have no good idea on where a dataset could be cloned to if no\n        # path was given, do something similar to git clone and derive the path from\n        # the source\n        props['default_destpath'] = _get_installationpath_from_url(props['giturl'])\n\n    return props",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 878,
                            "end_lineno": 961,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 938,
                            "length": 13
                        },
                        "new_range": {
                            "start": 946,
                            "length": 13
                        },
                        "section": "def decode_source_spec(spec, cfg=None):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        source_ri.path = '{urlpath}{urldelim}{trace}'.format(",
                                "type": "context"
                            },
                            {
                                "content": "            urlpath=source_ri.path if source_ri.path else '',",
                                "type": "context"
                            },
                            {
                                "content": "            urldelim='' if not source_ri.path or source_ri.path.endswith('/') else '/',",
                                "type": "context"
                            },
                            {
                                "content": "            trace='{}/{}'.format(dsid[:3], dsid[3:]),",
                                "type": "deleted"
                            },
                            {
                                "content": "            trace=trace,",
                                "type": "added"
                            },
                            {
                                "content": "        )",
                                "type": "context"
                            },
                            {
                                "content": "        props.update(",
                                "type": "context"
                            },
                            {
                                "content": "            type='ria',",
                                "type": "context"
                            },
                            {
                                "content": "            giturl=str(source_ri),",
                                "type": "context"
                            },
                            {
                                "content": "            version=version,",
                                "type": "context"
                            },
                            {
                                "content": "            default_destpath=dsid,",
                                "type": "deleted"
                            },
                            {
                                "content": "            default_destpath=default_destpath,",
                                "type": "added"
                            },
                            {
                                "content": "        )",
                                "type": "context"
                            },
                            {
                                "content": "    else:",
                                "type": "context"
                            },
                            {
                                "content": "        # let's assume that anything else is a URI that Git can handle",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "datalad/core/distributed/clone.py",
                            "type": "function",
                            "name": "decode_source_spec",
                            "content": "def decode_source_spec(spec, cfg=None):\n    \"\"\"Decode information from a clone source specification\n\n    Parameters\n    ----------\n    spec : str\n      Any supported clone source specification\n    cfg : ConfigManager, optional\n      Configuration will be queried from the instance (i.e. from a particular\n      dataset). If None is given, the global DataLad configuration will be\n      queried.\n\n    Returns\n    -------\n    dict\n      The value of each decoded property is stored under its own key in this\n      dict. By default the following keys are return: 'type', a specification\n      type label {'giturl', 'dataladri', 'ria'}; 'source' the original\n      source specification; 'giturl' a URL for the source that is a suitable\n      source argument for git-clone; 'version' a version-identifer, if present\n      (None else); 'default_destpath' a relative path that that can be used as\n      a clone destination.\n    \"\"\"\n    if cfg is None:\n        from datalad import cfg\n    # standard property dict composition\n    props = dict(\n        source=spec,\n        version=None,\n    )\n\n    # Git never gets to see these URLs, so let's manually apply any\n    # rewrite configuration Git might know about.\n    # Note: We need to rewrite before parsing, otherwise parsing might go wrong.\n    # This is particularly true for insteadOf labels replacing even the URL\n    # scheme.\n    spec = cfg.rewrite_url(spec)\n    # common starting point is a RI instance, support for accepting an RI\n    # instance is kept for backward-compatibility reasons\n    source_ri = RI(spec) if not isinstance(spec, RI) else spec\n\n    # scenario switch, each case must set 'giturl' at the very minimum\n    if isinstance(source_ri, DataLadRI):\n        # we have got our DataLadRI as the source, so expand it\n        props['type'] = 'dataladri'\n        props['giturl'] = source_ri.as_git_url()\n    elif isinstance(source_ri, URL) and source_ri.scheme.startswith('ria+'):\n        # parse a RIA URI\n        dsid, version = source_ri.fragment.split('@', maxsplit=1) \\\n            if '@' in source_ri.fragment else (source_ri.fragment, None)\n        uuid_regex = r'[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}'\n        if not re.match(uuid_regex, dsid):\n            raise ValueError('RIA URI does not contain a valid dataset ID: {}'.format(spec))\n        # now we cancel the fragment in the original URL, but keep everthing else\n        # in order to be able to support the various combinations of ports, paths,\n        # and everything else\n        source_ri.fragment = ''\n        # strip the custom protocol and go with standard one\n        source_ri.scheme = source_ri.scheme[4:]\n        # take any existing path, and add trace to dataset within the store\n        source_ri.path = '{urlpath}{urldelim}{trace}'.format(\n            urlpath=source_ri.path if source_ri.path else '',\n            urldelim='' if not source_ri.path or source_ri.path.endswith('/') else '/',\n            trace='{}/{}'.format(dsid[:3], dsid[3:]),\n        )\n        props.update(\n            type='ria',\n            giturl=str(source_ri),\n            version=version,\n            default_destpath=dsid,\n        )\n    else:\n        # let's assume that anything else is a URI that Git can handle\n        props['type'] = 'giturl'\n        # use original input verbatim\n        props['giturl'] = spec\n\n    if 'default_destpath' not in props:\n        # if we still have no good idea on where a dataset could be cloned to if no\n        # path was given, do something similar to git clone and derive the path from\n        # the source\n        props['default_destpath'] = _get_installationpath_from_url(props['giturl'])\n\n    return props",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 878,
                            "end_lineno": 961,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "# ex: set sts=4 ts=4 sw=4 noet:\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n#   See COPYING file distributed along with the datalad package for the\n#   copyright and license terms.\n#\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n\"\"\"Test clone action\n\n\"\"\"\n\nimport logging\nimport os.path as op\nimport stat\n\nfrom unittest.mock import patch\n\nfrom datalad.config import ConfigManager\nfrom datalad import consts\nfrom datalad.api import (\n    clone,\n    create,\n    remove,\n)\nfrom datalad.utils import (\n    chpwd,\n    Path,\n    on_windows,\n)\nfrom datalad.support.exceptions import IncompleteResultsError\nfrom datalad.support.gitrepo import GitRepo\nfrom datalad.support.annexrepo import AnnexRepo\nfrom datalad.cmd import Runner\nfrom datalad.tests.utils import (\n    assert_false,\n    assert_in,\n    assert_message,\n    assert_not_in,\n    assert_raises,\n    assert_repo_status,\n    assert_result_count,\n    assert_result_values_equal,\n    assert_status,\n    create_tree,\n    eq_,\n    get_datasets_topdir,\n    integration,\n    known_failure,\n    known_failure_appveyor,\n    neq_,\n    nok_,\n    ok_,\n    ok_file_has_content,\n    has_symlink_capability,\n    ok_startswith,\n    patch_config,\n    serve_path_via_http,\n    skip_if_no_network,\n    skip_if_on_windows,\n    slow,\n    swallow_logs,\n    use_cassette,\n    with_sameas_remote,\n    with_tempfile,\n    with_testrepos,\n    with_tree,\n    SkipTest,\n)\nfrom datalad.core.distributed.clone import (\n    _get_installationpath_from_url,\n    decode_source_spec,\n)\nfrom datalad.distribution.dataset import Dataset\n\n# this is the dataset ID of our test dataset in the main datalad RIA store\ndatalad_store_testds_id = '76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561'\n\n\n@with_tempfile(mkdir=True)\n@with_tempfile(mkdir=True)\n@with_tempfile(mkdir=True)\ndef test_invalid_args(path, otherpath, alienpath):\n    # source == path\n    assert_raises(ValueError, clone, 'Zoidberg', path='Zoidberg')\n    assert_raises(ValueError, clone, 'ssh://mars/Zoidberg', path='ssh://mars/Zoidberg')\n\n    # \"invalid URL\" is a valid filepath... and since no clone to remote\n    # is possible - we can just assume that it is the (legit) file path\n    # which is provided, not a URL.  So both below should fail as any\n    # other clone from a non-existing source and not for the reason of\n    # \"invalid something\".  Behavior is similar to how Git performs - can\n    # clone into a URL-like path.\n\n    # install to an \"invalid URL\" path\n    res = clone('Zoidberg', path='ssh://mars:Zoidberg', on_failure='ignore')\n    assert_status('error', res)\n\n    # install to a \"remote location\" path\n    res = clone('Zoidberg', path='ssh://mars/Zoidberg', on_failure='ignore')\n    assert_status('error', res)\n\n    # make fake dataset\n    ds = create(path)\n    assert_raises(IncompleteResultsError, ds.clone, '/higherup.', 'Zoidberg')\n    # make real dataset, try to install outside\n    ds_target = create(Path(otherpath) / 'target')\n    assert_raises(ValueError, ds_target.clone, ds.path, path=ds.path)\n    assert_status('error', ds_target.clone(ds.path, path=alienpath, on_failure='ignore'))\n\n\n@integration\n@skip_if_no_network\n@use_cassette('test_install_crcns')\n@with_tempfile(mkdir=True)\n@with_tempfile(mkdir=True)\ndef test_clone_crcns(tdir, ds_path):\n    with chpwd(tdir):\n        res = clone('///', path=\"all-nonrecursive\", on_failure='ignore',\n                    result_xfm=None, return_type='list')\n        assert_status('ok', res)\n\n    # again, but into existing dataset:\n    ds = create(ds_path)\n    crcns = ds.clone(\"///crcns\", result_xfm='datasets', return_type='item-or-list')\n    ok_(crcns.is_installed())\n    eq_(crcns.pathobj, ds.pathobj / \"crcns\")\n    assert_in(crcns.path, ds.subdatasets(result_xfm='paths'))\n\n\n@integration\n@skip_if_no_network\n@use_cassette('test_install_crcns')\n@with_tree(tree={'sub': {}})\ndef test_clone_datasets_root(tdir):\n    tdir = Path(tdir)\n    with chpwd(tdir):\n        ds = clone(\"///\")\n        ok_(ds.is_installed())\n        eq_(ds.pathobj, tdir / get_datasets_topdir())\n\n        # do it a second time:\n        res = clone(\"///\", on_failure='ignore', result_xfm=None, return_type='list')\n        assert_message(\n            \"dataset %s was already cloned from '%s'\",\n            res)\n        assert_status('notneeded', res)\n\n        # and a third time into an existing something, that is not a dataset:\n        (tdir / 'sub' / 'a_file.txt').write_text(\"something\")\n\n        res = clone('///', path=\"sub\", on_failure='ignore')\n        assert_message(\n            'target path already exists and not empty, refuse to clone into target path',\n            res)\n        assert_status('error', res)\n\n\n@with_testrepos('.*basic.*', flavors=['local-url', 'network', 'local'])\n@with_tempfile(mkdir=True)\ndef test_clone_simple_local(src, path):\n    origin = Dataset(path)\n\n    # now install it somewhere else\n    ds = clone(src, path, description='mydummy',\n               result_xfm='datasets', return_type='item-or-list')\n    eq_(ds.path, path)\n    ok_(ds.is_installed())\n    if not isinstance(origin.repo, AnnexRepo):\n        # this means it is a GitRepo\n        ok_(isinstance(origin.repo, GitRepo))\n        # stays plain Git repo\n        ok_(isinstance(ds.repo, GitRepo))\n        ok_(not isinstance(ds.repo, AnnexRepo))\n        ok_(GitRepo.is_valid_repo(ds.path))\n        eq_(set(ds.repo.get_indexed_files()),\n            {'test.dat', 'INFO.txt'})\n        assert_repo_status(path, annex=False)\n    else:\n        # must be an annex\n        ok_(isinstance(ds.repo, AnnexRepo))\n        ok_(AnnexRepo.is_valid_repo(ds.path, allow_noninitialized=False))\n        eq_(set(ds.repo.get_indexed_files()),\n            {'test.dat', 'INFO.txt', 'test-annex.dat'})\n        assert_repo_status(path, annex=True)\n        # no content was installed:\n        ok_(not ds.repo.file_has_content('test-annex.dat'))\n        uuid_before = ds.repo.uuid\n        eq_(ds.repo.get_description(), 'mydummy')\n\n    # installing it again, shouldn't matter:\n    res = clone(src, path, result_xfm=None, return_type='list')\n    assert_result_values_equal(res, 'source_url', [src])\n    assert_status('notneeded', res)\n    assert_message(\"dataset %s was already cloned from '%s'\", res)\n    ok_(ds.is_installed())\n    if isinstance(origin.repo, AnnexRepo):\n        eq_(uuid_before, ds.repo.uuid)\n\n\n@with_testrepos(flavors=['local-url', 'network', 'local'])\n@with_tempfile\ndef test_clone_dataset_from_just_source(url, path):\n    with chpwd(path, mkdir=True):\n        ds = clone(url, result_xfm='datasets', return_type='item-or-list')\n\n    ok_startswith(ds.path, path)\n    ok_(ds.is_installed())\n    ok_(GitRepo.is_valid_repo(ds.path))\n    assert_repo_status(ds.path, annex=None)\n    assert_in('INFO.txt', ds.repo.get_indexed_files())\n\n\n# test fails randomly, likely a bug in one of the employed test helpers\n# https://github.com/datalad/datalad/pull/3966#issuecomment-571267932\n@known_failure\n@with_tree(tree={\n    'ds': {'test.txt': 'some'},\n    })\n@serve_path_via_http\n@with_tempfile(mkdir=True)\ndef test_clone_dataladri(src, topurl, path):\n    # make plain git repo\n    ds_path = Path(src) / 'ds'\n    gr = GitRepo(ds_path, create=True)\n    gr.add('test.txt')\n    gr.commit('demo')\n    Runner(cwd=gr.path)(['git', 'update-server-info'])\n    # now install it somewhere else\n    with patch('datalad.consts.DATASETS_TOPURL', topurl):\n        ds = clone('///ds', path, result_xfm='datasets', return_type='item-or-list')\n    eq_(ds.path, path)\n    assert_repo_status(path, annex=False)\n    ok_file_has_content(ds.pathobj / 'test.txt', 'some')\n\n\n@with_testrepos('submodule_annex', flavors=['local', 'local-url', 'network'])\n@with_tempfile(mkdir=True)\n@with_tempfile(mkdir=True)\ndef test_clone_isnot_recursive(src, path_nr, path_r):\n    ds = clone(src, path_nr, result_xfm='datasets', return_type='item-or-list')\n    ok_(ds.is_installed())\n    # check nothin is unintentionally installed\n    subdss = ds.subdatasets(recursive=True)\n    assert_result_count(subdss, len(subdss), state='absent')\n    # this also means, subdatasets to be listed as not fulfilled:\n    eq_(set(ds.subdatasets(recursive=True, fulfilled=False, result_xfm='relpaths')),\n        {'subm 1', '2'})\n\n\n@slow  # 23.1478s\n@with_testrepos(flavors=['local'])\n# 'local-url', 'network'\n# TODO: Somehow annex gets confused while initializing installed ds, whose\n# .git/config show a submodule url \"file:///aaa/bbb%20b/...\"\n# this is delivered by with_testrepos as the url to clone\n@with_tempfile\ndef test_clone_into_dataset(source, top_path):\n\n    ds = create(top_path)\n    assert_repo_status(ds.path)\n\n    subds = ds.clone(source, \"sub\",\n                     result_xfm='datasets', return_type='item-or-list')\n    ok_((subds.pathobj / '.git').is_dir())\n    ok_(subds.is_installed())\n    assert_in('sub', ds.subdatasets(fulfilled=True, result_xfm='relpaths'))\n    # sub is clean:\n    assert_repo_status(subds.path, annex=None)\n    # top is clean:\n    assert_repo_status(ds.path, annex=None)\n\n    # but we could also save while installing and there should be no side-effect\n    # of saving any other changes if we state to not auto-save changes\n    # Create a dummy change\n    create_tree(ds.path, {'dummy.txt': 'buga'})\n    assert_repo_status(ds.path, untracked=['dummy.txt'])\n    subds_ = ds.clone(source, \"sub2\",\n                      result_xfm='datasets', return_type='item-or-list')\n    eq_(subds_.pathobj, ds.pathobj / \"sub2\")  # for paranoid yoh ;)\n    assert_repo_status(ds.path, untracked=['dummy.txt'])\n\n\n@with_testrepos('submodule_annex', flavors=['local', 'local-url', 'network'])\n@with_tempfile(mkdir=True)\ndef test_notclone_known_subdataset(src, path):\n    # get the superdataset:\n    ds = clone(src, path,\n               result_xfm='datasets', return_type='item-or-list')\n\n    # subdataset not installed:\n    subds = Dataset(ds.pathobj / 'subm 1')\n    assert_false(subds.is_installed())\n    assert_in('subm 1', ds.subdatasets(fulfilled=False, result_xfm='relpaths'))\n    assert_not_in('subm 1', ds.subdatasets(fulfilled=True, result_xfm='relpaths'))\n    # clone is not meaningful\n    res = ds.clone('subm 1', on_failure='ignore')\n    assert_status('error', res)\n    assert_message('Failed to clone from all attempted sources: %s',\n                   res)\n    # get does the job\n    res = ds.get(path='subm 1', get_data=False)\n    assert_status('ok', res)\n    ok_(subds.is_installed())\n    ok_(AnnexRepo.is_valid_repo(subds.path, allow_noninitialized=False))\n    # Verify that it is the correct submodule installed and not\n    # new repository initiated\n    eq_(set(subds.repo.get_indexed_files()),\n        {'test.dat', 'INFO.txt', 'test-annex.dat'})\n    assert_not_in('subm 1', ds.subdatasets(fulfilled=False, result_xfm='relpaths'))\n    assert_in('subm 1', ds.subdatasets(fulfilled=True, result_xfm='relpaths'))\n\n\n@with_tempfile(mkdir=True)\ndef test_failed_clone(dspath):\n    ds = create(dspath)\n    res = ds.clone(\"http://nonexistingreallyanything.datalad.org/bla\", \"sub\",\n                   on_failure='ignore')\n    assert_status('error', res)\n    assert_message('Failed to clone from all attempted sources: %s',\n                   res)\n\n\n@with_testrepos('submodule_annex', flavors=['local'])\n@with_tempfile(mkdir=True)\n@with_tempfile(mkdir=True)\ndef test_reckless(src, top_path, sharedpath):\n    ds = clone(src, top_path, reckless=True,\n               result_xfm='datasets', return_type='item-or-list')\n    eq_(ds.config.get('annex.hardlink', None), 'true')\n    # actual value is 'auto', because True is a legacy value and we map it\n    eq_(ds.config.get('datalad.clone.reckless', None), 'auto')\n    eq_(ds.repo.repo_info()['untrusted repositories'][0]['here'], True)\n    # now, if we clone another repo into this one, it will inherit the setting\n    # without having to provide it explicitly\n    sub = ds.clone(src, 'sub', result_xfm='datasets', return_type='item-or-list')\n    eq_(sub.config.get('datalad.clone.reckless', None), 'auto')\n    eq_(sub.config.get('annex.hardlink', None), 'true')\n\n    if ds.repo.is_managed_branch():\n        raise SkipTest(\"Remainder of test needs proper filesystem permissions\")\n\n    # the standard setup keeps the annex locks accessible to the user only\n    nok_((ds.pathobj / '.git' / 'annex' / 'index.lck').stat().st_mode \\\n         & stat.S_IWGRP)\n    # but we can set it up for group-shared access too\n    sharedds = clone(\n        src, sharedpath,\n        reckless='shared-group',\n        result_xfm='datasets',\n        return_type='item-or-list')\n    ok_((sharedds.pathobj / '.git' / 'annex' / 'index.lck').stat().st_mode \\\n        & stat.S_IWGRP)\n\n\n@with_tempfile\n@with_tempfile\ndef test_install_source_relpath(src, dest):\n    src = Path(src)\n    create(src)\n    src_ = src.name\n    with chpwd(src.parent):\n        clone(src_, dest)\n\n\n@with_tempfile\n@with_tempfile\ndef test_clone_isnt_a_smartass(origin_path, path):\n    origin = create(origin_path)\n    cloned = clone(origin, path,\n                   result_xfm='datasets', return_type='item-or-list')\n    with chpwd(path):\n        # no were are inside a dataset clone, and we make another one\n        # we do not want automatic subdatasetification without given a dataset\n        # explicitely\n        clonedsub = clone(origin, 'testsub',\n                          result_xfm='datasets', return_type='item-or-list')\n    # correct destination\n    assert clonedsub.path.startswith(path)\n    # no subdataset relation\n    eq_(cloned.subdatasets(), [])\n\n\n@with_tempfile(mkdir=True)\ndef test_clone_report_permission_issue(tdir):\n    pdir = Path(tdir) / 'protected'\n    pdir.mkdir()\n    # make it read-only\n    pdir.chmod(0o555)\n    with chpwd(pdir):\n        # first check the premise of the test. If we can write (strangely\n        # mounted/crippled file system, subsequent assumptions are violated\n        # and we can stop\n        probe = Path('probe')\n        try:\n            probe.write_text('should not work')\n            raise SkipTest\n        except PermissionError:\n            # we are indeed in a read-only situation\n            pass\n        res = clone('///', result_xfm=None, return_type='list', on_failure='ignore')\n        assert_status('error', res)\n        assert_result_count(\n            res, 1, status='error',\n            message=\"could not create work tree dir '%s/%s': Permission denied\"\n                    % (pdir, get_datasets_topdir())\n        )\n\n\n# Started to hang on appveyor.\n@known_failure_appveyor  #FIXME - hangs\n@skip_if_no_network\n@with_tempfile\ndef test_autoenabled_remote_msg(path):\n    # Verify that no message about a remote not been enabled is displayed\n    # whenever the remote we clone is the  type=git special remote, so the name\n    # of the remote might not match\n    with swallow_logs(new_level=logging.INFO) as cml:\n        res = clone('///repronim/containers', path, result_xfm=None, return_type='list')\n        assert_status('ok', res)\n        assert_not_in(\"not auto-enabled\", cml.out)\n\n\n@with_sameas_remote(autoenabled=True)\n@with_tempfile(mkdir=True)\ndef test_clone_autoenable_msg_handles_sameas(repo, clone_path):\n    ds = Dataset(repo.path)\n    with swallow_logs(new_level=logging.INFO) as cml:\n        res = clone(ds, clone_path, result_xfm=None, return_type='list')\n        assert_status('ok', res)\n        assert_in(\"r_dir\", cml.out)\n        assert_in(\"not auto-enabled\", cml.out)\n        # The rsyncurl remote was enabled.\n        assert_not_in(\"r_rsync\", cml.out)\n    ds_cloned = Dataset(clone_path)\n    remotes = ds_cloned.repo.get_remotes()\n    assert_in(\"r_rsync\", remotes)\n    assert_not_in(\"r_dir\", remotes)\n\n\ndef test_installationpath_from_url():\n    cases = (\n        'http://example.com/lastbit',\n        'http://example.com/lastbit.git',\n        'http://lastbit:8000',\n    ) + (\n        'C:\\\\Users\\\\mih\\\\AppData\\\\Local\\\\Temp\\\\lastbit',\n        'C:\\\\Users\\\\mih\\\\AppData\\\\Local\\\\Temp\\\\lastbit\\\\',\n        'Temp\\\\lastbit',\n        'Temp\\\\lastbit\\\\',\n        'lastbit.git',\n        'lastbit.git\\\\',\n    ) if on_windows else (\n        'lastbit',\n        'lastbit/',\n        '/lastbit',\n        'lastbit.git',\n        'lastbit.git/',\n    )\n    for p in cases:\n        eq_(_get_installationpath_from_url(p), 'lastbit')\n    # we need to deal with quoted urls\n    for url in (\n        # although some docs say that space could've been replaced with +\n        'http://localhost:8000/+last%20bit',\n        'http://localhost:8000/%2Blast%20bit',\n        '///%2Blast%20bit',\n        '///d1/%2Blast%20bit',\n        '///d1/+last bit',\n    ):\n        eq_(_get_installationpath_from_url(url), '+last bit')\n    # and the hostname alone\n    eq_(_get_installationpath_from_url(\"http://hostname\"), 'hostname')\n    eq_(_get_installationpath_from_url(\"http://hostname/\"), 'hostname')\n\n\n# https://github.com/datalad/datalad/issues/3958\n@with_tempfile(mkdir=True)\n@with_tempfile(mkdir=True)\ndef test_expanduser(srcpath, destpath):\n    src = Dataset(Path(srcpath) / 'src').create()\n    dest = Dataset(Path(destpath) / 'dest').create()\n\n    with chpwd(destpath), patch.dict('os.environ', {'HOME': srcpath}):\n        res = clone(op.join('~', 'src'), 'dest', result_xfm=None, return_type='list',\n                    on_failure='ignore')\n        assert_result_count(res, 1)\n        assert_result_count(\n            res, 1, action='install', status='error', path=dest.path,\n            message='target path already exists and not empty, refuse to '\n            'clone into target path')\n        # wipe out destination, and try again\n        assert_status('ok', remove(dataset=dest, check=False))\n        # now it should do it, and clone the right one\n        cloneds = clone(op.join('~', 'src'), 'dest')\n        eq_(cloneds.pathobj, Path(destpath) / 'dest')\n        eq_(src.id, cloneds.id)\n        # and it shouldn't fail when doing it again, because it detects\n        # the re-clone\n        cloneds = clone(op.join('~', 'src'), 'dest')\n        eq_(cloneds.pathobj, Path(destpath) / 'dest')\n\n\n@with_tempfile(mkdir=True)\ndef test_cfg_originorigin(path):\n    path = Path(path)\n    origin = Dataset(path / 'origin').create()\n    (origin.pathobj / 'file1.txt').write_text('content')\n    origin.save()\n    clone_lev1 = clone(origin, path / 'clone_lev1')\n    clone_lev2 = clone(clone_lev1, path / 'clone_lev2')\n    # the goal is to be able to get file content from origin without\n    # the need to configure it manually\n    assert_result_count(\n        clone_lev2.get('file1.txt', on_failure='ignore'),\n        1,\n        action='get',\n        status='ok',\n        path=str(clone_lev2.pathobj / 'file1.txt'),\n    )\n    eq_((clone_lev2.pathobj / 'file1.txt').read_text(), 'content')\n    eq_(\n        Path(clone_lev2.siblings(\n            'query',\n            name='origin-2',\n            return_type='item-or-list')['url']),\n        origin.pathobj\n    )\n\n    # Clone another level, this time with a relative path. Drop content from\n    # lev2 so that origin is the only place that the file is available from.\n    clone_lev2.drop(\"file1.txt\")\n    with chpwd(path), swallow_logs(new_level=logging.DEBUG) as cml:\n        clone_lev3 = clone('clone_lev2', 'clone_lev3')\n        # we called git-annex-init; see gh-4367:\n        cml.assert_logged(msg=r\"[^[]*Async run \\[('git', 'annex'|'git-annex'), \"\n                              r\"'init'\",\n                          match=False,\n                          level='DEBUG')\n    assert_result_count(\n        clone_lev3.get('file1.txt', on_failure='ignore'),\n        1,\n        action='get',\n        status='ok',\n        path=str(clone_lev3.pathobj / 'file1.txt'))\n\n\n# test fix for gh-2601/gh-3538\n@known_failure\n@with_tempfile()\ndef test_relative_submodule_url(path):\n    Dataset(op.join(path, 'origin')).create()\n    ds = Dataset(op.join(path, 'ds')).create()\n    with chpwd(ds.path):\n        ds_cloned = ds.clone(\n            source=op.join(op.pardir, 'origin'),\n            path='sources')\n\n    # Check that a simple fetch call does not fail.\n    ds_cloned.repo.fetch()\n\n    subinfo = ds.subdatasets(return_type='item-or-list')\n    eq_(subinfo['gitmodule_url'],\n        # must be a relative URL, not platform-specific relpath!\n        '../../origin')\n\n\n@with_tree(tree={\"subdir\": {}})\n@with_tempfile(mkdir=True)\ndef test_local_url_with_fetch(path, path_other):\n    path = Path(path)\n    path_other = Path(path_other)\n    Dataset(path / \"source\").create()\n\n    for where, source, path in [\n            (path, \"source\", \"a\"),\n            (path / \"subdir\", op.join(op.pardir, \"source\"), \"a\"),\n            (path, \"source\", path_other / \"a\")]:\n        with chpwd(where):\n            ds_cloned = clone(source=source, path=path)\n            # Perform a fetch to check that the URL points to a valid location.\n            ds_cloned.repo.fetch()\n\n\ndef test_decode_source_spec():\n    # resolves datalad RIs:\n    eq_(decode_source_spec('///subds'),\n        dict(source='///subds', giturl=consts.DATASETS_TOPURL + 'subds', version=None,\n             type='dataladri', default_destpath='subds'))\n    assert_raises(NotImplementedError, decode_source_spec,\n                  '//custom/subds')\n\n    # doesn't harm others:\n    for url in (\n            'http://example.com',\n            '/absolute/path',\n            'file://localhost/some',\n            'localhost/another/path',\n            'user@someho.st/mydir',\n            'ssh://somewhe.re/else',\n            'git://github.com/datalad/testrepo--basic--r1',\n    ):\n        props = decode_source_spec(url)\n        dest = props.pop('default_destpath')\n        eq_(props, dict(source=url, version=None, giturl=url, type='giturl'))\n\n    # RIA URIs with and without version specification\n    dsid = '6d69ca68-7e85-11e6-904c-002590f97d84'\n    for proto, loc, version in (\n            ('http', 'example.com', None),\n            ('http', 'example.com', 'v1.0'),\n            ('http', 'example.com', 'some_with@in_it'),\n            ('ssh', 'example.com', 'some_with@in_it'),\n    ):\n        spec = 'ria+{}://{}{}{}'.format(\n            proto,\n            loc,\n            '#{}'.format(dsid),\n            '@{}'.format(version) if version else '')\n        eq_(decode_source_spec(spec),\n            dict(\n                source=spec,\n                giturl='{}://{}/{}/{}'.format(\n                    proto,\n                    loc,\n                    dsid[:3],\n                    dsid[3:]),\n                version=version,\n                default_destpath=dsid,\n                type='ria')\n        )\n    # not a dataset UUID\n    assert_raises(ValueError, decode_source_spec, 'ria+http://example.com#123')\n\n\ndef _move2store(storepath, d):\n    # make a bare clone of it into a local that matches the organization\n    # of a ria dataset store\n    store_loc = str(storepath / d.id[:3] / d.id[3:])\n    d.repo.call_git(['clone', '--bare', d.path, store_loc])\n    d.siblings('configure', name='store', url=str(store_loc),\n               result_renderer='disabled')\n    Runner(cwd=store_loc).run(['git', 'update-server-info'])\n\n\n@with_tree(tree={\n    'ds': {\n        'test.txt': 'some',\n        'subdir': {\n            'subds': {'testsub.txt': 'somemore'},\n        },\n    },\n})\n@with_tempfile(mkdir=True)\n@serve_path_via_http\ndef test_ria_http(lcl, storepath, url):\n    # create a local dataset with a subdataset\n    lcl = Path(lcl)\n    storepath = Path(storepath)\n    subds = Dataset(lcl / 'ds' / 'subdir' / 'subds').create(force=True)\n    subds.save()\n    ds = Dataset(lcl / 'ds').create(force=True)\n    ds.save(version_tag='original')\n    assert_repo_status(ds.path)\n    for d in (ds, subds):\n        _move2store(storepath, d)\n    # location of superds in store\n    storeds_loc = str(storepath / ds.id[:3] / ds.id[3:])\n    # now we should be able to clone from a ria+http url\n    # the super\n    riaclone = clone(\n        'ria+{}#{}'.format(url, ds.id),\n        lcl / 'clone',\n    )\n\n    # due to default configuration, clone() should automatically look for the\n    # subdataset in the store, too -- if not the following would fail, because\n    # we never configured a proper submodule URL\n    riaclonesub = riaclone.get(\n        op.join('subdir', 'subds'), get_data=False,\n        result_xfm='datasets', return_type='item-or-list')\n\n    # both datasets came from the store and must be set up in an identical\n    # fashion\n    for origds, cloneds in ((ds, riaclone), (subds, riaclonesub)):\n        eq_(origds.id, cloneds.id)\n        if not ds.repo.is_managed_branch():\n            # test logic cannot handle adjusted branches\n            eq_(origds.repo.get_hexsha(), cloneds.repo.get_hexsha())\n        ok_(cloneds.config.get('remote.origin.url').startswith(url))\n        eq_(cloneds.config.get('remote.origin.annex-ignore'), 'true')\n        eq_(cloneds.config.get('datalad.get.subdataset-source-candidate-origin'),\n            'ria+%s#{id}' % url)\n\n    # now advance the source dataset\n    (ds.pathobj / 'newfile.txt').write_text('new')\n    ds.save()\n    ds.publish(to='store')\n    Runner(cwd=storeds_loc).run(['git', 'update-server-info'])\n    # re-clone as before\n    riaclone2 = clone(\n        'ria+{}#{}'.format(url, ds.id),\n        lcl / 'clone2',\n    )\n    # and now clone a specific version, here given be the tag name\n    riaclone_orig = clone(\n        'ria+{}#{}@{}'.format(url, ds.id, 'original'),\n        lcl / 'clone_orig',\n    )\n    if not ds.repo.is_managed_branch():\n        # test logic cannot handle adjusted branches\n        # we got the precise version we wanted\n        eq_(riaclone.repo.get_hexsha(), riaclone_orig.repo.get_hexsha())\n        # and not the latest\n        eq_(riaclone2.repo.get_hexsha(), ds.repo.get_hexsha())\n        neq_(riaclone2.repo.get_hexsha(), riaclone_orig.repo.get_hexsha())\n\n    # attempt to clone a version that doesn't exist\n    with swallow_logs():\n        with assert_raises(IncompleteResultsError) as cme:\n            clone('ria+{}#{}@impossible'.format(url, ds.id),\n                  lcl / 'clone_failed')\n        assert_in(\"not found in upstream\", str(cme.exception))\n\n    # lastly test if URL rewriting is in effect\n    # on the surface we clone from an SSH source identified by some custom\n    # label, no full URL, but URL rewriting setup maps it back to the\n    # HTTP URL used above\n    with patch_config({\n            'url.ria+{}#.insteadof'.format(url): 'ria+ssh://somelabel#'}):\n        cloned_by_label = clone(\n            'ria+ssh://somelabel#{}'.format(origds.id),\n            lcl / 'cloned_by_label',\n        )\n    # so we get the same setup as above, but....\n    eq_(origds.id, cloned_by_label.id)\n    if not ds.repo.is_managed_branch():\n        # test logic cannot handle adjusted branches\n        eq_(origds.repo.get_hexsha(), cloned_by_label.repo.get_hexsha())\n    ok_(cloned_by_label.config.get('remote.origin.url').startswith(url))\n    eq_(cloned_by_label.config.get('remote.origin.annex-ignore'), 'true')\n    # ... the clone candidates go with the label-based URL such that\n    # future get() requests acknowlege a (system-wide) configuration\n    # update\n    eq_(cloned_by_label.config.get('datalad.get.subdataset-source-candidate-origin'),\n        'ria+ssh://somelabel#{id}')\n\n\n@with_tempfile(mkdir=True)\n@with_tempfile(mkdir=True)\n@serve_path_via_http\ndef test_inherit_src_candidates(lcl, storepath, url):\n    lcl = Path(lcl)\n    storepath = Path(storepath)\n    # dataset with a subdataset\n    ds1 = Dataset(lcl / 'ds1').create()\n    ds1sub = ds1.create('sub')\n    # a different dataset into which we install ds1, but do not touch its subds\n    ds2 = Dataset(lcl / 'ds2').create()\n    ds2.clone(source=ds1.path, path='mysub')\n\n    # we give no dataset a source candidate config!\n    # move all dataset into the store\n    for d in (ds1, ds1sub, ds2):\n        _move2store(storepath, d)\n\n    # now we must be able to obtain all three datasets from the store\n    riaclone = clone(\n        'ria+{}#{}'.format(\n            # store URL\n            url,\n            # ID of the root dataset\n            ds2.id),\n        lcl / 'clone',\n    )\n    # what happens is the the initial clone call sets a source candidate\n    # config, because it sees the dataset coming from a store\n    # all obtained subdatasets get the config inherited on-clone\n    datasets = riaclone.get('.', get_data=False, recursive=True, result_xfm='datasets')\n    # we get two subdatasets\n    eq_(len(datasets), 2)\n    for ds in datasets:\n        eq_(ConfigManager(dataset=ds, source='dataset-local').get(\n            'datalad.get.subdataset-source-candidate-origin'),\n            'ria+%s#{id}' % url)\n\n\n@skip_if_no_network\n@with_tempfile()\ndef test_ria_http_storedataladorg(path):\n    # can we clone from the store w/o any dedicated config\n    ds = clone('ria+http://store.datalad.org#{}'.format(datalad_store_testds_id), path)\n    ok_(ds.is_installed())\n    eq_(ds.id, datalad_store_testds_id)\n\n\n@skip_if_on_windows  # see gh-4131\n@with_tree(tree={\n    'ds': {\n        'test.txt': 'some',\n        'subdir': {'testsub.txt': 'somemore'},\n    },\n})\n@with_tempfile\n@with_tempfile\ndef test_ephemeral(origin_path, clone1_path, clone2_path):\n\n    file_test = Path('ds') / 'test.txt'\n    file_testsub = Path('ds') / 'subdir' / 'testsub.txt'\n\n    origin = Dataset(origin_path).create(force=True)\n    if origin.repo.is_managed_branch():\n        raise SkipTest('Ephemeral clones cannot use adjusted mode repos')\n\n    origin.save()\n    # 1. clone via path\n    clone1 = clone(origin_path, clone1_path, reckless='ephemeral')\n\n    can_symlink = has_symlink_capability()\n\n    if can_symlink:\n        clone1_annex = (clone1.repo.dot_git / 'annex')\n        ok_(clone1_annex.is_symlink())\n        ok_(clone1_annex.resolve().samefile(origin.repo.dot_git / 'annex'))\n        if not clone1.repo.is_managed_branch():\n            # TODO: We can't properly handle adjusted branch yet\n            eq_((clone1.pathobj / file_test).read_text(), 'some')\n            eq_((clone1.pathobj / file_testsub).read_text(), 'somemore')\n\n    # 2. clone via file-scheme URL\n    clone2 = clone('file://' + Path(origin_path).as_posix(), clone2_path,\n                   reckless='ephemeral')\n\n    if can_symlink:\n        clone2_annex = (clone2.repo.dot_git / 'annex')\n        ok_(clone2_annex.is_symlink())\n        ok_(clone2_annex.resolve().samefile(origin.repo.dot_git / 'annex'))\n        if not clone2.repo.is_managed_branch():\n            # TODO: We can't properly handle adjusted branch yet\n            eq_((clone1.pathobj / file_test).read_text(), 'some')\n            eq_((clone1.pathobj / file_testsub).read_text(), 'somemore')\n\n    # 3. add something to clone1 and push back to origin availability from\n    # clone1 should not be propagated (we declared 'here' dead to that end)\n\n    (clone1.pathobj / 'addition.txt').write_text(\"even more\")\n    clone1.save()\n    origin.config.set(\"receive.denyCurrentBranch\", \"updateInstead\",\n                      where=\"local\")\n    # Note, that the only thing to test is git-annex-dead here,\n    # if we couldn't symlink:\n    clone1.publish(to='origin', transfer_data='none' if can_symlink else 'auto')\n    if not origin.repo.is_managed_branch():\n        # test logic cannot handle adjusted branches\n        eq_(origin.repo.get_hexsha(), clone1.repo.get_hexsha())\n    res = origin.repo.whereis(\"addition.txt\")\n    if can_symlink:\n        # obv. present in origin, but this is not yet known to origin:\n        eq_(res, [])\n        res = origin.repo.fsck()\n        assert_result_count(res, 3, success=True)\n        # TODO: Double check whether annex reports POSIX paths o windows!\n        eq_({str(file_test), str(file_testsub), \"addition.txt\"},\n            {r['file'] for r in res})\n        # now origin knows:\n    res = origin.repo.whereis(\"addition.txt\")\n    eq_(res, [origin.config.get(\"annex.uuid\")])\n\n\n@with_tempfile(mkdir=True)\ndef test_clone_unborn_head(path):\n    ds_origin = Dataset(op.join(path, \"a\")).create()\n    repo = ds_origin.repo\n    managed = repo.is_managed_branch()\n\n    # The setup below is involved, mostly because it's accounting for adjusted\n    # branches. The scenario itself isn't so complicated, though:\n    #\n    #   * a checked out master branch with no commits\n    #   * a (potentially adjusted) \"abc\" branch with commits.\n    #   * a (potentially adjusted) \"chooseme\" branch whose tip commit has a\n    #     more recent commit than any in \"abc\".\n    (ds_origin.pathobj / \"foo\").write_text(\"foo content\")\n    ds_origin.save(message=\"foo\")\n    for res in repo.for_each_ref_(fields=\"refname\"):\n        ref = res[\"refname\"]\n        if \"master\" in ref:\n            repo.update_ref(ref.replace(\"master\", \"abc\"), ref)\n            repo.call_git([\"update-ref\", \"-d\", ref])\n    repo.update_ref(\"HEAD\",\n                    \"refs/heads/{}\".format(\n                        \"adjusted/abc(unlocked)\" if managed else \"abc\"),\n                    symbolic=True)\n    repo.call_git([\"checkout\", \"-b\", \"chooseme\", \"abc~1\"])\n    if managed:\n        repo.adjust()\n    (ds_origin.pathobj / \"bar\").write_text(\"bar content\")\n    ds_origin.save(message=\"bar\")\n    # Try to make the git-annex branch the most recently updated ref so that we\n    # test that it is skipped.\n    ds_origin.drop(\"bar\", check=False)\n    ds_origin.repo.checkout(\"master\", options=[\"--orphan\"])\n\n    ds = clone(ds_origin.path, op.join(path, \"b\"))\n    # We landed on the branch with the most recent commit, ignoring the\n    # git-annex branch.\n    branch = ds.repo.get_active_branch()\n    eq_(ds.repo.get_corresponding_branch(branch) or branch,\n        \"chooseme\")\n    eq_(ds_origin.repo.get_hexsha(\"chooseme\"),\n        ds.repo.get_hexsha(\"chooseme\"))\n    # In the context of this test, the clone should be on an adjusted branch if\n    # the source landed there initially because we're on the same file system.\n    eq_(managed, ds.repo.is_managed_branch())\n\n\n@with_tempfile(mkdir=True)\ndef test_clone_unborn_head_no_other_ref(path):\n    ds_origin = Dataset(op.join(path, \"a\")).create(annex=False)\n    ds_origin.repo.call_git([\"update-ref\", \"-d\", \"refs/heads/master\"])\n    with swallow_logs(new_level=logging.WARNING) as cml:\n        clone(source=ds_origin.path, path=op.join(path, \"b\"))\n        assert_in(\"could not find a branch with commits\", cml.out)\n\n\n@with_tempfile(mkdir=True)\ndef test_clone_unborn_head_sub(path):\n    ds_origin = Dataset(op.join(path, \"a\")).create()\n    ds_origin_sub = Dataset(op.join(path, \"a\", \"sub\")).create()\n    managed = ds_origin_sub.repo.is_managed_branch()\n    ds_origin_sub.repo.call_git([\"branch\", \"-m\", \"master\", \"other\"])\n    ds_origin.save()\n    ds_origin_sub.repo.checkout(\"master\", options=[\"--orphan\"])\n\n    ds_cloned = clone(source=ds_origin.path, path=op.join(path, \"b\"))\n    ds_cloned_sub = ds_cloned.get(\n        \"sub\", result_xfm=\"datasets\", return_type=\"item-or-list\")\n\n    branch = ds_cloned_sub.repo.get_active_branch()\n    eq_(ds_cloned_sub.repo.get_corresponding_branch(branch) or branch,\n        \"other\")\n    # In the context of this test, the clone should be on an adjusted branch if\n    # the source landed there initially because we're on the same file system.\n    eq_(managed, ds_cloned_sub.repo.is_managed_branch())\n\n\n@skip_if_no_network\n@with_tempfile\ndef test_gin_cloning(path):\n    # can we clone a public ds anoynmously from gin and retrieve content\n    ds = clone('https://gin.g-node.org/datalad/datalad-ci-target', path)\n    ok_(ds.is_installed())\n    annex_path = op.join('annex', 'two')\n    git_path = op.join('git', 'one')\n    eq_(ds.repo.file_has_content(annex_path), False)\n    eq_(ds.repo.is_under_annex(git_path), False)\n    result = ds.get(annex_path)\n    assert_result_count(result, 1)\n    assert_status('ok', result)\n    eq_(result[0]['path'], op.join(ds.path, annex_path))\n    ok_file_has_content(op.join(ds.path, annex_path), 'two\\n')\n    ok_file_has_content(op.join(ds.path, git_path), 'one\\n')\n",
            "new_file_content": "# ex: set sts=4 ts=4 sw=4 noet:\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n#   See COPYING file distributed along with the datalad package for the\n#   copyright and license terms.\n#\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n\"\"\"Test clone action\n\n\"\"\"\n\nimport logging\nimport os.path as op\nimport stat\n\nfrom unittest.mock import patch\n\nfrom datalad.config import ConfigManager\nfrom datalad import consts\nfrom datalad.api import (\n    clone,\n    create,\n    remove,\n)\nfrom datalad.utils import (\n    chpwd,\n    Path,\n    on_windows,\n)\nfrom datalad.support.exceptions import IncompleteResultsError\nfrom datalad.support.gitrepo import GitRepo\nfrom datalad.support.annexrepo import AnnexRepo\nfrom datalad.cmd import Runner\nfrom datalad.tests.utils import (\n    assert_false,\n    assert_in,\n    assert_message,\n    assert_not_in,\n    assert_raises,\n    assert_repo_status,\n    assert_result_count,\n    assert_result_values_equal,\n    assert_status,\n    create_tree,\n    eq_,\n    get_datasets_topdir,\n    integration,\n    known_failure,\n    known_failure_appveyor,\n    neq_,\n    nok_,\n    ok_,\n    ok_file_has_content,\n    has_symlink_capability,\n    ok_startswith,\n    patch_config,\n    serve_path_via_http,\n    skip_if_no_network,\n    skip_if_on_windows,\n    slow,\n    swallow_logs,\n    use_cassette,\n    with_sameas_remote,\n    with_tempfile,\n    with_testrepos,\n    with_tree,\n    SkipTest,\n)\nfrom datalad.core.distributed.clone import (\n    _get_installationpath_from_url,\n    decode_source_spec,\n)\nfrom datalad.distribution.dataset import Dataset\n\n# this is the dataset ID of our test dataset in the main datalad RIA store\ndatalad_store_testds_id = '76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561'\n\n\n@with_tempfile(mkdir=True)\n@with_tempfile(mkdir=True)\n@with_tempfile(mkdir=True)\ndef test_invalid_args(path, otherpath, alienpath):\n    # source == path\n    assert_raises(ValueError, clone, 'Zoidberg', path='Zoidberg')\n    assert_raises(ValueError, clone, 'ssh://mars/Zoidberg', path='ssh://mars/Zoidberg')\n\n    # \"invalid URL\" is a valid filepath... and since no clone to remote\n    # is possible - we can just assume that it is the (legit) file path\n    # which is provided, not a URL.  So both below should fail as any\n    # other clone from a non-existing source and not for the reason of\n    # \"invalid something\".  Behavior is similar to how Git performs - can\n    # clone into a URL-like path.\n\n    # install to an \"invalid URL\" path\n    res = clone('Zoidberg', path='ssh://mars:Zoidberg', on_failure='ignore')\n    assert_status('error', res)\n\n    # install to a \"remote location\" path\n    res = clone('Zoidberg', path='ssh://mars/Zoidberg', on_failure='ignore')\n    assert_status('error', res)\n\n    # make fake dataset\n    ds = create(path)\n    assert_raises(IncompleteResultsError, ds.clone, '/higherup.', 'Zoidberg')\n    # make real dataset, try to install outside\n    ds_target = create(Path(otherpath) / 'target')\n    assert_raises(ValueError, ds_target.clone, ds.path, path=ds.path)\n    assert_status('error', ds_target.clone(ds.path, path=alienpath, on_failure='ignore'))\n\n\n@integration\n@skip_if_no_network\n@use_cassette('test_install_crcns')\n@with_tempfile(mkdir=True)\n@with_tempfile(mkdir=True)\ndef test_clone_crcns(tdir, ds_path):\n    with chpwd(tdir):\n        res = clone('///', path=\"all-nonrecursive\", on_failure='ignore',\n                    result_xfm=None, return_type='list')\n        assert_status('ok', res)\n\n    # again, but into existing dataset:\n    ds = create(ds_path)\n    crcns = ds.clone(\"///crcns\", result_xfm='datasets', return_type='item-or-list')\n    ok_(crcns.is_installed())\n    eq_(crcns.pathobj, ds.pathobj / \"crcns\")\n    assert_in(crcns.path, ds.subdatasets(result_xfm='paths'))\n\n\n@integration\n@skip_if_no_network\n@use_cassette('test_install_crcns')\n@with_tree(tree={'sub': {}})\ndef test_clone_datasets_root(tdir):\n    tdir = Path(tdir)\n    with chpwd(tdir):\n        ds = clone(\"///\")\n        ok_(ds.is_installed())\n        eq_(ds.pathobj, tdir / get_datasets_topdir())\n\n        # do it a second time:\n        res = clone(\"///\", on_failure='ignore', result_xfm=None, return_type='list')\n        assert_message(\n            \"dataset %s was already cloned from '%s'\",\n            res)\n        assert_status('notneeded', res)\n\n        # and a third time into an existing something, that is not a dataset:\n        (tdir / 'sub' / 'a_file.txt').write_text(\"something\")\n\n        res = clone('///', path=\"sub\", on_failure='ignore')\n        assert_message(\n            'target path already exists and not empty, refuse to clone into target path',\n            res)\n        assert_status('error', res)\n\n\n@with_testrepos('.*basic.*', flavors=['local-url', 'network', 'local'])\n@with_tempfile(mkdir=True)\ndef test_clone_simple_local(src, path):\n    origin = Dataset(path)\n\n    # now install it somewhere else\n    ds = clone(src, path, description='mydummy',\n               result_xfm='datasets', return_type='item-or-list')\n    eq_(ds.path, path)\n    ok_(ds.is_installed())\n    if not isinstance(origin.repo, AnnexRepo):\n        # this means it is a GitRepo\n        ok_(isinstance(origin.repo, GitRepo))\n        # stays plain Git repo\n        ok_(isinstance(ds.repo, GitRepo))\n        ok_(not isinstance(ds.repo, AnnexRepo))\n        ok_(GitRepo.is_valid_repo(ds.path))\n        eq_(set(ds.repo.get_indexed_files()),\n            {'test.dat', 'INFO.txt'})\n        assert_repo_status(path, annex=False)\n    else:\n        # must be an annex\n        ok_(isinstance(ds.repo, AnnexRepo))\n        ok_(AnnexRepo.is_valid_repo(ds.path, allow_noninitialized=False))\n        eq_(set(ds.repo.get_indexed_files()),\n            {'test.dat', 'INFO.txt', 'test-annex.dat'})\n        assert_repo_status(path, annex=True)\n        # no content was installed:\n        ok_(not ds.repo.file_has_content('test-annex.dat'))\n        uuid_before = ds.repo.uuid\n        eq_(ds.repo.get_description(), 'mydummy')\n\n    # installing it again, shouldn't matter:\n    res = clone(src, path, result_xfm=None, return_type='list')\n    assert_result_values_equal(res, 'source_url', [src])\n    assert_status('notneeded', res)\n    assert_message(\"dataset %s was already cloned from '%s'\", res)\n    ok_(ds.is_installed())\n    if isinstance(origin.repo, AnnexRepo):\n        eq_(uuid_before, ds.repo.uuid)\n\n\n@with_testrepos(flavors=['local-url', 'network', 'local'])\n@with_tempfile\ndef test_clone_dataset_from_just_source(url, path):\n    with chpwd(path, mkdir=True):\n        ds = clone(url, result_xfm='datasets', return_type='item-or-list')\n\n    ok_startswith(ds.path, path)\n    ok_(ds.is_installed())\n    ok_(GitRepo.is_valid_repo(ds.path))\n    assert_repo_status(ds.path, annex=None)\n    assert_in('INFO.txt', ds.repo.get_indexed_files())\n\n\n# test fails randomly, likely a bug in one of the employed test helpers\n# https://github.com/datalad/datalad/pull/3966#issuecomment-571267932\n@known_failure\n@with_tree(tree={\n    'ds': {'test.txt': 'some'},\n    })\n@serve_path_via_http\n@with_tempfile(mkdir=True)\ndef test_clone_dataladri(src, topurl, path):\n    # make plain git repo\n    ds_path = Path(src) / 'ds'\n    gr = GitRepo(ds_path, create=True)\n    gr.add('test.txt')\n    gr.commit('demo')\n    Runner(cwd=gr.path)(['git', 'update-server-info'])\n    # now install it somewhere else\n    with patch('datalad.consts.DATASETS_TOPURL', topurl):\n        ds = clone('///ds', path, result_xfm='datasets', return_type='item-or-list')\n    eq_(ds.path, path)\n    assert_repo_status(path, annex=False)\n    ok_file_has_content(ds.pathobj / 'test.txt', 'some')\n\n\n@with_testrepos('submodule_annex', flavors=['local', 'local-url', 'network'])\n@with_tempfile(mkdir=True)\n@with_tempfile(mkdir=True)\ndef test_clone_isnot_recursive(src, path_nr, path_r):\n    ds = clone(src, path_nr, result_xfm='datasets', return_type='item-or-list')\n    ok_(ds.is_installed())\n    # check nothin is unintentionally installed\n    subdss = ds.subdatasets(recursive=True)\n    assert_result_count(subdss, len(subdss), state='absent')\n    # this also means, subdatasets to be listed as not fulfilled:\n    eq_(set(ds.subdatasets(recursive=True, fulfilled=False, result_xfm='relpaths')),\n        {'subm 1', '2'})\n\n\n@slow  # 23.1478s\n@with_testrepos(flavors=['local'])\n# 'local-url', 'network'\n# TODO: Somehow annex gets confused while initializing installed ds, whose\n# .git/config show a submodule url \"file:///aaa/bbb%20b/...\"\n# this is delivered by with_testrepos as the url to clone\n@with_tempfile\ndef test_clone_into_dataset(source, top_path):\n\n    ds = create(top_path)\n    assert_repo_status(ds.path)\n\n    subds = ds.clone(source, \"sub\",\n                     result_xfm='datasets', return_type='item-or-list')\n    ok_((subds.pathobj / '.git').is_dir())\n    ok_(subds.is_installed())\n    assert_in('sub', ds.subdatasets(fulfilled=True, result_xfm='relpaths'))\n    # sub is clean:\n    assert_repo_status(subds.path, annex=None)\n    # top is clean:\n    assert_repo_status(ds.path, annex=None)\n\n    # but we could also save while installing and there should be no side-effect\n    # of saving any other changes if we state to not auto-save changes\n    # Create a dummy change\n    create_tree(ds.path, {'dummy.txt': 'buga'})\n    assert_repo_status(ds.path, untracked=['dummy.txt'])\n    subds_ = ds.clone(source, \"sub2\",\n                      result_xfm='datasets', return_type='item-or-list')\n    eq_(subds_.pathobj, ds.pathobj / \"sub2\")  # for paranoid yoh ;)\n    assert_repo_status(ds.path, untracked=['dummy.txt'])\n\n\n@with_testrepos('submodule_annex', flavors=['local', 'local-url', 'network'])\n@with_tempfile(mkdir=True)\ndef test_notclone_known_subdataset(src, path):\n    # get the superdataset:\n    ds = clone(src, path,\n               result_xfm='datasets', return_type='item-or-list')\n\n    # subdataset not installed:\n    subds = Dataset(ds.pathobj / 'subm 1')\n    assert_false(subds.is_installed())\n    assert_in('subm 1', ds.subdatasets(fulfilled=False, result_xfm='relpaths'))\n    assert_not_in('subm 1', ds.subdatasets(fulfilled=True, result_xfm='relpaths'))\n    # clone is not meaningful\n    res = ds.clone('subm 1', on_failure='ignore')\n    assert_status('error', res)\n    assert_message('Failed to clone from all attempted sources: %s',\n                   res)\n    # get does the job\n    res = ds.get(path='subm 1', get_data=False)\n    assert_status('ok', res)\n    ok_(subds.is_installed())\n    ok_(AnnexRepo.is_valid_repo(subds.path, allow_noninitialized=False))\n    # Verify that it is the correct submodule installed and not\n    # new repository initiated\n    eq_(set(subds.repo.get_indexed_files()),\n        {'test.dat', 'INFO.txt', 'test-annex.dat'})\n    assert_not_in('subm 1', ds.subdatasets(fulfilled=False, result_xfm='relpaths'))\n    assert_in('subm 1', ds.subdatasets(fulfilled=True, result_xfm='relpaths'))\n\n\n@with_tempfile(mkdir=True)\ndef test_failed_clone(dspath):\n    ds = create(dspath)\n    res = ds.clone(\"http://nonexistingreallyanything.datalad.org/bla\", \"sub\",\n                   on_failure='ignore')\n    assert_status('error', res)\n    assert_message('Failed to clone from all attempted sources: %s',\n                   res)\n\n\n@with_testrepos('submodule_annex', flavors=['local'])\n@with_tempfile(mkdir=True)\n@with_tempfile(mkdir=True)\ndef test_reckless(src, top_path, sharedpath):\n    ds = clone(src, top_path, reckless=True,\n               result_xfm='datasets', return_type='item-or-list')\n    eq_(ds.config.get('annex.hardlink', None), 'true')\n    # actual value is 'auto', because True is a legacy value and we map it\n    eq_(ds.config.get('datalad.clone.reckless', None), 'auto')\n    eq_(ds.repo.repo_info()['untrusted repositories'][0]['here'], True)\n    # now, if we clone another repo into this one, it will inherit the setting\n    # without having to provide it explicitly\n    sub = ds.clone(src, 'sub', result_xfm='datasets', return_type='item-or-list')\n    eq_(sub.config.get('datalad.clone.reckless', None), 'auto')\n    eq_(sub.config.get('annex.hardlink', None), 'true')\n\n    if ds.repo.is_managed_branch():\n        raise SkipTest(\"Remainder of test needs proper filesystem permissions\")\n\n    # the standard setup keeps the annex locks accessible to the user only\n    nok_((ds.pathobj / '.git' / 'annex' / 'index.lck').stat().st_mode \\\n         & stat.S_IWGRP)\n    # but we can set it up for group-shared access too\n    sharedds = clone(\n        src, sharedpath,\n        reckless='shared-group',\n        result_xfm='datasets',\n        return_type='item-or-list')\n    ok_((sharedds.pathobj / '.git' / 'annex' / 'index.lck').stat().st_mode \\\n        & stat.S_IWGRP)\n\n\n@with_tempfile\n@with_tempfile\ndef test_install_source_relpath(src, dest):\n    src = Path(src)\n    create(src)\n    src_ = src.name\n    with chpwd(src.parent):\n        clone(src_, dest)\n\n\n@with_tempfile\n@with_tempfile\ndef test_clone_isnt_a_smartass(origin_path, path):\n    origin = create(origin_path)\n    cloned = clone(origin, path,\n                   result_xfm='datasets', return_type='item-or-list')\n    with chpwd(path):\n        # no were are inside a dataset clone, and we make another one\n        # we do not want automatic subdatasetification without given a dataset\n        # explicitely\n        clonedsub = clone(origin, 'testsub',\n                          result_xfm='datasets', return_type='item-or-list')\n    # correct destination\n    assert clonedsub.path.startswith(path)\n    # no subdataset relation\n    eq_(cloned.subdatasets(), [])\n\n\n@with_tempfile(mkdir=True)\ndef test_clone_report_permission_issue(tdir):\n    pdir = Path(tdir) / 'protected'\n    pdir.mkdir()\n    # make it read-only\n    pdir.chmod(0o555)\n    with chpwd(pdir):\n        # first check the premise of the test. If we can write (strangely\n        # mounted/crippled file system, subsequent assumptions are violated\n        # and we can stop\n        probe = Path('probe')\n        try:\n            probe.write_text('should not work')\n            raise SkipTest\n        except PermissionError:\n            # we are indeed in a read-only situation\n            pass\n        res = clone('///', result_xfm=None, return_type='list', on_failure='ignore')\n        assert_status('error', res)\n        assert_result_count(\n            res, 1, status='error',\n            message=\"could not create work tree dir '%s/%s': Permission denied\"\n                    % (pdir, get_datasets_topdir())\n        )\n\n\n# Started to hang on appveyor.\n@known_failure_appveyor  #FIXME - hangs\n@skip_if_no_network\n@with_tempfile\ndef test_autoenabled_remote_msg(path):\n    # Verify that no message about a remote not been enabled is displayed\n    # whenever the remote we clone is the  type=git special remote, so the name\n    # of the remote might not match\n    with swallow_logs(new_level=logging.INFO) as cml:\n        res = clone('///repronim/containers', path, result_xfm=None, return_type='list')\n        assert_status('ok', res)\n        assert_not_in(\"not auto-enabled\", cml.out)\n\n\n@with_sameas_remote(autoenabled=True)\n@with_tempfile(mkdir=True)\ndef test_clone_autoenable_msg_handles_sameas(repo, clone_path):\n    ds = Dataset(repo.path)\n    with swallow_logs(new_level=logging.INFO) as cml:\n        res = clone(ds, clone_path, result_xfm=None, return_type='list')\n        assert_status('ok', res)\n        assert_in(\"r_dir\", cml.out)\n        assert_in(\"not auto-enabled\", cml.out)\n        # The rsyncurl remote was enabled.\n        assert_not_in(\"r_rsync\", cml.out)\n    ds_cloned = Dataset(clone_path)\n    remotes = ds_cloned.repo.get_remotes()\n    assert_in(\"r_rsync\", remotes)\n    assert_not_in(\"r_dir\", remotes)\n\n\ndef test_installationpath_from_url():\n    cases = (\n        'http://example.com/lastbit',\n        'http://example.com/lastbit.git',\n        'http://lastbit:8000',\n    ) + (\n        'C:\\\\Users\\\\mih\\\\AppData\\\\Local\\\\Temp\\\\lastbit',\n        'C:\\\\Users\\\\mih\\\\AppData\\\\Local\\\\Temp\\\\lastbit\\\\',\n        'Temp\\\\lastbit',\n        'Temp\\\\lastbit\\\\',\n        'lastbit.git',\n        'lastbit.git\\\\',\n    ) if on_windows else (\n        'lastbit',\n        'lastbit/',\n        '/lastbit',\n        'lastbit.git',\n        'lastbit.git/',\n    )\n    for p in cases:\n        eq_(_get_installationpath_from_url(p), 'lastbit')\n    # we need to deal with quoted urls\n    for url in (\n        # although some docs say that space could've been replaced with +\n        'http://localhost:8000/+last%20bit',\n        'http://localhost:8000/%2Blast%20bit',\n        '///%2Blast%20bit',\n        '///d1/%2Blast%20bit',\n        '///d1/+last bit',\n    ):\n        eq_(_get_installationpath_from_url(url), '+last bit')\n    # and the hostname alone\n    eq_(_get_installationpath_from_url(\"http://hostname\"), 'hostname')\n    eq_(_get_installationpath_from_url(\"http://hostname/\"), 'hostname')\n\n\n# https://github.com/datalad/datalad/issues/3958\n@with_tempfile(mkdir=True)\n@with_tempfile(mkdir=True)\ndef test_expanduser(srcpath, destpath):\n    src = Dataset(Path(srcpath) / 'src').create()\n    dest = Dataset(Path(destpath) / 'dest').create()\n\n    with chpwd(destpath), patch.dict('os.environ', {'HOME': srcpath}):\n        res = clone(op.join('~', 'src'), 'dest', result_xfm=None, return_type='list',\n                    on_failure='ignore')\n        assert_result_count(res, 1)\n        assert_result_count(\n            res, 1, action='install', status='error', path=dest.path,\n            message='target path already exists and not empty, refuse to '\n            'clone into target path')\n        # wipe out destination, and try again\n        assert_status('ok', remove(dataset=dest, check=False))\n        # now it should do it, and clone the right one\n        cloneds = clone(op.join('~', 'src'), 'dest')\n        eq_(cloneds.pathobj, Path(destpath) / 'dest')\n        eq_(src.id, cloneds.id)\n        # and it shouldn't fail when doing it again, because it detects\n        # the re-clone\n        cloneds = clone(op.join('~', 'src'), 'dest')\n        eq_(cloneds.pathobj, Path(destpath) / 'dest')\n\n\n@with_tempfile(mkdir=True)\ndef test_cfg_originorigin(path):\n    path = Path(path)\n    origin = Dataset(path / 'origin').create()\n    (origin.pathobj / 'file1.txt').write_text('content')\n    origin.save()\n    clone_lev1 = clone(origin, path / 'clone_lev1')\n    clone_lev2 = clone(clone_lev1, path / 'clone_lev2')\n    # the goal is to be able to get file content from origin without\n    # the need to configure it manually\n    assert_result_count(\n        clone_lev2.get('file1.txt', on_failure='ignore'),\n        1,\n        action='get',\n        status='ok',\n        path=str(clone_lev2.pathobj / 'file1.txt'),\n    )\n    eq_((clone_lev2.pathobj / 'file1.txt').read_text(), 'content')\n    eq_(\n        Path(clone_lev2.siblings(\n            'query',\n            name='origin-2',\n            return_type='item-or-list')['url']),\n        origin.pathobj\n    )\n\n    # Clone another level, this time with a relative path. Drop content from\n    # lev2 so that origin is the only place that the file is available from.\n    clone_lev2.drop(\"file1.txt\")\n    with chpwd(path), swallow_logs(new_level=logging.DEBUG) as cml:\n        clone_lev3 = clone('clone_lev2', 'clone_lev3')\n        # we called git-annex-init; see gh-4367:\n        cml.assert_logged(msg=r\"[^[]*Async run \\[('git', 'annex'|'git-annex'), \"\n                              r\"'init'\",\n                          match=False,\n                          level='DEBUG')\n    assert_result_count(\n        clone_lev3.get('file1.txt', on_failure='ignore'),\n        1,\n        action='get',\n        status='ok',\n        path=str(clone_lev3.pathobj / 'file1.txt'))\n\n\n# test fix for gh-2601/gh-3538\n@known_failure\n@with_tempfile()\ndef test_relative_submodule_url(path):\n    Dataset(op.join(path, 'origin')).create()\n    ds = Dataset(op.join(path, 'ds')).create()\n    with chpwd(ds.path):\n        ds_cloned = ds.clone(\n            source=op.join(op.pardir, 'origin'),\n            path='sources')\n\n    # Check that a simple fetch call does not fail.\n    ds_cloned.repo.fetch()\n\n    subinfo = ds.subdatasets(return_type='item-or-list')\n    eq_(subinfo['gitmodule_url'],\n        # must be a relative URL, not platform-specific relpath!\n        '../../origin')\n\n\n@with_tree(tree={\"subdir\": {}})\n@with_tempfile(mkdir=True)\ndef test_local_url_with_fetch(path, path_other):\n    path = Path(path)\n    path_other = Path(path_other)\n    Dataset(path / \"source\").create()\n\n    for where, source, path in [\n            (path, \"source\", \"a\"),\n            (path / \"subdir\", op.join(op.pardir, \"source\"), \"a\"),\n            (path, \"source\", path_other / \"a\")]:\n        with chpwd(where):\n            ds_cloned = clone(source=source, path=path)\n            # Perform a fetch to check that the URL points to a valid location.\n            ds_cloned.repo.fetch()\n\n\ndef test_decode_source_spec():\n    # resolves datalad RIs:\n    eq_(decode_source_spec('///subds'),\n        dict(source='///subds', giturl=consts.DATASETS_TOPURL + 'subds', version=None,\n             type='dataladri', default_destpath='subds'))\n    assert_raises(NotImplementedError, decode_source_spec,\n                  '//custom/subds')\n\n    # doesn't harm others:\n    for url in (\n            'http://example.com',\n            '/absolute/path',\n            'file://localhost/some',\n            'localhost/another/path',\n            'user@someho.st/mydir',\n            'ssh://somewhe.re/else',\n            'git://github.com/datalad/testrepo--basic--r1',\n    ):\n        props = decode_source_spec(url)\n        dest = props.pop('default_destpath')\n        eq_(props, dict(source=url, version=None, giturl=url, type='giturl'))\n\n    # RIA URIs with and without version specification\n    dsid = '6d69ca68-7e85-11e6-904c-002590f97d84'\n    for proto, loc, version in (\n            ('http', 'example.com', None),\n            ('http', 'example.com', 'v1.0'),\n            ('http', 'example.com', 'some_with@in_it'),\n            ('ssh', 'example.com', 'some_with@in_it'),\n    ):\n        spec = 'ria+{}://{}{}{}'.format(\n            proto,\n            loc,\n            '#{}'.format(dsid),\n            '@{}'.format(version) if version else '')\n        eq_(decode_source_spec(spec),\n            dict(\n                source=spec,\n                giturl='{}://{}/{}/{}'.format(\n                    proto,\n                    loc,\n                    dsid[:3],\n                    dsid[3:]),\n                version=version,\n                default_destpath=dsid,\n                type='ria')\n        )\n    # not a dataset UUID\n    assert_raises(ValueError, decode_source_spec, 'ria+http://example.com#123')\n\n    # literal dataset name/location\n    eq_(decode_source_spec('ria+http://example.com#~rootds'),\n        {'source': 'ria+http://example.com#~rootds',\n         'version': None, 'type': 'ria',\n         'giturl': 'http://example.com/alias/rootds',\n         'default_destpath': 'rootds'})\n    # version etc still works\n    eq_(decode_source_spec('ria+http://example.com#~rootds@specialbranch'),\n        {'source': 'ria+http://example.com#~rootds@specialbranch',\n         'version': 'specialbranch', 'type': 'ria',\n         'giturl': 'http://example.com/alias/rootds',\n         'default_destpath': 'rootds'})\n\n\ndef _move2store(storepath, d):\n    # make a bare clone of it into a local that matches the organization\n    # of a ria dataset store\n    store_loc = str(storepath / d.id[:3] / d.id[3:])\n    d.repo.call_git(['clone', '--bare', d.path, store_loc])\n    d.siblings('configure', name='store', url=str(store_loc),\n               result_renderer='disabled')\n    Runner(cwd=store_loc).run(['git', 'update-server-info'])\n\n\n@with_tree(tree={\n    'ds': {\n        'test.txt': 'some',\n        'subdir': {\n            'subds': {'testsub.txt': 'somemore'},\n        },\n    },\n})\n@with_tempfile(mkdir=True)\n@serve_path_via_http\ndef test_ria_http(lcl, storepath, url):\n    # create a local dataset with a subdataset\n    lcl = Path(lcl)\n    storepath = Path(storepath)\n    subds = Dataset(lcl / 'ds' / 'subdir' / 'subds').create(force=True)\n    subds.save()\n    ds = Dataset(lcl / 'ds').create(force=True)\n    ds.save(version_tag='original')\n    assert_repo_status(ds.path)\n    for d in (ds, subds):\n        _move2store(storepath, d)\n    # location of superds in store\n    storeds_loc = str(storepath / ds.id[:3] / ds.id[3:])\n    # now we should be able to clone from a ria+http url\n    # the super\n    riaclone = clone(\n        'ria+{}#{}'.format(url, ds.id),\n        lcl / 'clone',\n    )\n\n    # due to default configuration, clone() should automatically look for the\n    # subdataset in the store, too -- if not the following would fail, because\n    # we never configured a proper submodule URL\n    riaclonesub = riaclone.get(\n        op.join('subdir', 'subds'), get_data=False,\n        result_xfm='datasets', return_type='item-or-list')\n\n    # both datasets came from the store and must be set up in an identical\n    # fashion\n    for origds, cloneds in ((ds, riaclone), (subds, riaclonesub)):\n        eq_(origds.id, cloneds.id)\n        if not ds.repo.is_managed_branch():\n            # test logic cannot handle adjusted branches\n            eq_(origds.repo.get_hexsha(), cloneds.repo.get_hexsha())\n        ok_(cloneds.config.get('remote.origin.url').startswith(url))\n        eq_(cloneds.config.get('remote.origin.annex-ignore'), 'true')\n        eq_(cloneds.config.get('datalad.get.subdataset-source-candidate-origin'),\n            'ria+%s#{id}' % url)\n\n    # now advance the source dataset\n    (ds.pathobj / 'newfile.txt').write_text('new')\n    ds.save()\n    ds.publish(to='store')\n    Runner(cwd=storeds_loc).run(['git', 'update-server-info'])\n    # re-clone as before\n    riaclone2 = clone(\n        'ria+{}#{}'.format(url, ds.id),\n        lcl / 'clone2',\n    )\n    # and now clone a specific version, here given be the tag name\n    riaclone_orig = clone(\n        'ria+{}#{}@{}'.format(url, ds.id, 'original'),\n        lcl / 'clone_orig',\n    )\n    if not ds.repo.is_managed_branch():\n        # test logic cannot handle adjusted branches\n        # we got the precise version we wanted\n        eq_(riaclone.repo.get_hexsha(), riaclone_orig.repo.get_hexsha())\n        # and not the latest\n        eq_(riaclone2.repo.get_hexsha(), ds.repo.get_hexsha())\n        neq_(riaclone2.repo.get_hexsha(), riaclone_orig.repo.get_hexsha())\n\n    # attempt to clone a version that doesn't exist\n    with swallow_logs():\n        with assert_raises(IncompleteResultsError) as cme:\n            clone('ria+{}#{}@impossible'.format(url, ds.id),\n                  lcl / 'clone_failed')\n        assert_in(\"not found in upstream\", str(cme.exception))\n\n    # lastly test if URL rewriting is in effect\n    # on the surface we clone from an SSH source identified by some custom\n    # label, no full URL, but URL rewriting setup maps it back to the\n    # HTTP URL used above\n    with patch_config({\n            'url.ria+{}#.insteadof'.format(url): 'ria+ssh://somelabel#'}):\n        cloned_by_label = clone(\n            'ria+ssh://somelabel#{}'.format(origds.id),\n            lcl / 'cloned_by_label',\n        )\n    # so we get the same setup as above, but....\n    eq_(origds.id, cloned_by_label.id)\n    if not ds.repo.is_managed_branch():\n        # test logic cannot handle adjusted branches\n        eq_(origds.repo.get_hexsha(), cloned_by_label.repo.get_hexsha())\n    ok_(cloned_by_label.config.get('remote.origin.url').startswith(url))\n    eq_(cloned_by_label.config.get('remote.origin.annex-ignore'), 'true')\n    # ... the clone candidates go with the label-based URL such that\n    # future get() requests acknowlege a (system-wide) configuration\n    # update\n    eq_(cloned_by_label.config.get('datalad.get.subdataset-source-candidate-origin'),\n        'ria+ssh://somelabel#{id}')\n\n    if not has_symlink_capability():\n        return\n    # place a symlink in the store to serve as a dataset alias\n    (storepath / 'alias').mkdir()\n    (storepath / 'alias' / 'myname').symlink_to(storeds_loc)\n    with chpwd(lcl):\n        cloned_by_alias = clone('ria+{}#~{}'.format(url, 'myname'))\n    # still get the same data\n    eq_(cloned_by_alias.id, ds.id)\n    # more sensible default install path\n    eq_(cloned_by_alias.pathobj.name, 'myname')\n\n\n@with_tempfile(mkdir=True)\n@with_tempfile(mkdir=True)\n@serve_path_via_http\ndef test_inherit_src_candidates(lcl, storepath, url):\n    lcl = Path(lcl)\n    storepath = Path(storepath)\n    # dataset with a subdataset\n    ds1 = Dataset(lcl / 'ds1').create()\n    ds1sub = ds1.create('sub')\n    # a different dataset into which we install ds1, but do not touch its subds\n    ds2 = Dataset(lcl / 'ds2').create()\n    ds2.clone(source=ds1.path, path='mysub')\n\n    # we give no dataset a source candidate config!\n    # move all dataset into the store\n    for d in (ds1, ds1sub, ds2):\n        _move2store(storepath, d)\n\n    # now we must be able to obtain all three datasets from the store\n    riaclone = clone(\n        'ria+{}#{}'.format(\n            # store URL\n            url,\n            # ID of the root dataset\n            ds2.id),\n        lcl / 'clone',\n    )\n    # what happens is the the initial clone call sets a source candidate\n    # config, because it sees the dataset coming from a store\n    # all obtained subdatasets get the config inherited on-clone\n    datasets = riaclone.get('.', get_data=False, recursive=True, result_xfm='datasets')\n    # we get two subdatasets\n    eq_(len(datasets), 2)\n    for ds in datasets:\n        eq_(ConfigManager(dataset=ds, source='dataset-local').get(\n            'datalad.get.subdataset-source-candidate-origin'),\n            'ria+%s#{id}' % url)\n\n\n@skip_if_no_network\n@with_tempfile()\ndef test_ria_http_storedataladorg(path):\n    # can we clone from the store w/o any dedicated config\n    ds = clone('ria+http://store.datalad.org#{}'.format(datalad_store_testds_id), path)\n    ok_(ds.is_installed())\n    eq_(ds.id, datalad_store_testds_id)\n\n\n@skip_if_on_windows  # see gh-4131\n@with_tree(tree={\n    'ds': {\n        'test.txt': 'some',\n        'subdir': {'testsub.txt': 'somemore'},\n    },\n})\n@with_tempfile\n@with_tempfile\ndef test_ephemeral(origin_path, clone1_path, clone2_path):\n\n    file_test = Path('ds') / 'test.txt'\n    file_testsub = Path('ds') / 'subdir' / 'testsub.txt'\n\n    origin = Dataset(origin_path).create(force=True)\n    if origin.repo.is_managed_branch():\n        raise SkipTest('Ephemeral clones cannot use adjusted mode repos')\n\n    origin.save()\n    # 1. clone via path\n    clone1 = clone(origin_path, clone1_path, reckless='ephemeral')\n\n    can_symlink = has_symlink_capability()\n\n    if can_symlink:\n        clone1_annex = (clone1.repo.dot_git / 'annex')\n        ok_(clone1_annex.is_symlink())\n        ok_(clone1_annex.resolve().samefile(origin.repo.dot_git / 'annex'))\n        if not clone1.repo.is_managed_branch():\n            # TODO: We can't properly handle adjusted branch yet\n            eq_((clone1.pathobj / file_test).read_text(), 'some')\n            eq_((clone1.pathobj / file_testsub).read_text(), 'somemore')\n\n    # 2. clone via file-scheme URL\n    clone2 = clone('file://' + Path(origin_path).as_posix(), clone2_path,\n                   reckless='ephemeral')\n\n    if can_symlink:\n        clone2_annex = (clone2.repo.dot_git / 'annex')\n        ok_(clone2_annex.is_symlink())\n        ok_(clone2_annex.resolve().samefile(origin.repo.dot_git / 'annex'))\n        if not clone2.repo.is_managed_branch():\n            # TODO: We can't properly handle adjusted branch yet\n            eq_((clone1.pathobj / file_test).read_text(), 'some')\n            eq_((clone1.pathobj / file_testsub).read_text(), 'somemore')\n\n    # 3. add something to clone1 and push back to origin availability from\n    # clone1 should not be propagated (we declared 'here' dead to that end)\n\n    (clone1.pathobj / 'addition.txt').write_text(\"even more\")\n    clone1.save()\n    origin.config.set(\"receive.denyCurrentBranch\", \"updateInstead\",\n                      where=\"local\")\n    # Note, that the only thing to test is git-annex-dead here,\n    # if we couldn't symlink:\n    clone1.publish(to='origin', transfer_data='none' if can_symlink else 'auto')\n    if not origin.repo.is_managed_branch():\n        # test logic cannot handle adjusted branches\n        eq_(origin.repo.get_hexsha(), clone1.repo.get_hexsha())\n    res = origin.repo.whereis(\"addition.txt\")\n    if can_symlink:\n        # obv. present in origin, but this is not yet known to origin:\n        eq_(res, [])\n        res = origin.repo.fsck()\n        assert_result_count(res, 3, success=True)\n        # TODO: Double check whether annex reports POSIX paths o windows!\n        eq_({str(file_test), str(file_testsub), \"addition.txt\"},\n            {r['file'] for r in res})\n        # now origin knows:\n    res = origin.repo.whereis(\"addition.txt\")\n    eq_(res, [origin.config.get(\"annex.uuid\")])\n\n\n@with_tempfile(mkdir=True)\ndef test_clone_unborn_head(path):\n    ds_origin = Dataset(op.join(path, \"a\")).create()\n    repo = ds_origin.repo\n    managed = repo.is_managed_branch()\n\n    # The setup below is involved, mostly because it's accounting for adjusted\n    # branches. The scenario itself isn't so complicated, though:\n    #\n    #   * a checked out master branch with no commits\n    #   * a (potentially adjusted) \"abc\" branch with commits.\n    #   * a (potentially adjusted) \"chooseme\" branch whose tip commit has a\n    #     more recent commit than any in \"abc\".\n    (ds_origin.pathobj / \"foo\").write_text(\"foo content\")\n    ds_origin.save(message=\"foo\")\n    for res in repo.for_each_ref_(fields=\"refname\"):\n        ref = res[\"refname\"]\n        if \"master\" in ref:\n            repo.update_ref(ref.replace(\"master\", \"abc\"), ref)\n            repo.call_git([\"update-ref\", \"-d\", ref])\n    repo.update_ref(\"HEAD\",\n                    \"refs/heads/{}\".format(\n                        \"adjusted/abc(unlocked)\" if managed else \"abc\"),\n                    symbolic=True)\n    repo.call_git([\"checkout\", \"-b\", \"chooseme\", \"abc~1\"])\n    if managed:\n        repo.adjust()\n    (ds_origin.pathobj / \"bar\").write_text(\"bar content\")\n    ds_origin.save(message=\"bar\")\n    # Try to make the git-annex branch the most recently updated ref so that we\n    # test that it is skipped.\n    ds_origin.drop(\"bar\", check=False)\n    ds_origin.repo.checkout(\"master\", options=[\"--orphan\"])\n\n    ds = clone(ds_origin.path, op.join(path, \"b\"))\n    # We landed on the branch with the most recent commit, ignoring the\n    # git-annex branch.\n    branch = ds.repo.get_active_branch()\n    eq_(ds.repo.get_corresponding_branch(branch) or branch,\n        \"chooseme\")\n    eq_(ds_origin.repo.get_hexsha(\"chooseme\"),\n        ds.repo.get_hexsha(\"chooseme\"))\n    # In the context of this test, the clone should be on an adjusted branch if\n    # the source landed there initially because we're on the same file system.\n    eq_(managed, ds.repo.is_managed_branch())\n\n\n@with_tempfile(mkdir=True)\ndef test_clone_unborn_head_no_other_ref(path):\n    ds_origin = Dataset(op.join(path, \"a\")).create(annex=False)\n    ds_origin.repo.call_git([\"update-ref\", \"-d\", \"refs/heads/master\"])\n    with swallow_logs(new_level=logging.WARNING) as cml:\n        clone(source=ds_origin.path, path=op.join(path, \"b\"))\n        assert_in(\"could not find a branch with commits\", cml.out)\n\n\n@with_tempfile(mkdir=True)\ndef test_clone_unborn_head_sub(path):\n    ds_origin = Dataset(op.join(path, \"a\")).create()\n    ds_origin_sub = Dataset(op.join(path, \"a\", \"sub\")).create()\n    managed = ds_origin_sub.repo.is_managed_branch()\n    ds_origin_sub.repo.call_git([\"branch\", \"-m\", \"master\", \"other\"])\n    ds_origin.save()\n    ds_origin_sub.repo.checkout(\"master\", options=[\"--orphan\"])\n\n    ds_cloned = clone(source=ds_origin.path, path=op.join(path, \"b\"))\n    ds_cloned_sub = ds_cloned.get(\n        \"sub\", result_xfm=\"datasets\", return_type=\"item-or-list\")\n\n    branch = ds_cloned_sub.repo.get_active_branch()\n    eq_(ds_cloned_sub.repo.get_corresponding_branch(branch) or branch,\n        \"other\")\n    # In the context of this test, the clone should be on an adjusted branch if\n    # the source landed there initially because we're on the same file system.\n    eq_(managed, ds_cloned_sub.repo.is_managed_branch())\n\n\n@skip_if_no_network\n@with_tempfile\ndef test_gin_cloning(path):\n    # can we clone a public ds anoynmously from gin and retrieve content\n    ds = clone('https://gin.g-node.org/datalad/datalad-ci-target', path)\n    ok_(ds.is_installed())\n    annex_path = op.join('annex', 'two')\n    git_path = op.join('git', 'one')\n    eq_(ds.repo.file_has_content(annex_path), False)\n    eq_(ds.repo.is_under_annex(git_path), False)\n    result = ds.get(annex_path)\n    assert_result_count(result, 1)\n    assert_status('ok', result)\n    eq_(result[0]['path'], op.join(ds.path, annex_path))\n    ok_file_has_content(op.join(ds.path, annex_path), 'two\\n')\n    ok_file_has_content(op.join(ds.path, git_path), 'one\\n')\n",
            "header": {
                "file": {
                    "path": "datalad/core/distributed/tests/test_clone.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "666b8ce5a",
                "new_commit_hash": "27feefdd7",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/datalad/core/distributed/tests/test_clone.py"
            },
            "plus_file": {
                "path": "b/datalad/core/distributed/tests/test_clone.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 631,
                            "length": 6
                        },
                        "new_range": {
                            "start": 631,
                            "length": 19
                        },
                        "section": "def test_decode_source_spec():"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    # not a dataset UUID",
                                "type": "context"
                            },
                            {
                                "content": "    assert_raises(ValueError, decode_source_spec, 'ria+http://example.com#123')",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    # literal dataset name/location",
                                "type": "added"
                            },
                            {
                                "content": "    eq_(decode_source_spec('ria+http://example.com#~rootds'),",
                                "type": "added"
                            },
                            {
                                "content": "        {'source': 'ria+http://example.com#~rootds',",
                                "type": "added"
                            },
                            {
                                "content": "         'version': None, 'type': 'ria',",
                                "type": "added"
                            },
                            {
                                "content": "         'giturl': 'http://example.com/alias/rootds',",
                                "type": "added"
                            },
                            {
                                "content": "         'default_destpath': 'rootds'})",
                                "type": "added"
                            },
                            {
                                "content": "    # version etc still works",
                                "type": "added"
                            },
                            {
                                "content": "    eq_(decode_source_spec('ria+http://example.com#~rootds@specialbranch'),",
                                "type": "added"
                            },
                            {
                                "content": "        {'source': 'ria+http://example.com#~rootds@specialbranch',",
                                "type": "added"
                            },
                            {
                                "content": "         'version': 'specialbranch', 'type': 'ria',",
                                "type": "added"
                            },
                            {
                                "content": "         'giturl': 'http://example.com/alias/rootds',",
                                "type": "added"
                            },
                            {
                                "content": "         'default_destpath': 'rootds'})",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "def _move2store(storepath, d):",
                                "type": "context"
                            },
                            {
                                "content": "    # make a bare clone of it into a local that matches the organization",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "datalad/core/distributed/tests/test_clone.py",
                            "type": "function",
                            "name": "test_decode_source_spec",
                            "content": "def test_decode_source_spec():\n    # resolves datalad RIs:\n    eq_(decode_source_spec('///subds'),\n        dict(source='///subds', giturl=consts.DATASETS_TOPURL + 'subds', version=None,\n             type='dataladri', default_destpath='subds'))\n    assert_raises(NotImplementedError, decode_source_spec,\n                  '//custom/subds')\n\n    # doesn't harm others:\n    for url in (\n            'http://example.com',\n            '/absolute/path',\n            'file://localhost/some',\n            'localhost/another/path',\n            'user@someho.st/mydir',\n            'ssh://somewhe.re/else',\n            'git://github.com/datalad/testrepo--basic--r1',\n    ):\n        props = decode_source_spec(url)\n        dest = props.pop('default_destpath')\n        eq_(props, dict(source=url, version=None, giturl=url, type='giturl'))\n\n    # RIA URIs with and without version specification\n    dsid = '6d69ca68-7e85-11e6-904c-002590f97d84'\n    for proto, loc, version in (\n            ('http', 'example.com', None),\n            ('http', 'example.com', 'v1.0'),\n            ('http', 'example.com', 'some_with@in_it'),\n            ('ssh', 'example.com', 'some_with@in_it'),\n    ):\n        spec = 'ria+{}://{}{}{}'.format(\n            proto,\n            loc,\n            '#{}'.format(dsid),\n            '@{}'.format(version) if version else '')\n        eq_(decode_source_spec(spec),\n            dict(\n                source=spec,\n                giturl='{}://{}/{}/{}'.format(\n                    proto,\n                    loc,\n                    dsid[:3],\n                    dsid[3:]),\n                version=version,\n                default_destpath=dsid,\n                type='ria')\n        )\n    # not a dataset UUID\n    assert_raises(ValueError, decode_source_spec, 'ria+http://example.com#123')\n\n    # literal dataset name/location\n    eq_(decode_source_spec('ria+http://example.com#~rootds'),\n        {'source': 'ria+http://example.com#~rootds',\n         'version': None, 'type': 'ria',\n         'giturl': 'http://example.com/alias/rootds',\n         'default_destpath': 'rootds'})\n    # version etc still works\n    eq_(decode_source_spec('ria+http://example.com#~rootds@specialbranch'),\n        {'source': 'ria+http://example.com#~rootds@specialbranch',\n         'version': 'specialbranch', 'type': 'ria',\n         'giturl': 'http://example.com/alias/rootds',\n         'default_destpath': 'rootds'})",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 584,
                            "end_lineno": 645,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 744,
                            "length": 6
                        },
                        "new_range": {
                            "start": 757,
                            "length": 18
                        },
                        "section": "def test_ria_http(lcl, storepath, url):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    eq_(cloned_by_label.config.get('datalad.get.subdataset-source-candidate-origin'),",
                                "type": "context"
                            },
                            {
                                "content": "        'ria+ssh://somelabel#{id}')",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    if not has_symlink_capability():",
                                "type": "added"
                            },
                            {
                                "content": "        return",
                                "type": "added"
                            },
                            {
                                "content": "    # place a symlink in the store to serve as a dataset alias",
                                "type": "added"
                            },
                            {
                                "content": "    (storepath / 'alias').mkdir()",
                                "type": "added"
                            },
                            {
                                "content": "    (storepath / 'alias' / 'myname').symlink_to(storeds_loc)",
                                "type": "added"
                            },
                            {
                                "content": "    with chpwd(lcl):",
                                "type": "added"
                            },
                            {
                                "content": "        cloned_by_alias = clone('ria+{}#~{}'.format(url, 'myname'))",
                                "type": "added"
                            },
                            {
                                "content": "    # still get the same data",
                                "type": "added"
                            },
                            {
                                "content": "    eq_(cloned_by_alias.id, ds.id)",
                                "type": "added"
                            },
                            {
                                "content": "    # more sensible default install path",
                                "type": "added"
                            },
                            {
                                "content": "    eq_(cloned_by_alias.pathobj.name, 'myname')",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "@with_tempfile(mkdir=True)",
                                "type": "context"
                            },
                            {
                                "content": "@with_tempfile(mkdir=True)",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "datalad/core/distributed/tests/test_clone.py",
                            "type": "function",
                            "name": "test_ria_http",
                            "content": "def test_ria_http(lcl, storepath, url):\n    # create a local dataset with a subdataset\n    lcl = Path(lcl)\n    storepath = Path(storepath)\n    subds = Dataset(lcl / 'ds' / 'subdir' / 'subds').create(force=True)\n    subds.save()\n    ds = Dataset(lcl / 'ds').create(force=True)\n    ds.save(version_tag='original')\n    assert_repo_status(ds.path)\n    for d in (ds, subds):\n        _move2store(storepath, d)\n    # location of superds in store\n    storeds_loc = str(storepath / ds.id[:3] / ds.id[3:])\n    # now we should be able to clone from a ria+http url\n    # the super\n    riaclone = clone(\n        'ria+{}#{}'.format(url, ds.id),\n        lcl / 'clone',\n    )\n\n    # due to default configuration, clone() should automatically look for the\n    # subdataset in the store, too -- if not the following would fail, because\n    # we never configured a proper submodule URL\n    riaclonesub = riaclone.get(\n        op.join('subdir', 'subds'), get_data=False,\n        result_xfm='datasets', return_type='item-or-list')\n\n    # both datasets came from the store and must be set up in an identical\n    # fashion\n    for origds, cloneds in ((ds, riaclone), (subds, riaclonesub)):\n        eq_(origds.id, cloneds.id)\n        if not ds.repo.is_managed_branch():\n            # test logic cannot handle adjusted branches\n            eq_(origds.repo.get_hexsha(), cloneds.repo.get_hexsha())\n        ok_(cloneds.config.get('remote.origin.url').startswith(url))\n        eq_(cloneds.config.get('remote.origin.annex-ignore'), 'true')\n        eq_(cloneds.config.get('datalad.get.subdataset-source-candidate-origin'),\n            'ria+%s#{id}' % url)\n\n    # now advance the source dataset\n    (ds.pathobj / 'newfile.txt').write_text('new')\n    ds.save()\n    ds.publish(to='store')\n    Runner(cwd=storeds_loc).run(['git', 'update-server-info'])\n    # re-clone as before\n    riaclone2 = clone(\n        'ria+{}#{}'.format(url, ds.id),\n        lcl / 'clone2',\n    )\n    # and now clone a specific version, here given be the tag name\n    riaclone_orig = clone(\n        'ria+{}#{}@{}'.format(url, ds.id, 'original'),\n        lcl / 'clone_orig',\n    )\n    if not ds.repo.is_managed_branch():\n        # test logic cannot handle adjusted branches\n        # we got the precise version we wanted\n        eq_(riaclone.repo.get_hexsha(), riaclone_orig.repo.get_hexsha())\n        # and not the latest\n        eq_(riaclone2.repo.get_hexsha(), ds.repo.get_hexsha())\n        neq_(riaclone2.repo.get_hexsha(), riaclone_orig.repo.get_hexsha())\n\n    # attempt to clone a version that doesn't exist\n    with swallow_logs():\n        with assert_raises(IncompleteResultsError) as cme:\n            clone('ria+{}#{}@impossible'.format(url, ds.id),\n                  lcl / 'clone_failed')\n        assert_in(\"not found in upstream\", str(cme.exception))\n\n    # lastly test if URL rewriting is in effect\n    # on the surface we clone from an SSH source identified by some custom\n    # label, no full URL, but URL rewriting setup maps it back to the\n    # HTTP URL used above\n    with patch_config({\n            'url.ria+{}#.insteadof'.format(url): 'ria+ssh://somelabel#'}):\n        cloned_by_label = clone(\n            'ria+ssh://somelabel#{}'.format(origds.id),\n            lcl / 'cloned_by_label',\n        )\n    # so we get the same setup as above, but....\n    eq_(origds.id, cloned_by_label.id)\n    if not ds.repo.is_managed_branch():\n        # test logic cannot handle adjusted branches\n        eq_(origds.repo.get_hexsha(), cloned_by_label.repo.get_hexsha())\n    ok_(cloned_by_label.config.get('remote.origin.url').startswith(url))\n    eq_(cloned_by_label.config.get('remote.origin.annex-ignore'), 'true')\n    # ... the clone candidates go with the label-based URL such that\n    # future get() requests acknowlege a (system-wide) configuration\n    # update\n    eq_(cloned_by_label.config.get('datalad.get.subdataset-source-candidate-origin'),\n        'ria+ssh://somelabel#{id}')\n\n    if not has_symlink_capability():\n        return\n    # place a symlink in the store to serve as a dataset alias\n    (storepath / 'alias').mkdir()\n    (storepath / 'alias' / 'myname').symlink_to(storeds_loc)\n    with chpwd(lcl):\n        cloned_by_alias = clone('ria+{}#~{}'.format(url, 'myname'))\n    # still get the same data\n    eq_(cloned_by_alias.id, ds.id)\n    # more sensible default install path\n    eq_(cloned_by_alias.pathobj.name, 'myname')",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 668,
                            "end_lineno": 770,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-\n# ex: set sts=4 ts=4 sw=4 noet:\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n#   See COPYING file distributed along with the datalad package for the\n#   copyright and license terms.\n#\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n\"\"\"Create a sibling in a RIA store\"\"\"\n\n__docformat__ = 'restructuredtext'\n\n\nimport logging\nimport subprocess\n\nfrom datalad.interface.common_opts import (\n    recursion_flag,\n    recursion_limit\n)\nfrom datalad.interface.base import (\n    build_doc,\n    Interface,\n)\nfrom datalad.interface.results import (\n    get_status_dict,\n)\nfrom datalad.interface.utils import eval_results\nfrom datalad.support.param import Parameter\nfrom datalad.support.constraints import (\n    EnsureBool,\n    EnsureChoice,\n    EnsureNone,\n    EnsureStr,\n)\nfrom datalad.distribution.dataset import (\n    datasetmethod,\n    EnsureDataset,\n    require_dataset,\n)\nfrom datalad.utils import (\n    Path,\n    quote_cmdlinearg,\n)\nfrom datalad.support.exceptions import (\n    CommandError\n)\nfrom datalad.support.gitrepo import (\n    GitRepo\n)\nfrom datalad.core.distributed.clone import (\n    decode_source_spec\n)\nfrom datalad.log import log_progress\nfrom datalad.distributed.ria_utils import (\n    get_layout_locations,\n    verify_ria_url,\n)\n\nlgr = logging.getLogger('datalad.distributed.create_sibling_ria')\n\n\n@build_doc\nclass CreateSiblingRia(Interface):\n    \"\"\"Creates a sibling to a dataset in a RIA store\n\n    Communication with a dataset in a RIA store is implemented via two\n    siblings. A regular Git remote (repository sibling) and a git-annex\n    special remote for data transfer (storage sibling) -- with the former\n    having a publication dependency on the latter. By default, the name of the\n    storage sibling is derived from the repository sibling's name by appending\n    \"-storage\".\n\n    The store's base path is expected to not exist, be an empty directory,\n    or a valid RIA store.\n\n    RIA store layout\n    ~~~~~~~~~~~~~~~~\n\n    A RIA store is a directory tree with a dedicated subdirectory for each\n    dataset in the store. The subdirectory name is constructed from the\n    DataLad dataset ID, e.g. '124/68afe-59ec-11ea-93d7-f0d5bf7b5561', where\n    the first three characters of the ID are used for an intermediate\n    subdirectory in order to mitigate files system limitations for stores\n    containing a large number of datasets.\n\n    Each dataset subdirectory contains a standard bare Git repository for\n    the dataset.\n\n    In addition, a subdirectory 'annex' hold a standard Git-annex object\n    store. However, instead of using the 'dirhashlower' naming scheme for\n    the object directories, like Git-annex would do, a 'dirhashmixed'\n    layout is used -- the same as for non-bare Git repositories or regular\n    DataLad datasets.\n\n    Optionally, there can be a further subdirectory 'archives' with\n    (compressed) 7z archives of annex objects. The storage remote is able to\n    pull annex objects from these archives, if it cannot find in the regular\n    annex object store. This feature can be useful for storing large\n    collections of rarely changing data on systems that limit the number of\n    files that can be stored.\n\n    Each dataset directory also contains a 'ria-layout-version' file that\n    identifies the data organization (as, for example, described above).\n\n    Lastly, there is a global 'ria-layout-version' file at the store's\n    base path that identifies where dataset subdirectories themselves are\n    located. At present, this file must contain a single line stating the\n    version (currently \"1\"). This line MUST end with a newline character.\n\n    Error logging\n    ~~~~~~~~~~~~~\n\n    To enable error logging at the remote end, append a pipe symbol and an \"l\"\n    to the version number in ria-layout-version (like so '1|l\\\\n').\n\n    Error logging will create files in an \"error_log\" directory whenever the\n    git-annex special remote (storage sibling) raises an exception, storing the\n    Python traceback of it. The logfiles are named according to the scheme\n    '<dataset id>.<annex uuid of the remote>.log' showing \"who\" ran into this\n    issue with which dataset. Because logging can potentially leak personal\n    data (like local file paths for example), it can be disabled client-side\n    by setting the configuration variable\n    \"annex.ora-remote.<storage-sibling-name>.ignore-remote-config\".\n    \"\"\"\n\n    # TODO: description?\n    _params_ = dict(\n        dataset=Parameter(\n            args=(\"-d\", \"--dataset\"),\n            doc=\"\"\"specify the dataset to process.  If\n            no dataset is given, an attempt is made to identify the dataset\n            based on the current working directory\"\"\",\n            constraints=EnsureDataset() | EnsureNone()),\n        url=Parameter(\n            args=(\"url\",),\n            metavar=\"ria+<ssh|file>://<host>[/path]\",\n            doc=\"\"\"URL identifying the target RIA store and access protocol.\n            \"\"\",\n            constraints=EnsureStr() | EnsureNone()),\n        name=Parameter(\n            args=('-s', '--name',),\n            metavar='NAME',\n            doc=\"\"\"Name of the sibling.\n            With `recursive`, the same name will be used to label all\n            the subdatasets' siblings.\"\"\",\n            constraints=EnsureStr() | EnsureNone(),\n            required=True),\n        storage_name=Parameter(\n            args=(\"--storage-name\",),\n            metavar=\"NAME\",\n            doc=\"\"\"Name of the storage sibling (git-annex special remote).\n            Must not be identical to the sibling name. If not specified,\n            defaults to the sibling name plus '-storage' suffix.\"\"\",\n            constraints=EnsureStr() | EnsureNone()),\n        post_update_hook=Parameter(\n            args=(\"--post-update-hook\",),\n            doc=\"\"\"Enable git's default post-update-hook for the created\n            sibling.\"\"\",\n            action=\"store_true\"),\n        shared=Parameter(\n            args=(\"--shared\",),\n            metavar='{false|true|umask|group|all|world|everybody|0xxx}',\n            doc=\"\"\"If given, configures the permissions in the\n            RIA store for multi-users access.\n            Possible values for this option are identical to those of\n            `git init --shared` and are described in its documentation.\"\"\",\n            constraints=EnsureStr() | EnsureBool() | EnsureNone()),\n        group=Parameter(\n            args=(\"--group\",),\n            metavar=\"GROUP\",\n            doc=\"\"\"Filesystem group for the repository. Specifying the group is\n            crucial when [CMD: --shared=group CMD][PY: shared=\"group\" PY]\"\"\",\n            constraints=EnsureStr() | EnsureNone()),\n        storage_sibling=Parameter(\n            args=(\"--no-storage-sibling\",),\n            dest='storage_sibling',\n            doc=\"\"\"Flag to disable establishing a storage sibling.\"\"\",\n            action=\"store_false\"),\n        existing=Parameter(\n            args=(\"--existing\",),\n            constraints=EnsureChoice(\n                'skip', 'error', 'reconfigure') | EnsureNone(),\n            metavar='MODE',\n            doc=\"\"\"Action to perform, if a (storage) sibling is already\n            configured under the given name and/or a target already exists.\n            In this case, a dataset can be skipped ('skip'), an existing target\n            repository be forcefully re-initialized, and the sibling\n            (re-)configured ('reconfigure'), or the command be instructed to\n            fail ('error').\"\"\", ),\n        recursive=recursion_flag,\n        recursion_limit=recursion_limit,\n        trust_level=Parameter(\n            args=(\"--trust-level\",),\n            metavar=\"TRUST-LEVEL\",\n            constraints=EnsureChoice(\n                'trust', 'semitrust', 'untrust') | EnsureNone(),\n            doc=\"\"\"specify a trust level for the storage sibling. If not\n            specified, the default git-annex trust level is used.\"\"\",),\n    )\n\n    @staticmethod\n    @datasetmethod(name='create_sibling_ria')\n    @eval_results\n    def __call__(url,\n                 name,\n                 dataset=None,\n                 storage_name=None,\n                 post_update_hook=False,\n                 shared=None,\n                 group=None,\n                 storage_sibling=True,\n                 existing='error',\n                 trust_level=None,\n                 recursive=False,\n                 recursion_limit=None\n                 ):\n\n        ds = require_dataset(\n            dataset, check_installed=True, purpose='create sibling RIA')\n        res_kwargs = dict(\n            ds=ds,\n            action=\"create-sibling-ria\",\n            logger=lgr,\n        )\n\n        if ds.repo.get_hexsha() is None or ds.id is None:\n            raise RuntimeError(\n                \"Repository at {} is not a DataLad dataset, \"\n                \"run 'datalad create [--force]' first.\".format(ds.path))\n\n        if not storage_sibling and storage_name:\n            lgr.warning(\n                \"Storage sibling setup disabled, but a storage sibling name \"\n                \"was provided\"\n            )\n\n        if storage_sibling and not storage_name:\n            storage_name = \"{}-storage\".format(name)\n\n        if storage_sibling and name == storage_name:\n            # leads to unresolvable, circular dependency with publish-depends\n            raise ValueError(\"sibling names must not be equal\")\n\n        if not isinstance(url, str):\n            raise TypeError(\"url is not a string, but %s\" % type(url))\n\n        # Query existing siblings upfront in order to fail early on\n        # existing=='error', since misconfiguration (particularly of special\n        # remotes) only to fail in a subdataset later on with that config, can\n        # be quite painful.\n        # TODO: messages - this is \"create-sibling\". Don't confuse existence of\n        #       local remotes with existence of the actual remote sibling\n        #       in wording\n        if existing == 'error':\n            # in recursive mode this check could take a substantial amount of\n            # time: employ a progress bar (or rather a counter, because we dont\n            # know the total in advance\n            pbar_id = 'check-siblings-{}'.format(id(ds))\n            log_progress(\n                lgr.info, pbar_id,\n                'Start checking pre-existing sibling configuration %s', ds,\n                label='Query siblings',\n                unit=' Siblings',\n            )\n            # even if we have to fail, let's report all conflicting siblings\n            # in subdatasets\n            failed = False\n            for r in ds.siblings(result_renderer=None,\n                                 recursive=recursive,\n                                 recursion_limit=recursion_limit):\n                log_progress(\n                    lgr.info, pbar_id,\n                    'Discovered sibling %s in dataset at %s',\n                    r['name'], r['path'],\n                    update=1,\n                    increment=True)\n                if not r['type'] == 'sibling' or r['status'] != 'ok':\n                    # this is an internal status query that has not consequence\n                    # for the outside world. Be silent unless something useful\n                    # can be said\n                    #yield r\n                    continue\n                if r['name'] == name:\n                    res = get_status_dict(\n                        status='error',\n                        message=\"a sibling '{}' is already configured in \"\n                        \"dataset {}\".format(name, r['path']),\n                        **res_kwargs,\n                    )\n                    failed = True\n                    yield res\n                    continue\n                if storage_name and r['name'] == storage_name:\n                    res = get_status_dict(\n                        status='error',\n                        message=\"a sibling '{}' is already configured in \"\n                        \"dataset {}\".format(storage_name, r['path']),\n                        **res_kwargs,\n                    )\n                    failed = True\n                    yield res\n                    continue\n            log_progress(\n                lgr.info, pbar_id,\n                'Finished checking pre-existing sibling configuration %s', ds,\n            )\n            if failed:\n                return\n\n        yield from _create_sibling_ria(\n            ds,\n            url,\n            name,\n            storage_sibling,\n            storage_name,\n            existing,\n            shared,\n            group,\n            post_update_hook,\n            trust_level,\n            res_kwargs)\n\n        if recursive:\n            # Note: subdatasets can be treated independently, so go full\n            # recursion when querying for them and _no_recursion with the\n            # actual call. Theoretically this can be parallelized.\n\n            for subds in ds.subdatasets(fulfilled=True,\n                                        recursive=True,\n                                        recursion_limit=recursion_limit,\n                                        result_xfm='datasets'):\n                yield from _create_sibling_ria(\n                    subds,\n                    url,\n                    name,\n                    storage_sibling,\n                    storage_name,\n                    existing,\n                    shared,\n                    group,\n                    post_update_hook,\n                    trust_level,\n                    res_kwargs)\n\n\ndef _create_sibling_ria(\n        ds,\n        url,\n        name,\n        storage_sibling,\n        storage_name,\n        existing,\n        shared,\n        group,\n        post_update_hook,\n        trust_level,\n        res_kwargs):\n    # be safe across datasets\n    res_kwargs = res_kwargs.copy()\n\n    # parse target URL\n    try:\n        ssh_host, base_path, rewritten_url = verify_ria_url(url, ds.config)\n    except ValueError as e:\n        yield get_status_dict(\n            status='error',\n            message=str(e),\n            **res_kwargs\n        )\n        return\n\n    base_path = Path(base_path)\n\n    git_url = decode_source_spec(\n        # append dataset id to url and use magic from clone-helper:\n        url + '#{}'.format(ds.id),\n        cfg=ds.config\n    )['giturl']\n    # determine layout locations; go for a v1 layout\n    repo_path, _, _ = get_layout_locations(1, base_path, ds.id)\n\n    ds_siblings = [r['name'] for r in ds.siblings(result_renderer=None)]\n    # Figure whether we are supposed to skip this very dataset\n    if existing == 'skip' and (\n            name in ds_siblings or (\n                storage_name and storage_name in ds_siblings)):\n        yield get_status_dict(\n            status='notneeded',\n            message=\"Skipped on existing sibling\",\n            **res_kwargs\n        )\n        # if we skip here, nothing else can change that decision further\n        # down\n        return\n\n    # figure whether we need to skip or error due an existing target repo before\n    # we try to init a special remote.\n    if ssh_host:\n        from datalad import ssh_manager\n        ssh = ssh_manager.get_connection(\n            ssh_host,\n            use_remote_annex_bundle=False)\n        ssh.open()\n\n    if existing in ['skip', 'error']:\n        config_path = repo_path / 'config'\n        # No .git -- if it's an existing repo in a RIA store it should be a\n        # bare repo.\n        # Theoretically we could have additional checks for whether we have\n        # an empty repo dir or a non-bare repo or whatever else.\n        if ssh_host:\n            try:\n                ssh('[ -e {p} ]'.format(p=quote_cmdlinearg(str(config_path))))\n                exists = True\n            except CommandError:\n                exists = False\n        else:\n            exists = config_path.exists()\n\n        if exists:\n            if existing == 'skip':\n                # 1. not rendered by default\n                # 2. message doesn't show up in ultimate result\n                #    record as shown by -f json_pp\n                yield get_status_dict(\n                    status='notneeded',\n                    message=\"Skipped on existing remote \"\n                            \"directory {}\".format(repo_path),\n                    **res_kwargs\n                )\n                return\n            else:  # existing == 'error'\n                yield get_status_dict(\n                    status='error',\n                    message=\"remote directory {} already \"\n                            \"exists.\".format(repo_path),\n                    **res_kwargs\n                )\n                return\n\n    lgr.info(\"create sibling{} '{}'{} ...\".format(\n        's' if storage_name else '',\n        name,\n        \" and '{}'\".format(storage_name) if storage_name else '',\n    ))\n    if storage_sibling:\n        lgr.debug('init special remote {}'.format(storage_name))\n        special_remote_options = [\n            'type=external',\n            'externaltype=ora',\n            'encryption=none',\n            'autoenable=true',\n            'url={}'.format(url)]\n        try:\n            ds.repo.init_remote(\n                storage_name,\n                options=special_remote_options)\n        except CommandError as e:\n            if existing == 'reconfigure' \\\n                    and 'git-annex: There is already a special remote' \\\n                    in e.stderr:\n                # run enableremote instead\n                lgr.debug(\n                    \"special remote '%s' already exists. \"\n                    \"Run enableremote instead.\",\n                    storage_name)\n                # TODO: Use AnnexRepo.enable_remote (which needs to get\n                #       `options` first)\n                cmd = [\n                    'git',\n                    'annex',\n                    'enableremote',\n                    storage_name] + special_remote_options\n                subprocess.run(cmd, cwd=quote_cmdlinearg(ds.repo.path))\n            else:\n                yield get_status_dict(\n                    status='error',\n                    message=\"initremote failed.\\nstdout: %s\\nstderr: %s\"\n                    % (e.stdout, e.stderr),\n                    **res_kwargs\n                )\n                return\n\n        # 1. create remote object store:\n        # Note: All it actually takes is to trigger the special\n        # remote's `prepare` method once.\n        # ATM trying to achieve that by invoking a minimal fsck.\n        # TODO: - It's probably faster to actually talk to the special\n        #         remote (i.e. pretending to be annex and use\n        #         the protocol to send PREPARE)\n        #       - Alternatively we can create the remote directory and\n        #         ria version file directly, but this means\n        #         code duplication that then needs to be kept in sync\n        #         with ria-remote implementation.\n        #       - this leads to the third option: Have that creation\n        #         routine importable and callable from\n        #         ria-remote package without the need to actually\n        #         instantiate a RIARemote object\n        lgr.debug(\"initializing object store\")\n        ds.repo.fsck(\n            remote=storage_name,\n            fast=True,\n            annex_options=['--exclude=*/*'])\n\n        if trust_level:\n            ds.repo.call_git(['annex', trust_level, storage_name])\n        # get uuid for use in bare repo's config\n        uuid = ds.config.get(\"remote.{}.annex-uuid\".format(storage_name))\n\n    else:\n        # with no special remote we currently need to create the\n        # required directories\n        # TODO: This should be cleaner once we have access to the\n        #       special remote's RemoteIO classes without\n        #       talking via annex\n        if ssh_host:\n            ssh('mkdir -p {}'.format(quote_cmdlinearg(str(repo_path))))\n        else:\n            repo_path.mkdir(parents=True)\n\n    # 2. create a bare repository in-store:\n\n    lgr.debug(\"init bare repository\")\n    # TODO: we should prob. check whether it's there already. How?\n    # Note: like the special remote itself, we assume local FS if no\n    # SSH host is specified\n    disabled_hook = repo_path / 'hooks' / 'post-update.sample'\n    enabled_hook = repo_path / 'hooks' / 'post-update'\n\n    if group:\n        chgrp_cmd = \"chgrp -R {} {}\".format(\n            quote_cmdlinearg(str(group)),\n            quote_cmdlinearg(str(repo_path)))\n\n    if ssh_host:\n        ssh('cd {rootdir} && git init --bare{shared}'.format(\n            rootdir=quote_cmdlinearg(str(repo_path)),\n            shared=\" --shared='{}'\".format(\n                quote_cmdlinearg(shared)) if shared else ''\n        ))\n\n        if storage_sibling:\n            # write special remote's uuid into git-config, so clone can\n            # which one it is supposed to be and enable it even with\n            # fallback URL\n            ssh(\"cd {rootdir} && git config datalad.ora-remote.uuid {uuid}\"\n                \"\".format(rootdir=quote_cmdlinearg(str(repo_path)),\n                          uuid=uuid))\n\n        if post_update_hook:\n            ssh('mv {} {}'.format(quote_cmdlinearg(str(disabled_hook)),\n                                  quote_cmdlinearg(str(enabled_hook))))\n\n        if group:\n            # Either repository existed before or a new directory was\n            # created for it, set its group to a desired one if was\n            # provided with the same chgrp\n            ssh(chgrp_cmd)\n    else:\n        gr = GitRepo(repo_path, create=True, bare=True,\n                     shared=\" --shared='{}'\".format(quote_cmdlinearg(shared))\n                     if shared else None)\n        if storage_sibling:\n            # write special remote's uuid into git-config, so clone can\n            # which one it is supposed to be and enable it even with\n            # fallback URL\n            gr.config.add(\"datalad.ora-remote.uuid\", uuid, where='local')\n\n        if post_update_hook:\n            disabled_hook.rename(enabled_hook)\n        if group:\n            # TODO; do we need a cwd here?\n            subprocess.run(chgrp_cmd, cwd=quote_cmdlinearg(ds.path))\n\n    # add a git remote to the bare repository\n    # Note: needs annex-ignore! Otherwise we might push into dirhash\n    # lower annex/object tree instead of mixed, since it's a bare\n    # repo. This in turn would be an issue, if we want to pack the\n    # entire thing into an archive. Special remote will then not be\n    # able to access content in the \"wrong\" place within the archive\n    lgr.debug(\"set up git remote\")\n    if name in ds_siblings:\n        # otherwise we should have skipped or failed before\n        assert existing == 'reconfigure'\n    ds.config.set(\n        \"remote.{}.annex-ignore\".format(name),\n        value=\"true\",\n        where=\"local\")\n    ds.siblings(\n        'configure',\n        name=name,\n        url=git_url\n        if ssh_host\n        else str(repo_path),\n        recursive=False,\n        # Note, that this should be None if storage_sibling was not set\n        publish_depends=storage_name,\n        result_renderer=None,\n        # Note, that otherwise a subsequent publish will report\n        # \"notneeded\".\n        fetch=True\n    )\n\n    yield get_status_dict(\n        status='ok',\n        **res_kwargs,\n    )\n",
            "new_file_content": "# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-\n# ex: set sts=4 ts=4 sw=4 noet:\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n#   See COPYING file distributed along with the datalad package for the\n#   copyright and license terms.\n#\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n\"\"\"Create a sibling in a RIA store\"\"\"\n\n__docformat__ = 'restructuredtext'\n\n\nimport logging\nimport subprocess\n\nfrom datalad.interface.common_opts import (\n    recursion_flag,\n    recursion_limit\n)\nfrom datalad.interface.base import (\n    build_doc,\n    Interface,\n)\nfrom datalad.interface.results import (\n    get_status_dict,\n)\nfrom datalad.interface.utils import eval_results\nfrom datalad.support.param import Parameter\nfrom datalad.support.constraints import (\n    EnsureBool,\n    EnsureChoice,\n    EnsureNone,\n    EnsureStr,\n)\nfrom datalad.distribution.dataset import (\n    datasetmethod,\n    EnsureDataset,\n    require_dataset,\n)\nfrom datalad.utils import (\n    Path,\n    quote_cmdlinearg,\n)\nfrom datalad.support.exceptions import (\n    CommandError\n)\nfrom datalad.support.gitrepo import (\n    GitRepo\n)\nfrom datalad.core.distributed.clone import (\n    decode_source_spec\n)\nfrom datalad.log import log_progress\nfrom datalad.distributed.ria_utils import (\n    get_layout_locations,\n    verify_ria_url,\n)\n\nlgr = logging.getLogger('datalad.distributed.create_sibling_ria')\n\n\n@build_doc\nclass CreateSiblingRia(Interface):\n    \"\"\"Creates a sibling to a dataset in a RIA store\n\n    Communication with a dataset in a RIA store is implemented via two\n    siblings. A regular Git remote (repository sibling) and a git-annex\n    special remote for data transfer (storage sibling) -- with the former\n    having a publication dependency on the latter. By default, the name of the\n    storage sibling is derived from the repository sibling's name by appending\n    \"-storage\".\n\n    The store's base path is expected to not exist, be an empty directory,\n    or a valid RIA store.\n\n    RIA store layout\n    ~~~~~~~~~~~~~~~~\n\n    A RIA store is a directory tree with a dedicated subdirectory for each\n    dataset in the store. The subdirectory name is constructed from the\n    DataLad dataset ID, e.g. '124/68afe-59ec-11ea-93d7-f0d5bf7b5561', where\n    the first three characters of the ID are used for an intermediate\n    subdirectory in order to mitigate files system limitations for stores\n    containing a large number of datasets.\n\n    Each dataset subdirectory contains a standard bare Git repository for\n    the dataset.\n\n    In addition, a subdirectory 'annex' hold a standard Git-annex object\n    store. However, instead of using the 'dirhashlower' naming scheme for\n    the object directories, like Git-annex would do, a 'dirhashmixed'\n    layout is used -- the same as for non-bare Git repositories or regular\n    DataLad datasets.\n\n    Optionally, there can be a further subdirectory 'archives' with\n    (compressed) 7z archives of annex objects. The storage remote is able to\n    pull annex objects from these archives, if it cannot find in the regular\n    annex object store. This feature can be useful for storing large\n    collections of rarely changing data on systems that limit the number of\n    files that can be stored.\n\n    Each dataset directory also contains a 'ria-layout-version' file that\n    identifies the data organization (as, for example, described above).\n\n    Lastly, there is a global 'ria-layout-version' file at the store's\n    base path that identifies where dataset subdirectories themselves are\n    located. At present, this file must contain a single line stating the\n    version (currently \"1\"). This line MUST end with a newline character.\n\n    It is possible to define an alias for an individual dataset in a store by\n    placing a symlink to the dataset location into an 'alias/' directory\n    in the root of the store. This enables dataset access via URLs of format:\n    'ria+<protocol>://<storelocation>#~<aliasname>'.\n\n    Error logging\n    ~~~~~~~~~~~~~\n\n    To enable error logging at the remote end, append a pipe symbol and an \"l\"\n    to the version number in ria-layout-version (like so '1|l\\\\n').\n\n    Error logging will create files in an \"error_log\" directory whenever the\n    git-annex special remote (storage sibling) raises an exception, storing the\n    Python traceback of it. The logfiles are named according to the scheme\n    '<dataset id>.<annex uuid of the remote>.log' showing \"who\" ran into this\n    issue with which dataset. Because logging can potentially leak personal\n    data (like local file paths for example), it can be disabled client-side\n    by setting the configuration variable\n    \"annex.ora-remote.<storage-sibling-name>.ignore-remote-config\".\n    \"\"\"\n\n    # TODO: description?\n    _params_ = dict(\n        dataset=Parameter(\n            args=(\"-d\", \"--dataset\"),\n            doc=\"\"\"specify the dataset to process.  If\n            no dataset is given, an attempt is made to identify the dataset\n            based on the current working directory\"\"\",\n            constraints=EnsureDataset() | EnsureNone()),\n        url=Parameter(\n            args=(\"url\",),\n            metavar=\"ria+<ssh|file>://<host>[/path]\",\n            doc=\"\"\"URL identifying the target RIA store and access protocol.\n            \"\"\",\n            constraints=EnsureStr() | EnsureNone()),\n        name=Parameter(\n            args=('-s', '--name',),\n            metavar='NAME',\n            doc=\"\"\"Name of the sibling.\n            With `recursive`, the same name will be used to label all\n            the subdatasets' siblings.\"\"\",\n            constraints=EnsureStr() | EnsureNone(),\n            required=True),\n        storage_name=Parameter(\n            args=(\"--storage-name\",),\n            metavar=\"NAME\",\n            doc=\"\"\"Name of the storage sibling (git-annex special remote).\n            Must not be identical to the sibling name. If not specified,\n            defaults to the sibling name plus '-storage' suffix.\"\"\",\n            constraints=EnsureStr() | EnsureNone()),\n        post_update_hook=Parameter(\n            args=(\"--post-update-hook\",),\n            doc=\"\"\"Enable git's default post-update-hook for the created\n            sibling.\"\"\",\n            action=\"store_true\"),\n        shared=Parameter(\n            args=(\"--shared\",),\n            metavar='{false|true|umask|group|all|world|everybody|0xxx}',\n            doc=\"\"\"If given, configures the permissions in the\n            RIA store for multi-users access.\n            Possible values for this option are identical to those of\n            `git init --shared` and are described in its documentation.\"\"\",\n            constraints=EnsureStr() | EnsureBool() | EnsureNone()),\n        group=Parameter(\n            args=(\"--group\",),\n            metavar=\"GROUP\",\n            doc=\"\"\"Filesystem group for the repository. Specifying the group is\n            crucial when [CMD: --shared=group CMD][PY: shared=\"group\" PY]\"\"\",\n            constraints=EnsureStr() | EnsureNone()),\n        storage_sibling=Parameter(\n            args=(\"--no-storage-sibling\",),\n            dest='storage_sibling',\n            doc=\"\"\"Flag to disable establishing a storage sibling.\"\"\",\n            action=\"store_false\"),\n        existing=Parameter(\n            args=(\"--existing\",),\n            constraints=EnsureChoice(\n                'skip', 'error', 'reconfigure') | EnsureNone(),\n            metavar='MODE',\n            doc=\"\"\"Action to perform, if a (storage) sibling is already\n            configured under the given name and/or a target already exists.\n            In this case, a dataset can be skipped ('skip'), an existing target\n            repository be forcefully re-initialized, and the sibling\n            (re-)configured ('reconfigure'), or the command be instructed to\n            fail ('error').\"\"\", ),\n        recursive=recursion_flag,\n        recursion_limit=recursion_limit,\n        trust_level=Parameter(\n            args=(\"--trust-level\",),\n            metavar=\"TRUST-LEVEL\",\n            constraints=EnsureChoice(\n                'trust', 'semitrust', 'untrust') | EnsureNone(),\n            doc=\"\"\"specify a trust level for the storage sibling. If not\n            specified, the default git-annex trust level is used.\"\"\",),\n    )\n\n    @staticmethod\n    @datasetmethod(name='create_sibling_ria')\n    @eval_results\n    def __call__(url,\n                 name,\n                 dataset=None,\n                 storage_name=None,\n                 post_update_hook=False,\n                 shared=None,\n                 group=None,\n                 storage_sibling=True,\n                 existing='error',\n                 trust_level=None,\n                 recursive=False,\n                 recursion_limit=None\n                 ):\n\n        ds = require_dataset(\n            dataset, check_installed=True, purpose='create sibling RIA')\n        res_kwargs = dict(\n            ds=ds,\n            action=\"create-sibling-ria\",\n            logger=lgr,\n        )\n\n        if ds.repo.get_hexsha() is None or ds.id is None:\n            raise RuntimeError(\n                \"Repository at {} is not a DataLad dataset, \"\n                \"run 'datalad create [--force]' first.\".format(ds.path))\n\n        if not storage_sibling and storage_name:\n            lgr.warning(\n                \"Storage sibling setup disabled, but a storage sibling name \"\n                \"was provided\"\n            )\n\n        if storage_sibling and not storage_name:\n            storage_name = \"{}-storage\".format(name)\n\n        if storage_sibling and name == storage_name:\n            # leads to unresolvable, circular dependency with publish-depends\n            raise ValueError(\"sibling names must not be equal\")\n\n        if not isinstance(url, str):\n            raise TypeError(\"url is not a string, but %s\" % type(url))\n\n        # Query existing siblings upfront in order to fail early on\n        # existing=='error', since misconfiguration (particularly of special\n        # remotes) only to fail in a subdataset later on with that config, can\n        # be quite painful.\n        # TODO: messages - this is \"create-sibling\". Don't confuse existence of\n        #       local remotes with existence of the actual remote sibling\n        #       in wording\n        if existing == 'error':\n            # in recursive mode this check could take a substantial amount of\n            # time: employ a progress bar (or rather a counter, because we dont\n            # know the total in advance\n            pbar_id = 'check-siblings-{}'.format(id(ds))\n            log_progress(\n                lgr.info, pbar_id,\n                'Start checking pre-existing sibling configuration %s', ds,\n                label='Query siblings',\n                unit=' Siblings',\n            )\n            # even if we have to fail, let's report all conflicting siblings\n            # in subdatasets\n            failed = False\n            for r in ds.siblings(result_renderer=None,\n                                 recursive=recursive,\n                                 recursion_limit=recursion_limit):\n                log_progress(\n                    lgr.info, pbar_id,\n                    'Discovered sibling %s in dataset at %s',\n                    r['name'], r['path'],\n                    update=1,\n                    increment=True)\n                if not r['type'] == 'sibling' or r['status'] != 'ok':\n                    # this is an internal status query that has not consequence\n                    # for the outside world. Be silent unless something useful\n                    # can be said\n                    #yield r\n                    continue\n                if r['name'] == name:\n                    res = get_status_dict(\n                        status='error',\n                        message=\"a sibling '{}' is already configured in \"\n                        \"dataset {}\".format(name, r['path']),\n                        **res_kwargs,\n                    )\n                    failed = True\n                    yield res\n                    continue\n                if storage_name and r['name'] == storage_name:\n                    res = get_status_dict(\n                        status='error',\n                        message=\"a sibling '{}' is already configured in \"\n                        \"dataset {}\".format(storage_name, r['path']),\n                        **res_kwargs,\n                    )\n                    failed = True\n                    yield res\n                    continue\n            log_progress(\n                lgr.info, pbar_id,\n                'Finished checking pre-existing sibling configuration %s', ds,\n            )\n            if failed:\n                return\n\n        yield from _create_sibling_ria(\n            ds,\n            url,\n            name,\n            storage_sibling,\n            storage_name,\n            existing,\n            shared,\n            group,\n            post_update_hook,\n            trust_level,\n            res_kwargs)\n\n        if recursive:\n            # Note: subdatasets can be treated independently, so go full\n            # recursion when querying for them and _no_recursion with the\n            # actual call. Theoretically this can be parallelized.\n\n            for subds in ds.subdatasets(fulfilled=True,\n                                        recursive=True,\n                                        recursion_limit=recursion_limit,\n                                        result_xfm='datasets'):\n                yield from _create_sibling_ria(\n                    subds,\n                    url,\n                    name,\n                    storage_sibling,\n                    storage_name,\n                    existing,\n                    shared,\n                    group,\n                    post_update_hook,\n                    trust_level,\n                    res_kwargs)\n\n\ndef _create_sibling_ria(\n        ds,\n        url,\n        name,\n        storage_sibling,\n        storage_name,\n        existing,\n        shared,\n        group,\n        post_update_hook,\n        trust_level,\n        res_kwargs):\n    # be safe across datasets\n    res_kwargs = res_kwargs.copy()\n\n    # parse target URL\n    try:\n        ssh_host, base_path, rewritten_url = verify_ria_url(url, ds.config)\n    except ValueError as e:\n        yield get_status_dict(\n            status='error',\n            message=str(e),\n            **res_kwargs\n        )\n        return\n\n    base_path = Path(base_path)\n\n    git_url = decode_source_spec(\n        # append dataset id to url and use magic from clone-helper:\n        url + '#{}'.format(ds.id),\n        cfg=ds.config\n    )['giturl']\n    # determine layout locations; go for a v1 layout\n    repo_path, _, _ = get_layout_locations(1, base_path, ds.id)\n\n    ds_siblings = [r['name'] for r in ds.siblings(result_renderer=None)]\n    # Figure whether we are supposed to skip this very dataset\n    if existing == 'skip' and (\n            name in ds_siblings or (\n                storage_name and storage_name in ds_siblings)):\n        yield get_status_dict(\n            status='notneeded',\n            message=\"Skipped on existing sibling\",\n            **res_kwargs\n        )\n        # if we skip here, nothing else can change that decision further\n        # down\n        return\n\n    # figure whether we need to skip or error due an existing target repo before\n    # we try to init a special remote.\n    if ssh_host:\n        from datalad import ssh_manager\n        ssh = ssh_manager.get_connection(\n            ssh_host,\n            use_remote_annex_bundle=False)\n        ssh.open()\n\n    if existing in ['skip', 'error']:\n        config_path = repo_path / 'config'\n        # No .git -- if it's an existing repo in a RIA store it should be a\n        # bare repo.\n        # Theoretically we could have additional checks for whether we have\n        # an empty repo dir or a non-bare repo or whatever else.\n        if ssh_host:\n            try:\n                ssh('[ -e {p} ]'.format(p=quote_cmdlinearg(str(config_path))))\n                exists = True\n            except CommandError:\n                exists = False\n        else:\n            exists = config_path.exists()\n\n        if exists:\n            if existing == 'skip':\n                # 1. not rendered by default\n                # 2. message doesn't show up in ultimate result\n                #    record as shown by -f json_pp\n                yield get_status_dict(\n                    status='notneeded',\n                    message=\"Skipped on existing remote \"\n                            \"directory {}\".format(repo_path),\n                    **res_kwargs\n                )\n                return\n            else:  # existing == 'error'\n                yield get_status_dict(\n                    status='error',\n                    message=\"remote directory {} already \"\n                            \"exists.\".format(repo_path),\n                    **res_kwargs\n                )\n                return\n\n    lgr.info(\"create sibling{} '{}'{} ...\".format(\n        's' if storage_name else '',\n        name,\n        \" and '{}'\".format(storage_name) if storage_name else '',\n    ))\n    if storage_sibling:\n        lgr.debug('init special remote {}'.format(storage_name))\n        special_remote_options = [\n            'type=external',\n            'externaltype=ora',\n            'encryption=none',\n            'autoenable=true',\n            'url={}'.format(url)]\n        try:\n            ds.repo.init_remote(\n                storage_name,\n                options=special_remote_options)\n        except CommandError as e:\n            if existing == 'reconfigure' \\\n                    and 'git-annex: There is already a special remote' \\\n                    in e.stderr:\n                # run enableremote instead\n                lgr.debug(\n                    \"special remote '%s' already exists. \"\n                    \"Run enableremote instead.\",\n                    storage_name)\n                # TODO: Use AnnexRepo.enable_remote (which needs to get\n                #       `options` first)\n                cmd = [\n                    'git',\n                    'annex',\n                    'enableremote',\n                    storage_name] + special_remote_options\n                subprocess.run(cmd, cwd=quote_cmdlinearg(ds.repo.path))\n            else:\n                yield get_status_dict(\n                    status='error',\n                    message=\"initremote failed.\\nstdout: %s\\nstderr: %s\"\n                    % (e.stdout, e.stderr),\n                    **res_kwargs\n                )\n                return\n\n        # 1. create remote object store:\n        # Note: All it actually takes is to trigger the special\n        # remote's `prepare` method once.\n        # ATM trying to achieve that by invoking a minimal fsck.\n        # TODO: - It's probably faster to actually talk to the special\n        #         remote (i.e. pretending to be annex and use\n        #         the protocol to send PREPARE)\n        #       - Alternatively we can create the remote directory and\n        #         ria version file directly, but this means\n        #         code duplication that then needs to be kept in sync\n        #         with ria-remote implementation.\n        #       - this leads to the third option: Have that creation\n        #         routine importable and callable from\n        #         ria-remote package without the need to actually\n        #         instantiate a RIARemote object\n        lgr.debug(\"initializing object store\")\n        ds.repo.fsck(\n            remote=storage_name,\n            fast=True,\n            annex_options=['--exclude=*/*'])\n\n        if trust_level:\n            ds.repo.call_git(['annex', trust_level, storage_name])\n        # get uuid for use in bare repo's config\n        uuid = ds.config.get(\"remote.{}.annex-uuid\".format(storage_name))\n\n    else:\n        # with no special remote we currently need to create the\n        # required directories\n        # TODO: This should be cleaner once we have access to the\n        #       special remote's RemoteIO classes without\n        #       talking via annex\n        if ssh_host:\n            ssh('mkdir -p {}'.format(quote_cmdlinearg(str(repo_path))))\n        else:\n            repo_path.mkdir(parents=True)\n\n    # 2. create a bare repository in-store:\n\n    lgr.debug(\"init bare repository\")\n    # TODO: we should prob. check whether it's there already. How?\n    # Note: like the special remote itself, we assume local FS if no\n    # SSH host is specified\n    disabled_hook = repo_path / 'hooks' / 'post-update.sample'\n    enabled_hook = repo_path / 'hooks' / 'post-update'\n\n    if group:\n        chgrp_cmd = \"chgrp -R {} {}\".format(\n            quote_cmdlinearg(str(group)),\n            quote_cmdlinearg(str(repo_path)))\n\n    if ssh_host:\n        ssh('cd {rootdir} && git init --bare{shared}'.format(\n            rootdir=quote_cmdlinearg(str(repo_path)),\n            shared=\" --shared='{}'\".format(\n                quote_cmdlinearg(shared)) if shared else ''\n        ))\n\n        if storage_sibling:\n            # write special remote's uuid into git-config, so clone can\n            # which one it is supposed to be and enable it even with\n            # fallback URL\n            ssh(\"cd {rootdir} && git config datalad.ora-remote.uuid {uuid}\"\n                \"\".format(rootdir=quote_cmdlinearg(str(repo_path)),\n                          uuid=uuid))\n\n        if post_update_hook:\n            ssh('mv {} {}'.format(quote_cmdlinearg(str(disabled_hook)),\n                                  quote_cmdlinearg(str(enabled_hook))))\n\n        if group:\n            # Either repository existed before or a new directory was\n            # created for it, set its group to a desired one if was\n            # provided with the same chgrp\n            ssh(chgrp_cmd)\n    else:\n        gr = GitRepo(repo_path, create=True, bare=True,\n                     shared=\" --shared='{}'\".format(quote_cmdlinearg(shared))\n                     if shared else None)\n        if storage_sibling:\n            # write special remote's uuid into git-config, so clone can\n            # which one it is supposed to be and enable it even with\n            # fallback URL\n            gr.config.add(\"datalad.ora-remote.uuid\", uuid, where='local')\n\n        if post_update_hook:\n            disabled_hook.rename(enabled_hook)\n        if group:\n            # TODO; do we need a cwd here?\n            subprocess.run(chgrp_cmd, cwd=quote_cmdlinearg(ds.path))\n\n    # add a git remote to the bare repository\n    # Note: needs annex-ignore! Otherwise we might push into dirhash\n    # lower annex/object tree instead of mixed, since it's a bare\n    # repo. This in turn would be an issue, if we want to pack the\n    # entire thing into an archive. Special remote will then not be\n    # able to access content in the \"wrong\" place within the archive\n    lgr.debug(\"set up git remote\")\n    if name in ds_siblings:\n        # otherwise we should have skipped or failed before\n        assert existing == 'reconfigure'\n    ds.config.set(\n        \"remote.{}.annex-ignore\".format(name),\n        value=\"true\",\n        where=\"local\")\n    ds.siblings(\n        'configure',\n        name=name,\n        url=git_url\n        if ssh_host\n        else str(repo_path),\n        recursive=False,\n        # Note, that this should be None if storage_sibling was not set\n        publish_depends=storage_name,\n        result_renderer=None,\n        # Note, that otherwise a subsequent publish will report\n        # \"notneeded\".\n        fetch=True\n    )\n\n    yield get_status_dict(\n        status='ok',\n        **res_kwargs,\n    )\n",
            "header": {
                "file": {
                    "path": "datalad/distributed/create_sibling_ria.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "a9ae43afd",
                "new_commit_hash": "b4d49e682",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/datalad/distributed/create_sibling_ria.py"
            },
            "plus_file": {
                "path": "b/datalad/distributed/create_sibling_ria.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 108,
                            "length": 6
                        },
                        "new_range": {
                            "start": 108,
                            "length": 11
                        },
                        "section": "class CreateSiblingRia(Interface):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    located. At present, this file must contain a single line stating the",
                                "type": "context"
                            },
                            {
                                "content": "    version (currently \"1\"). This line MUST end with a newline character.",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    It is possible to define an alias for an individual dataset in a store by",
                                "type": "added"
                            },
                            {
                                "content": "    placing a symlink to the dataset location into an 'alias/' directory",
                                "type": "added"
                            },
                            {
                                "content": "    in the root of the store. This enables dataset access via URLs of format:",
                                "type": "added"
                            },
                            {
                                "content": "    'ria+<protocol>://<storelocation>#~<aliasname>'.",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    Error logging",
                                "type": "context"
                            },
                            {
                                "content": "    ~~~~~~~~~~~~~",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "datalad/distributed/create_sibling_ria.py",
                            "type": "class",
                            "name": "CreateSiblingRia",
                            "content": "class CreateSiblingRia(Interface):\n    \"\"\"Creates a sibling to a dataset in a RIA store\n\n    Communication with a dataset in a RIA store is implemented via two\n    siblings. A regular Git remote (repository sibling) and a git-annex\n    special remote for data transfer (storage sibling) -- with the former\n    having a publication dependency on the latter. By default, the name of the\n    storage sibling is derived from the repository sibling's name by appending\n    \"-storage\".\n\n    The store's base path is expected to not exist, be an empty directory,\n    or a valid RIA store.\n\n    RIA store layout\n    ~~~~~~~~~~~~~~~~\n\n    A RIA store is a directory tree with a dedicated subdirectory for each\n    dataset in the store. The subdirectory name is constructed from the\n    DataLad dataset ID, e.g. '124/68afe-59ec-11ea-93d7-f0d5bf7b5561', where\n    the first three characters of the ID are used for an intermediate\n    subdirectory in order to mitigate files system limitations for stores\n    containing a large number of datasets.\n\n    Each dataset subdirectory contains a standard bare Git repository for\n    the dataset.\n\n    In addition, a subdirectory 'annex' hold a standard Git-annex object\n    store. However, instead of using the 'dirhashlower' naming scheme for\n    the object directories, like Git-annex would do, a 'dirhashmixed'\n    layout is used -- the same as for non-bare Git repositories or regular\n    DataLad datasets.\n\n    Optionally, there can be a further subdirectory 'archives' with\n    (compressed) 7z archives of annex objects. The storage remote is able to\n    pull annex objects from these archives, if it cannot find in the regular\n    annex object store. This feature can be useful for storing large\n    collections of rarely changing data on systems that limit the number of\n    files that can be stored.\n\n    Each dataset directory also contains a 'ria-layout-version' file that\n    identifies the data organization (as, for example, described above).\n\n    Lastly, there is a global 'ria-layout-version' file at the store's\n    base path that identifies where dataset subdirectories themselves are\n    located. At present, this file must contain a single line stating the\n    version (currently \"1\"). This line MUST end with a newline character.\n\n    It is possible to define an alias for an individual dataset in a store by\n    placing a symlink to the dataset location into an 'alias/' directory\n    in the root of the store. This enables dataset access via URLs of format:\n    'ria+<protocol>://<storelocation>#~<aliasname>'.\n\n    Error logging\n    ~~~~~~~~~~~~~\n\n    To enable error logging at the remote end, append a pipe symbol and an \"l\"\n    to the version number in ria-layout-version (like so '1|l\\\\n').\n\n    Error logging will create files in an \"error_log\" directory whenever the\n    git-annex special remote (storage sibling) raises an exception, storing the\n    Python traceback of it. The logfiles are named according to the scheme\n    '<dataset id>.<annex uuid of the remote>.log' showing \"who\" ran into this\n    issue with which dataset. Because logging can potentially leak personal\n    data (like local file paths for example), it can be disabled client-side\n    by setting the configuration variable\n    \"annex.ora-remote.<storage-sibling-name>.ignore-remote-config\".\n    \"\"\"\n\n    # TODO: description?\n    _params_ = dict(\n        dataset=Parameter(\n            args=(\"-d\", \"--dataset\"),\n            doc=\"\"\"specify the dataset to process.  If\n            no dataset is given, an attempt is made to identify the dataset\n            based on the current working directory\"\"\",\n            constraints=EnsureDataset() | EnsureNone()),\n        url=Parameter(\n            args=(\"url\",),\n            metavar=\"ria+<ssh|file>://<host>[/path]\",\n            doc=\"\"\"URL identifying the target RIA store and access protocol.\n            \"\"\",\n            constraints=EnsureStr() | EnsureNone()),\n        name=Parameter(\n            args=('-s', '--name',),\n            metavar='NAME',\n            doc=\"\"\"Name of the sibling.\n            With `recursive`, the same name will be used to label all\n            the subdatasets' siblings.\"\"\",\n            constraints=EnsureStr() | EnsureNone(),\n            required=True),\n        storage_name=Parameter(\n            args=(\"--storage-name\",),\n            metavar=\"NAME\",\n            doc=\"\"\"Name of the storage sibling (git-annex special remote).\n            Must not be identical to the sibling name. If not specified,\n            defaults to the sibling name plus '-storage' suffix.\"\"\",\n            constraints=EnsureStr() | EnsureNone()),\n        post_update_hook=Parameter(\n            args=(\"--post-update-hook\",),\n            doc=\"\"\"Enable git's default post-update-hook for the created\n            sibling.\"\"\",\n            action=\"store_true\"),\n        shared=Parameter(\n            args=(\"--shared\",),\n            metavar='{false|true|umask|group|all|world|everybody|0xxx}',\n            doc=\"\"\"If given, configures the permissions in the\n            RIA store for multi-users access.\n            Possible values for this option are identical to those of\n            `git init --shared` and are described in its documentation.\"\"\",\n            constraints=EnsureStr() | EnsureBool() | EnsureNone()),\n        group=Parameter(\n            args=(\"--group\",),\n            metavar=\"GROUP\",\n            doc=\"\"\"Filesystem group for the repository. Specifying the group is\n            crucial when [CMD: --shared=group CMD][PY: shared=\"group\" PY]\"\"\",\n            constraints=EnsureStr() | EnsureNone()),\n        storage_sibling=Parameter(\n            args=(\"--no-storage-sibling\",),\n            dest='storage_sibling',\n            doc=\"\"\"Flag to disable establishing a storage sibling.\"\"\",\n            action=\"store_false\"),\n        existing=Parameter(\n            args=(\"--existing\",),\n            constraints=EnsureChoice(\n                'skip', 'error', 'reconfigure') | EnsureNone(),\n            metavar='MODE',\n            doc=\"\"\"Action to perform, if a (storage) sibling is already\n            configured under the given name and/or a target already exists.\n            In this case, a dataset can be skipped ('skip'), an existing target\n            repository be forcefully re-initialized, and the sibling\n            (re-)configured ('reconfigure'), or the command be instructed to\n            fail ('error').\"\"\", ),\n        recursive=recursion_flag,\n        recursion_limit=recursion_limit,\n        trust_level=Parameter(\n            args=(\"--trust-level\",),\n            metavar=\"TRUST-LEVEL\",\n            constraints=EnsureChoice(\n                'trust', 'semitrust', 'untrust') | EnsureNone(),\n            doc=\"\"\"specify a trust level for the storage sibling. If not\n            specified, the default git-annex trust level is used.\"\"\",),\n    )\n\n    @staticmethod\n    @datasetmethod(name='create_sibling_ria')\n    @eval_results\n    def __call__(url,\n                 name,\n                 dataset=None,\n                 storage_name=None,\n                 post_update_hook=False,\n                 shared=None,\n                 group=None,\n                 storage_sibling=True,\n                 existing='error',\n                 trust_level=None,\n                 recursive=False,\n                 recursion_limit=None\n                 ):\n\n        ds = require_dataset(\n            dataset, check_installed=True, purpose='create sibling RIA')\n        res_kwargs = dict(\n            ds=ds,\n            action=\"create-sibling-ria\",\n            logger=lgr,\n        )\n\n        if ds.repo.get_hexsha() is None or ds.id is None:\n            raise RuntimeError(\n                \"Repository at {} is not a DataLad dataset, \"\n                \"run 'datalad create [--force]' first.\".format(ds.path))\n\n        if not storage_sibling and storage_name:\n            lgr.warning(\n                \"Storage sibling setup disabled, but a storage sibling name \"\n                \"was provided\"\n            )\n\n        if storage_sibling and not storage_name:\n            storage_name = \"{}-storage\".format(name)\n\n        if storage_sibling and name == storage_name:\n            # leads to unresolvable, circular dependency with publish-depends\n            raise ValueError(\"sibling names must not be equal\")\n\n        if not isinstance(url, str):\n            raise TypeError(\"url is not a string, but %s\" % type(url))\n\n        # Query existing siblings upfront in order to fail early on\n        # existing=='error', since misconfiguration (particularly of special\n        # remotes) only to fail in a subdataset later on with that config, can\n        # be quite painful.\n        # TODO: messages - this is \"create-sibling\". Don't confuse existence of\n        #       local remotes with existence of the actual remote sibling\n        #       in wording\n        if existing == 'error':\n            # in recursive mode this check could take a substantial amount of\n            # time: employ a progress bar (or rather a counter, because we dont\n            # know the total in advance\n            pbar_id = 'check-siblings-{}'.format(id(ds))\n            log_progress(\n                lgr.info, pbar_id,\n                'Start checking pre-existing sibling configuration %s', ds,\n                label='Query siblings',\n                unit=' Siblings',\n            )\n            # even if we have to fail, let's report all conflicting siblings\n            # in subdatasets\n            failed = False\n            for r in ds.siblings(result_renderer=None,\n                                 recursive=recursive,\n                                 recursion_limit=recursion_limit):\n                log_progress(\n                    lgr.info, pbar_id,\n                    'Discovered sibling %s in dataset at %s',\n                    r['name'], r['path'],\n                    update=1,\n                    increment=True)\n                if not r['type'] == 'sibling' or r['status'] != 'ok':\n                    # this is an internal status query that has not consequence\n                    # for the outside world. Be silent unless something useful\n                    # can be said\n                    #yield r\n                    continue\n                if r['name'] == name:\n                    res = get_status_dict(\n                        status='error',\n                        message=\"a sibling '{}' is already configured in \"\n                        \"dataset {}\".format(name, r['path']),\n                        **res_kwargs,\n                    )\n                    failed = True\n                    yield res\n                    continue\n                if storage_name and r['name'] == storage_name:\n                    res = get_status_dict(\n                        status='error',\n                        message=\"a sibling '{}' is already configured in \"\n                        \"dataset {}\".format(storage_name, r['path']),\n                        **res_kwargs,\n                    )\n                    failed = True\n                    yield res\n                    continue\n            log_progress(\n                lgr.info, pbar_id,\n                'Finished checking pre-existing sibling configuration %s', ds,\n            )\n            if failed:\n                return\n\n        yield from _create_sibling_ria(\n            ds,\n            url,\n            name,\n            storage_sibling,\n            storage_name,\n            existing,\n            shared,\n            group,\n            post_update_hook,\n            trust_level,\n            res_kwargs)\n\n        if recursive:\n            # Note: subdatasets can be treated independently, so go full\n            # recursion when querying for them and _no_recursion with the\n            # actual call. Theoretically this can be parallelized.\n\n            for subds in ds.subdatasets(fulfilled=True,\n                                        recursive=True,\n                                        recursion_limit=recursion_limit,\n                                        result_xfm='datasets'):\n                yield from _create_sibling_ria(\n                    subds,\n                    url,\n                    name,\n                    storage_sibling,\n                    storage_name,\n                    existing,\n                    shared,\n                    group,\n                    post_update_hook,\n                    trust_level,\n                    res_kwargs)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 64,
                            "end_lineno": 349,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "6b6d671fe7a7efffe0106c3607d89143ea428402^",
    "new_commit_hash": "6b6d671fe7a7efffe0106c3607d89143ea428402",
    "commit_message": "Merge pull request #4459 from mih/enh-4424\n\nENH: Support dataset aliases in RIA stores",
    "commit_date": "2020-04-30T07:35:49+02:00",
    "metadata": {}
}
{
    "repo_name": "datalad",
    "new_commit_hash": "6b6d671fe7a7efffe0106c3607d89143ea428402",
    "test_file_codes": [
        "# ex: set sts=4 ts=4 sw=4 noet:\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n#   See COPYING file distributed along with the datalad package for the\n#   copyright and license terms.\n#\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n\"\"\"Test clone action\n\n\"\"\"\n\nimport logging\nimport os.path as op\nimport stat\n\nfrom unittest.mock import patch\n\nfrom datalad.config import ConfigManager\nfrom datalad import consts\nfrom datalad.api import (\n    clone,\n    create,\n    remove,\n)\nfrom datalad.utils import (\n    chpwd,\n    Path,\n    on_windows,\n)\nfrom datalad.support.exceptions import IncompleteResultsError\nfrom datalad.support.gitrepo import GitRepo\nfrom datalad.support.annexrepo import AnnexRepo\nfrom datalad.cmd import Runner\nfrom datalad.tests.utils import (\n    assert_false,\n    assert_in,\n    assert_message,\n    assert_not_in,\n    assert_raises,\n    assert_repo_status,\n    assert_result_count,\n    assert_result_values_equal,\n    assert_status,\n    create_tree,\n    eq_,\n    get_datasets_topdir,\n    integration,\n    known_failure,\n    known_failure_appveyor,\n    neq_,\n    nok_,\n    ok_,\n    ok_file_has_content,\n    has_symlink_capability,\n    ok_startswith,\n    patch_config,\n    serve_path_via_http,\n    skip_if_no_network,\n    skip_if_on_windows,\n    slow,\n    swallow_logs,\n    use_cassette,\n    with_sameas_remote,\n    with_tempfile,\n    with_testrepos,\n    with_tree,\n    SkipTest,\n)\nfrom datalad.core.distributed.clone import (\n    _get_installationpath_from_url,\n    decode_source_spec,\n)\nfrom datalad.distribution.dataset import Dataset\n\n# this is the dataset ID of our test dataset in the main datalad RIA store\ndatalad_store_testds_id = '76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561'\n\n\n@with_tempfile(mkdir=True)\n@with_tempfile(mkdir=True)\n@with_tempfile(mkdir=True)\ndef test_invalid_args(path, otherpath, alienpath):\n    # source == path\n    assert_raises(ValueError, clone, 'Zoidberg', path='Zoidberg')\n    assert_raises(ValueError, clone, 'ssh://mars/Zoidberg', path='ssh://mars/Zoidberg')\n\n    # \"invalid URL\" is a valid filepath... and since no clone to remote\n    # is possible - we can just assume that it is the (legit) file path\n    # which is provided, not a URL.  So both below should fail as any\n    # other clone from a non-existing source and not for the reason of\n    # \"invalid something\".  Behavior is similar to how Git performs - can\n    # clone into a URL-like path.\n\n    # install to an \"invalid URL\" path\n    res = clone('Zoidberg', path='ssh://mars:Zoidberg', on_failure='ignore')\n    assert_status('error', res)\n\n    # install to a \"remote location\" path\n    res = clone('Zoidberg', path='ssh://mars/Zoidberg', on_failure='ignore')\n    assert_status('error', res)\n\n    # make fake dataset\n    ds = create(path)\n    assert_raises(IncompleteResultsError, ds.clone, '/higherup.', 'Zoidberg')\n    # make real dataset, try to install outside\n    ds_target = create(Path(otherpath) / 'target')\n    assert_raises(ValueError, ds_target.clone, ds.path, path=ds.path)\n    assert_status('error', ds_target.clone(ds.path, path=alienpath, on_failure='ignore'))\n\n\n@integration\n@skip_if_no_network\n@use_cassette('test_install_crcns')\n@with_tempfile(mkdir=True)\n@with_tempfile(mkdir=True)\ndef test_clone_crcns(tdir, ds_path):\n    with chpwd(tdir):\n        res = clone('///', path=\"all-nonrecursive\", on_failure='ignore',\n                    result_xfm=None, return_type='list')\n        assert_status('ok', res)\n\n    # again, but into existing dataset:\n    ds = create(ds_path)\n    crcns = ds.clone(\"///crcns\", result_xfm='datasets', return_type='item-or-list')\n    ok_(crcns.is_installed())\n    eq_(crcns.pathobj, ds.pathobj / \"crcns\")\n    assert_in(crcns.path, ds.subdatasets(result_xfm='paths'))\n\n\n@integration\n@skip_if_no_network\n@use_cassette('test_install_crcns')\n@with_tree(tree={'sub': {}})\ndef test_clone_datasets_root(tdir):\n    tdir = Path(tdir)\n    with chpwd(tdir):\n        ds = clone(\"///\")\n        ok_(ds.is_installed())\n        eq_(ds.pathobj, tdir / get_datasets_topdir())\n\n        # do it a second time:\n        res = clone(\"///\", on_failure='ignore', result_xfm=None, return_type='list')\n        assert_message(\n            \"dataset %s was already cloned from '%s'\",\n            res)\n        assert_status('notneeded', res)\n\n        # and a third time into an existing something, that is not a dataset:\n        (tdir / 'sub' / 'a_file.txt').write_text(\"something\")\n\n        res = clone('///', path=\"sub\", on_failure='ignore')\n        assert_message(\n            'target path already exists and not empty, refuse to clone into target path',\n            res)\n        assert_status('error', res)\n\n\n@with_testrepos('.*basic.*', flavors=['local-url', 'network', 'local'])\n@with_tempfile(mkdir=True)\ndef test_clone_simple_local(src, path):\n    origin = Dataset(path)\n\n    # now install it somewhere else\n    ds = clone(src, path, description='mydummy',\n               result_xfm='datasets', return_type='item-or-list')\n    eq_(ds.path, path)\n    ok_(ds.is_installed())\n    if not isinstance(origin.repo, AnnexRepo):\n        # this means it is a GitRepo\n        ok_(isinstance(origin.repo, GitRepo))\n        # stays plain Git repo\n        ok_(isinstance(ds.repo, GitRepo))\n        ok_(not isinstance(ds.repo, AnnexRepo))\n        ok_(GitRepo.is_valid_repo(ds.path))\n        eq_(set(ds.repo.get_indexed_files()),\n            {'test.dat', 'INFO.txt'})\n        assert_repo_status(path, annex=False)\n    else:\n        # must be an annex\n        ok_(isinstance(ds.repo, AnnexRepo))\n        ok_(AnnexRepo.is_valid_repo(ds.path, allow_noninitialized=False))\n        eq_(set(ds.repo.get_indexed_files()),\n            {'test.dat', 'INFO.txt', 'test-annex.dat'})\n        assert_repo_status(path, annex=True)\n        # no content was installed:\n        ok_(not ds.repo.file_has_content('test-annex.dat'))\n        uuid_before = ds.repo.uuid\n        eq_(ds.repo.get_description(), 'mydummy')\n\n    # installing it again, shouldn't matter:\n    res = clone(src, path, result_xfm=None, return_type='list')\n    assert_result_values_equal(res, 'source_url', [src])\n    assert_status('notneeded', res)\n    assert_message(\"dataset %s was already cloned from '%s'\", res)\n    ok_(ds.is_installed())\n    if isinstance(origin.repo, AnnexRepo):\n        eq_(uuid_before, ds.repo.uuid)\n\n\n@with_testrepos(flavors=['local-url', 'network', 'local'])\n@with_tempfile\ndef test_clone_dataset_from_just_source(url, path):\n    with chpwd(path, mkdir=True):\n        ds = clone(url, result_xfm='datasets', return_type='item-or-list')\n\n    ok_startswith(ds.path, path)\n    ok_(ds.is_installed())\n    ok_(GitRepo.is_valid_repo(ds.path))\n    assert_repo_status(ds.path, annex=None)\n    assert_in('INFO.txt', ds.repo.get_indexed_files())\n\n\n# test fails randomly, likely a bug in one of the employed test helpers\n# https://github.com/datalad/datalad/pull/3966#issuecomment-571267932\n@known_failure\n@with_tree(tree={\n    'ds': {'test.txt': 'some'},\n    })\n@serve_path_via_http\n@with_tempfile(mkdir=True)\ndef test_clone_dataladri(src, topurl, path):\n    # make plain git repo\n    ds_path = Path(src) / 'ds'\n    gr = GitRepo(ds_path, create=True)\n    gr.add('test.txt')\n    gr.commit('demo')\n    Runner(cwd=gr.path)(['git', 'update-server-info'])\n    # now install it somewhere else\n    with patch('datalad.consts.DATASETS_TOPURL', topurl):\n        ds = clone('///ds', path, result_xfm='datasets', return_type='item-or-list')\n    eq_(ds.path, path)\n    assert_repo_status(path, annex=False)\n    ok_file_has_content(ds.pathobj / 'test.txt', 'some')\n\n\n@with_testrepos('submodule_annex', flavors=['local', 'local-url', 'network'])\n@with_tempfile(mkdir=True)\n@with_tempfile(mkdir=True)\ndef test_clone_isnot_recursive(src, path_nr, path_r):\n    ds = clone(src, path_nr, result_xfm='datasets', return_type='item-or-list')\n    ok_(ds.is_installed())\n    # check nothin is unintentionally installed\n    subdss = ds.subdatasets(recursive=True)\n    assert_result_count(subdss, len(subdss), state='absent')\n    # this also means, subdatasets to be listed as not fulfilled:\n    eq_(set(ds.subdatasets(recursive=True, fulfilled=False, result_xfm='relpaths')),\n        {'subm 1', '2'})\n\n\n@slow  # 23.1478s\n@with_testrepos(flavors=['local'])\n# 'local-url', 'network'\n# TODO: Somehow annex gets confused while initializing installed ds, whose\n# .git/config show a submodule url \"file:///aaa/bbb%20b/...\"\n# this is delivered by with_testrepos as the url to clone\n@with_tempfile\ndef test_clone_into_dataset(source, top_path):\n\n    ds = create(top_path)\n    assert_repo_status(ds.path)\n\n    subds = ds.clone(source, \"sub\",\n                     result_xfm='datasets', return_type='item-or-list')\n    ok_((subds.pathobj / '.git').is_dir())\n    ok_(subds.is_installed())\n    assert_in('sub', ds.subdatasets(fulfilled=True, result_xfm='relpaths'))\n    # sub is clean:\n    assert_repo_status(subds.path, annex=None)\n    # top is clean:\n    assert_repo_status(ds.path, annex=None)\n\n    # but we could also save while installing and there should be no side-effect\n    # of saving any other changes if we state to not auto-save changes\n    # Create a dummy change\n    create_tree(ds.path, {'dummy.txt': 'buga'})\n    assert_repo_status(ds.path, untracked=['dummy.txt'])\n    subds_ = ds.clone(source, \"sub2\",\n                      result_xfm='datasets', return_type='item-or-list')\n    eq_(subds_.pathobj, ds.pathobj / \"sub2\")  # for paranoid yoh ;)\n    assert_repo_status(ds.path, untracked=['dummy.txt'])\n\n\n@with_testrepos('submodule_annex', flavors=['local', 'local-url', 'network'])\n@with_tempfile(mkdir=True)\ndef test_notclone_known_subdataset(src, path):\n    # get the superdataset:\n    ds = clone(src, path,\n               result_xfm='datasets', return_type='item-or-list')\n\n    # subdataset not installed:\n    subds = Dataset(ds.pathobj / 'subm 1')\n    assert_false(subds.is_installed())\n    assert_in('subm 1', ds.subdatasets(fulfilled=False, result_xfm='relpaths'))\n    assert_not_in('subm 1', ds.subdatasets(fulfilled=True, result_xfm='relpaths'))\n    # clone is not meaningful\n    res = ds.clone('subm 1', on_failure='ignore')\n    assert_status('error', res)\n    assert_message('Failed to clone from all attempted sources: %s',\n                   res)\n    # get does the job\n    res = ds.get(path='subm 1', get_data=False)\n    assert_status('ok', res)\n    ok_(subds.is_installed())\n    ok_(AnnexRepo.is_valid_repo(subds.path, allow_noninitialized=False))\n    # Verify that it is the correct submodule installed and not\n    # new repository initiated\n    eq_(set(subds.repo.get_indexed_files()),\n        {'test.dat', 'INFO.txt', 'test-annex.dat'})\n    assert_not_in('subm 1', ds.subdatasets(fulfilled=False, result_xfm='relpaths'))\n    assert_in('subm 1', ds.subdatasets(fulfilled=True, result_xfm='relpaths'))\n\n\n@with_tempfile(mkdir=True)\ndef test_failed_clone(dspath):\n    ds = create(dspath)\n    res = ds.clone(\"http://nonexistingreallyanything.datalad.org/bla\", \"sub\",\n                   on_failure='ignore')\n    assert_status('error', res)\n    assert_message('Failed to clone from all attempted sources: %s',\n                   res)\n\n\n@with_testrepos('submodule_annex', flavors=['local'])\n@with_tempfile(mkdir=True)\n@with_tempfile(mkdir=True)\ndef test_reckless(src, top_path, sharedpath):\n    ds = clone(src, top_path, reckless=True,\n               result_xfm='datasets', return_type='item-or-list')\n    eq_(ds.config.get('annex.hardlink', None), 'true')\n    # actual value is 'auto', because True is a legacy value and we map it\n    eq_(ds.config.get('datalad.clone.reckless', None), 'auto')\n    eq_(ds.repo.repo_info()['untrusted repositories'][0]['here'], True)\n    # now, if we clone another repo into this one, it will inherit the setting\n    # without having to provide it explicitly\n    sub = ds.clone(src, 'sub', result_xfm='datasets', return_type='item-or-list')\n    eq_(sub.config.get('datalad.clone.reckless', None), 'auto')\n    eq_(sub.config.get('annex.hardlink', None), 'true')\n\n    if ds.repo.is_managed_branch():\n        raise SkipTest(\"Remainder of test needs proper filesystem permissions\")\n\n    # the standard setup keeps the annex locks accessible to the user only\n    nok_((ds.pathobj / '.git' / 'annex' / 'index.lck').stat().st_mode \\\n         & stat.S_IWGRP)\n    # but we can set it up for group-shared access too\n    sharedds = clone(\n        src, sharedpath,\n        reckless='shared-group',\n        result_xfm='datasets',\n        return_type='item-or-list')\n    ok_((sharedds.pathobj / '.git' / 'annex' / 'index.lck').stat().st_mode \\\n        & stat.S_IWGRP)\n\n\n@with_tempfile\n@with_tempfile\ndef test_install_source_relpath(src, dest):\n    src = Path(src)\n    create(src)\n    src_ = src.name\n    with chpwd(src.parent):\n        clone(src_, dest)\n\n\n@with_tempfile\n@with_tempfile\ndef test_clone_isnt_a_smartass(origin_path, path):\n    origin = create(origin_path)\n    cloned = clone(origin, path,\n                   result_xfm='datasets', return_type='item-or-list')\n    with chpwd(path):\n        # no were are inside a dataset clone, and we make another one\n        # we do not want automatic subdatasetification without given a dataset\n        # explicitely\n        clonedsub = clone(origin, 'testsub',\n                          result_xfm='datasets', return_type='item-or-list')\n    # correct destination\n    assert clonedsub.path.startswith(path)\n    # no subdataset relation\n    eq_(cloned.subdatasets(), [])\n\n\n@with_tempfile(mkdir=True)\ndef test_clone_report_permission_issue(tdir):\n    pdir = Path(tdir) / 'protected'\n    pdir.mkdir()\n    # make it read-only\n    pdir.chmod(0o555)\n    with chpwd(pdir):\n        # first check the premise of the test. If we can write (strangely\n        # mounted/crippled file system, subsequent assumptions are violated\n        # and we can stop\n        probe = Path('probe')\n        try:\n            probe.write_text('should not work')\n            raise SkipTest\n        except PermissionError:\n            # we are indeed in a read-only situation\n            pass\n        res = clone('///', result_xfm=None, return_type='list', on_failure='ignore')\n        assert_status('error', res)\n        assert_result_count(\n            res, 1, status='error',\n            message=\"could not create work tree dir '%s/%s': Permission denied\"\n                    % (pdir, get_datasets_topdir())\n        )\n\n\n# Started to hang on appveyor.\n@known_failure_appveyor  #FIXME - hangs\n@skip_if_no_network\n@with_tempfile\ndef test_autoenabled_remote_msg(path):\n    # Verify that no message about a remote not been enabled is displayed\n    # whenever the remote we clone is the  type=git special remote, so the name\n    # of the remote might not match\n    with swallow_logs(new_level=logging.INFO) as cml:\n        res = clone('///repronim/containers', path, result_xfm=None, return_type='list')\n        assert_status('ok', res)\n        assert_not_in(\"not auto-enabled\", cml.out)\n\n\n@with_sameas_remote(autoenabled=True)\n@with_tempfile(mkdir=True)\ndef test_clone_autoenable_msg_handles_sameas(repo, clone_path):\n    ds = Dataset(repo.path)\n    with swallow_logs(new_level=logging.INFO) as cml:\n        res = clone(ds, clone_path, result_xfm=None, return_type='list')\n        assert_status('ok', res)\n        assert_in(\"r_dir\", cml.out)\n        assert_in(\"not auto-enabled\", cml.out)\n        # The rsyncurl remote was enabled.\n        assert_not_in(\"r_rsync\", cml.out)\n    ds_cloned = Dataset(clone_path)\n    remotes = ds_cloned.repo.get_remotes()\n    assert_in(\"r_rsync\", remotes)\n    assert_not_in(\"r_dir\", remotes)\n\n\ndef test_installationpath_from_url():\n    cases = (\n        'http://example.com/lastbit',\n        'http://example.com/lastbit.git',\n        'http://lastbit:8000',\n    ) + (\n        'C:\\\\Users\\\\mih\\\\AppData\\\\Local\\\\Temp\\\\lastbit',\n        'C:\\\\Users\\\\mih\\\\AppData\\\\Local\\\\Temp\\\\lastbit\\\\',\n        'Temp\\\\lastbit',\n        'Temp\\\\lastbit\\\\',\n        'lastbit.git',\n        'lastbit.git\\\\',\n    ) if on_windows else (\n        'lastbit',\n        'lastbit/',\n        '/lastbit',\n        'lastbit.git',\n        'lastbit.git/',\n    )\n    for p in cases:\n        eq_(_get_installationpath_from_url(p), 'lastbit')\n    # we need to deal with quoted urls\n    for url in (\n        # although some docs say that space could've been replaced with +\n        'http://localhost:8000/+last%20bit',\n        'http://localhost:8000/%2Blast%20bit',\n        '///%2Blast%20bit',\n        '///d1/%2Blast%20bit',\n        '///d1/+last bit',\n    ):\n        eq_(_get_installationpath_from_url(url), '+last bit')\n    # and the hostname alone\n    eq_(_get_installationpath_from_url(\"http://hostname\"), 'hostname')\n    eq_(_get_installationpath_from_url(\"http://hostname/\"), 'hostname')\n\n\n# https://github.com/datalad/datalad/issues/3958\n@with_tempfile(mkdir=True)\n@with_tempfile(mkdir=True)\ndef test_expanduser(srcpath, destpath):\n    src = Dataset(Path(srcpath) / 'src').create()\n    dest = Dataset(Path(destpath) / 'dest').create()\n\n    with chpwd(destpath), patch.dict('os.environ', {'HOME': srcpath}):\n        res = clone(op.join('~', 'src'), 'dest', result_xfm=None, return_type='list',\n                    on_failure='ignore')\n        assert_result_count(res, 1)\n        assert_result_count(\n            res, 1, action='install', status='error', path=dest.path,\n            message='target path already exists and not empty, refuse to '\n            'clone into target path')\n        # wipe out destination, and try again\n        assert_status('ok', remove(dataset=dest, check=False))\n        # now it should do it, and clone the right one\n        cloneds = clone(op.join('~', 'src'), 'dest')\n        eq_(cloneds.pathobj, Path(destpath) / 'dest')\n        eq_(src.id, cloneds.id)\n        # and it shouldn't fail when doing it again, because it detects\n        # the re-clone\n        cloneds = clone(op.join('~', 'src'), 'dest')\n        eq_(cloneds.pathobj, Path(destpath) / 'dest')\n\n\n@with_tempfile(mkdir=True)\ndef test_cfg_originorigin(path):\n    path = Path(path)\n    origin = Dataset(path / 'origin').create()\n    (origin.pathobj / 'file1.txt').write_text('content')\n    origin.save()\n    clone_lev1 = clone(origin, path / 'clone_lev1')\n    clone_lev2 = clone(clone_lev1, path / 'clone_lev2')\n    # the goal is to be able to get file content from origin without\n    # the need to configure it manually\n    assert_result_count(\n        clone_lev2.get('file1.txt', on_failure='ignore'),\n        1,\n        action='get',\n        status='ok',\n        path=str(clone_lev2.pathobj / 'file1.txt'),\n    )\n    eq_((clone_lev2.pathobj / 'file1.txt').read_text(), 'content')\n    eq_(\n        Path(clone_lev2.siblings(\n            'query',\n            name='origin-2',\n            return_type='item-or-list')['url']),\n        origin.pathobj\n    )\n\n    # Clone another level, this time with a relative path. Drop content from\n    # lev2 so that origin is the only place that the file is available from.\n    clone_lev2.drop(\"file1.txt\")\n    with chpwd(path), swallow_logs(new_level=logging.DEBUG) as cml:\n        clone_lev3 = clone('clone_lev2', 'clone_lev3')\n        # we called git-annex-init; see gh-4367:\n        cml.assert_logged(msg=r\"[^[]*Async run \\[('git', 'annex'|'git-annex'), \"\n                              r\"'init'\",\n                          match=False,\n                          level='DEBUG')\n    assert_result_count(\n        clone_lev3.get('file1.txt', on_failure='ignore'),\n        1,\n        action='get',\n        status='ok',\n        path=str(clone_lev3.pathobj / 'file1.txt'))\n\n\n# test fix for gh-2601/gh-3538\n@known_failure\n@with_tempfile()\ndef test_relative_submodule_url(path):\n    Dataset(op.join(path, 'origin')).create()\n    ds = Dataset(op.join(path, 'ds')).create()\n    with chpwd(ds.path):\n        ds_cloned = ds.clone(\n            source=op.join(op.pardir, 'origin'),\n            path='sources')\n\n    # Check that a simple fetch call does not fail.\n    ds_cloned.repo.fetch()\n\n    subinfo = ds.subdatasets(return_type='item-or-list')\n    eq_(subinfo['gitmodule_url'],\n        # must be a relative URL, not platform-specific relpath!\n        '../../origin')\n\n\n@with_tree(tree={\"subdir\": {}})\n@with_tempfile(mkdir=True)\ndef test_local_url_with_fetch(path, path_other):\n    path = Path(path)\n    path_other = Path(path_other)\n    Dataset(path / \"source\").create()\n\n    for where, source, path in [\n            (path, \"source\", \"a\"),\n            (path / \"subdir\", op.join(op.pardir, \"source\"), \"a\"),\n            (path, \"source\", path_other / \"a\")]:\n        with chpwd(where):\n            ds_cloned = clone(source=source, path=path)\n            # Perform a fetch to check that the URL points to a valid location.\n            ds_cloned.repo.fetch()\n\n\ndef test_decode_source_spec():\n    # resolves datalad RIs:\n    eq_(decode_source_spec('///subds'),\n        dict(source='///subds', giturl=consts.DATASETS_TOPURL + 'subds', version=None,\n             type='dataladri', default_destpath='subds'))\n    assert_raises(NotImplementedError, decode_source_spec,\n                  '//custom/subds')\n\n    # doesn't harm others:\n    for url in (\n            'http://example.com',\n            '/absolute/path',\n            'file://localhost/some',\n            'localhost/another/path',\n            'user@someho.st/mydir',\n            'ssh://somewhe.re/else',\n            'git://github.com/datalad/testrepo--basic--r1',\n    ):\n        props = decode_source_spec(url)\n        dest = props.pop('default_destpath')\n        eq_(props, dict(source=url, version=None, giturl=url, type='giturl'))\n\n    # RIA URIs with and without version specification\n    dsid = '6d69ca68-7e85-11e6-904c-002590f97d84'\n    for proto, loc, version in (\n            ('http', 'example.com', None),\n            ('http', 'example.com', 'v1.0'),\n            ('http', 'example.com', 'some_with@in_it'),\n            ('ssh', 'example.com', 'some_with@in_it'),\n    ):\n        spec = 'ria+{}://{}{}{}'.format(\n            proto,\n            loc,\n            '#{}'.format(dsid),\n            '@{}'.format(version) if version else '')\n        eq_(decode_source_spec(spec),\n            dict(\n                source=spec,\n                giturl='{}://{}/{}/{}'.format(\n                    proto,\n                    loc,\n                    dsid[:3],\n                    dsid[3:]),\n                version=version,\n                default_destpath=dsid,\n                type='ria')\n        )\n    # not a dataset UUID\n    assert_raises(ValueError, decode_source_spec, 'ria+http://example.com#123')\n\n    # literal dataset name/location\n    eq_(decode_source_spec('ria+http://example.com#~rootds'),\n        {'source': 'ria+http://example.com#~rootds',\n         'version': None, 'type': 'ria',\n         'giturl': 'http://example.com/alias/rootds',\n         'default_destpath': 'rootds'})\n    # version etc still works\n    eq_(decode_source_spec('ria+http://example.com#~rootds@specialbranch'),\n        {'source': 'ria+http://example.com#~rootds@specialbranch',\n         'version': 'specialbranch', 'type': 'ria',\n         'giturl': 'http://example.com/alias/rootds',\n         'default_destpath': 'rootds'})\n\n\ndef _move2store(storepath, d):\n    # make a bare clone of it into a local that matches the organization\n    # of a ria dataset store\n    store_loc = str(storepath / d.id[:3] / d.id[3:])\n    d.repo.call_git(['clone', '--bare', d.path, store_loc])\n    d.siblings('configure', name='store', url=str(store_loc),\n               result_renderer='disabled')\n    Runner(cwd=store_loc).run(['git', 'update-server-info'])\n\n\n@with_tree(tree={\n    'ds': {\n        'test.txt': 'some',\n        'subdir': {\n            'subds': {'testsub.txt': 'somemore'},\n        },\n    },\n})\n@with_tempfile(mkdir=True)\n@serve_path_via_http\ndef test_ria_http(lcl, storepath, url):\n    # create a local dataset with a subdataset\n    lcl = Path(lcl)\n    storepath = Path(storepath)\n    subds = Dataset(lcl / 'ds' / 'subdir' / 'subds').create(force=True)\n    subds.save()\n    ds = Dataset(lcl / 'ds').create(force=True)\n    ds.save(version_tag='original')\n    assert_repo_status(ds.path)\n    for d in (ds, subds):\n        _move2store(storepath, d)\n    # location of superds in store\n    storeds_loc = str(storepath / ds.id[:3] / ds.id[3:])\n    # now we should be able to clone from a ria+http url\n    # the super\n    riaclone = clone(\n        'ria+{}#{}'.format(url, ds.id),\n        lcl / 'clone',\n    )\n\n    # due to default configuration, clone() should automatically look for the\n    # subdataset in the store, too -- if not the following would fail, because\n    # we never configured a proper submodule URL\n    riaclonesub = riaclone.get(\n        op.join('subdir', 'subds'), get_data=False,\n        result_xfm='datasets', return_type='item-or-list')\n\n    # both datasets came from the store and must be set up in an identical\n    # fashion\n    for origds, cloneds in ((ds, riaclone), (subds, riaclonesub)):\n        eq_(origds.id, cloneds.id)\n        if not ds.repo.is_managed_branch():\n            # test logic cannot handle adjusted branches\n            eq_(origds.repo.get_hexsha(), cloneds.repo.get_hexsha())\n        ok_(cloneds.config.get('remote.origin.url').startswith(url))\n        eq_(cloneds.config.get('remote.origin.annex-ignore'), 'true')\n        eq_(cloneds.config.get('datalad.get.subdataset-source-candidate-origin'),\n            'ria+%s#{id}' % url)\n\n    # now advance the source dataset\n    (ds.pathobj / 'newfile.txt').write_text('new')\n    ds.save()\n    ds.publish(to='store')\n    Runner(cwd=storeds_loc).run(['git', 'update-server-info'])\n    # re-clone as before\n    riaclone2 = clone(\n        'ria+{}#{}'.format(url, ds.id),\n        lcl / 'clone2',\n    )\n    # and now clone a specific version, here given be the tag name\n    riaclone_orig = clone(\n        'ria+{}#{}@{}'.format(url, ds.id, 'original'),\n        lcl / 'clone_orig',\n    )\n    if not ds.repo.is_managed_branch():\n        # test logic cannot handle adjusted branches\n        # we got the precise version we wanted\n        eq_(riaclone.repo.get_hexsha(), riaclone_orig.repo.get_hexsha())\n        # and not the latest\n        eq_(riaclone2.repo.get_hexsha(), ds.repo.get_hexsha())\n        neq_(riaclone2.repo.get_hexsha(), riaclone_orig.repo.get_hexsha())\n\n    # attempt to clone a version that doesn't exist\n    with swallow_logs():\n        with assert_raises(IncompleteResultsError) as cme:\n            clone('ria+{}#{}@impossible'.format(url, ds.id),\n                  lcl / 'clone_failed')\n        assert_in(\"not found in upstream\", str(cme.exception))\n\n    # lastly test if URL rewriting is in effect\n    # on the surface we clone from an SSH source identified by some custom\n    # label, no full URL, but URL rewriting setup maps it back to the\n    # HTTP URL used above\n    with patch_config({\n            'url.ria+{}#.insteadof'.format(url): 'ria+ssh://somelabel#'}):\n        cloned_by_label = clone(\n            'ria+ssh://somelabel#{}'.format(origds.id),\n            lcl / 'cloned_by_label',\n        )\n    # so we get the same setup as above, but....\n    eq_(origds.id, cloned_by_label.id)\n    if not ds.repo.is_managed_branch():\n        # test logic cannot handle adjusted branches\n        eq_(origds.repo.get_hexsha(), cloned_by_label.repo.get_hexsha())\n    ok_(cloned_by_label.config.get('remote.origin.url').startswith(url))\n    eq_(cloned_by_label.config.get('remote.origin.annex-ignore'), 'true')\n    # ... the clone candidates go with the label-based URL such that\n    # future get() requests acknowlege a (system-wide) configuration\n    # update\n    eq_(cloned_by_label.config.get('datalad.get.subdataset-source-candidate-origin'),\n        'ria+ssh://somelabel#{id}')\n\n    if not has_symlink_capability():\n        return\n    # place a symlink in the store to serve as a dataset alias\n    (storepath / 'alias').mkdir()\n    (storepath / 'alias' / 'myname').symlink_to(storeds_loc)\n    with chpwd(lcl):\n        cloned_by_alias = clone('ria+{}#~{}'.format(url, 'myname'))\n    # still get the same data\n    eq_(cloned_by_alias.id, ds.id)\n    # more sensible default install path\n    eq_(cloned_by_alias.pathobj.name, 'myname')\n\n\n@with_tempfile(mkdir=True)\n@with_tempfile(mkdir=True)\n@serve_path_via_http\ndef test_inherit_src_candidates(lcl, storepath, url):\n    lcl = Path(lcl)\n    storepath = Path(storepath)\n    # dataset with a subdataset\n    ds1 = Dataset(lcl / 'ds1').create()\n    ds1sub = ds1.create('sub')\n    # a different dataset into which we install ds1, but do not touch its subds\n    ds2 = Dataset(lcl / 'ds2').create()\n    ds2.clone(source=ds1.path, path='mysub')\n\n    # we give no dataset a source candidate config!\n    # move all dataset into the store\n    for d in (ds1, ds1sub, ds2):\n        _move2store(storepath, d)\n\n    # now we must be able to obtain all three datasets from the store\n    riaclone = clone(\n        'ria+{}#{}'.format(\n            # store URL\n            url,\n            # ID of the root dataset\n            ds2.id),\n        lcl / 'clone',\n    )\n    # what happens is the the initial clone call sets a source candidate\n    # config, because it sees the dataset coming from a store\n    # all obtained subdatasets get the config inherited on-clone\n    datasets = riaclone.get('.', get_data=False, recursive=True, result_xfm='datasets')\n    # we get two subdatasets\n    eq_(len(datasets), 2)\n    for ds in datasets:\n        eq_(ConfigManager(dataset=ds, source='dataset-local').get(\n            'datalad.get.subdataset-source-candidate-origin'),\n            'ria+%s#{id}' % url)\n\n\n@skip_if_no_network\n@with_tempfile()\ndef test_ria_http_storedataladorg(path):\n    # can we clone from the store w/o any dedicated config\n    ds = clone('ria+http://store.datalad.org#{}'.format(datalad_store_testds_id), path)\n    ok_(ds.is_installed())\n    eq_(ds.id, datalad_store_testds_id)\n\n\n@skip_if_on_windows  # see gh-4131\n@with_tree(tree={\n    'ds': {\n        'test.txt': 'some',\n        'subdir': {'testsub.txt': 'somemore'},\n    },\n})\n@with_tempfile\n@with_tempfile\ndef test_ephemeral(origin_path, clone1_path, clone2_path):\n\n    file_test = Path('ds') / 'test.txt'\n    file_testsub = Path('ds') / 'subdir' / 'testsub.txt'\n\n    origin = Dataset(origin_path).create(force=True)\n    if origin.repo.is_managed_branch():\n        raise SkipTest('Ephemeral clones cannot use adjusted mode repos')\n\n    origin.save()\n    # 1. clone via path\n    clone1 = clone(origin_path, clone1_path, reckless='ephemeral')\n\n    can_symlink = has_symlink_capability()\n\n    if can_symlink:\n        clone1_annex = (clone1.repo.dot_git / 'annex')\n        ok_(clone1_annex.is_symlink())\n        ok_(clone1_annex.resolve().samefile(origin.repo.dot_git / 'annex'))\n        if not clone1.repo.is_managed_branch():\n            # TODO: We can't properly handle adjusted branch yet\n            eq_((clone1.pathobj / file_test).read_text(), 'some')\n            eq_((clone1.pathobj / file_testsub).read_text(), 'somemore')\n\n    # 2. clone via file-scheme URL\n    clone2 = clone('file://' + Path(origin_path).as_posix(), clone2_path,\n                   reckless='ephemeral')\n\n    if can_symlink:\n        clone2_annex = (clone2.repo.dot_git / 'annex')\n        ok_(clone2_annex.is_symlink())\n        ok_(clone2_annex.resolve().samefile(origin.repo.dot_git / 'annex'))\n        if not clone2.repo.is_managed_branch():\n            # TODO: We can't properly handle adjusted branch yet\n            eq_((clone1.pathobj / file_test).read_text(), 'some')\n            eq_((clone1.pathobj / file_testsub).read_text(), 'somemore')\n\n    # 3. add something to clone1 and push back to origin availability from\n    # clone1 should not be propagated (we declared 'here' dead to that end)\n\n    (clone1.pathobj / 'addition.txt').write_text(\"even more\")\n    clone1.save()\n    origin.config.set(\"receive.denyCurrentBranch\", \"updateInstead\",\n                      where=\"local\")\n    # Note, that the only thing to test is git-annex-dead here,\n    # if we couldn't symlink:\n    clone1.publish(to='origin', transfer_data='none' if can_symlink else 'auto')\n    if not origin.repo.is_managed_branch():\n        # test logic cannot handle adjusted branches\n        eq_(origin.repo.get_hexsha(), clone1.repo.get_hexsha())\n    res = origin.repo.whereis(\"addition.txt\")\n    if can_symlink:\n        # obv. present in origin, but this is not yet known to origin:\n        eq_(res, [])\n        res = origin.repo.fsck()\n        assert_result_count(res, 3, success=True)\n        # TODO: Double check whether annex reports POSIX paths o windows!\n        eq_({str(file_test), str(file_testsub), \"addition.txt\"},\n            {r['file'] for r in res})\n        # now origin knows:\n    res = origin.repo.whereis(\"addition.txt\")\n    eq_(res, [origin.config.get(\"annex.uuid\")])\n\n\n@with_tempfile(mkdir=True)\ndef test_clone_unborn_head(path):\n    ds_origin = Dataset(op.join(path, \"a\")).create()\n    repo = ds_origin.repo\n    managed = repo.is_managed_branch()\n\n    # The setup below is involved, mostly because it's accounting for adjusted\n    # branches. The scenario itself isn't so complicated, though:\n    #\n    #   * a checked out master branch with no commits\n    #   * a (potentially adjusted) \"abc\" branch with commits.\n    #   * a (potentially adjusted) \"chooseme\" branch whose tip commit has a\n    #     more recent commit than any in \"abc\".\n    (ds_origin.pathobj / \"foo\").write_text(\"foo content\")\n    ds_origin.save(message=\"foo\")\n    for res in repo.for_each_ref_(fields=\"refname\"):\n        ref = res[\"refname\"]\n        if \"master\" in ref:\n            repo.update_ref(ref.replace(\"master\", \"abc\"), ref)\n            repo.call_git([\"update-ref\", \"-d\", ref])\n    repo.update_ref(\"HEAD\",\n                    \"refs/heads/{}\".format(\n                        \"adjusted/abc(unlocked)\" if managed else \"abc\"),\n                    symbolic=True)\n    repo.call_git([\"checkout\", \"-b\", \"chooseme\", \"abc~1\"])\n    if managed:\n        repo.adjust()\n    (ds_origin.pathobj / \"bar\").write_text(\"bar content\")\n    ds_origin.save(message=\"bar\")\n    # Try to make the git-annex branch the most recently updated ref so that we\n    # test that it is skipped.\n    ds_origin.drop(\"bar\", check=False)\n    ds_origin.repo.checkout(\"master\", options=[\"--orphan\"])\n\n    ds = clone(ds_origin.path, op.join(path, \"b\"))\n    # We landed on the branch with the most recent commit, ignoring the\n    # git-annex branch.\n    branch = ds.repo.get_active_branch()\n    eq_(ds.repo.get_corresponding_branch(branch) or branch,\n        \"chooseme\")\n    eq_(ds_origin.repo.get_hexsha(\"chooseme\"),\n        ds.repo.get_hexsha(\"chooseme\"))\n    # In the context of this test, the clone should be on an adjusted branch if\n    # the source landed there initially because we're on the same file system.\n    eq_(managed, ds.repo.is_managed_branch())\n\n\n@with_tempfile(mkdir=True)\ndef test_clone_unborn_head_no_other_ref(path):\n    ds_origin = Dataset(op.join(path, \"a\")).create(annex=False)\n    ds_origin.repo.call_git([\"update-ref\", \"-d\", \"refs/heads/master\"])\n    with swallow_logs(new_level=logging.WARNING) as cml:\n        clone(source=ds_origin.path, path=op.join(path, \"b\"))\n        assert_in(\"could not find a branch with commits\", cml.out)\n\n\n@with_tempfile(mkdir=True)\ndef test_clone_unborn_head_sub(path):\n    ds_origin = Dataset(op.join(path, \"a\")).create()\n    ds_origin_sub = Dataset(op.join(path, \"a\", \"sub\")).create()\n    managed = ds_origin_sub.repo.is_managed_branch()\n    ds_origin_sub.repo.call_git([\"branch\", \"-m\", \"master\", \"other\"])\n    ds_origin.save()\n    ds_origin_sub.repo.checkout(\"master\", options=[\"--orphan\"])\n\n    ds_cloned = clone(source=ds_origin.path, path=op.join(path, \"b\"))\n    ds_cloned_sub = ds_cloned.get(\n        \"sub\", result_xfm=\"datasets\", return_type=\"item-or-list\")\n\n    branch = ds_cloned_sub.repo.get_active_branch()\n    eq_(ds_cloned_sub.repo.get_corresponding_branch(branch) or branch,\n        \"other\")\n    # In the context of this test, the clone should be on an adjusted branch if\n    # the source landed there initially because we're on the same file system.\n    eq_(managed, ds_cloned_sub.repo.is_managed_branch())\n\n\n@skip_if_no_network\n@with_tempfile\ndef test_gin_cloning(path):\n    # can we clone a public ds anoynmously from gin and retrieve content\n    ds = clone('https://gin.g-node.org/datalad/datalad-ci-target', path)\n    ok_(ds.is_installed())\n    annex_path = op.join('annex', 'two')\n    git_path = op.join('git', 'one')\n    eq_(ds.repo.file_has_content(annex_path), False)\n    eq_(ds.repo.is_under_annex(git_path), False)\n    result = ds.get(annex_path)\n    assert_result_count(result, 1)\n    assert_status('ok', result)\n    eq_(result[0]['path'], op.join(ds.path, annex_path))\n    ok_file_has_content(op.join(ds.path, annex_path), 'two\\n')\n    ok_file_has_content(op.join(ds.path, git_path), 'one\\n')\n",
        "import pytest\nimport tempfile\nimport os\n\n\n@pytest.fixture\ndef path():\n    with tempfile.TemporaryDirectory() as tmpdir:\n        yield tmpdir\n\n\n@pytest.fixture(autouse=True)\ndef setup_git_config():\n    with tempfile.TemporaryDirectory() as home:\n        old_home = os.environ.get(\"HOME\")\n        os.environ[\"HOME\"] = home\n        os.system('git config --global user.name \"DataLad Tester\"')\n        os.system('git config --global user.email \"test@example.com\"')\n        yield\n        if old_home:\n            os.environ[\"HOME\"] = old_home\n"
    ],
    "test_file_names": [
        "test_1.py",
        "conftest.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "Starting Datalad installation attempts...\nVerifying installation...\nDatalad version: 0.12.6.dev631\n✅ Installation successful!\nSuccessfully installed Datalad using Python 3.9\n",
    "setup_res_stderr": "Using CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 25 packages in 16ms\nInstalled 25 packages in 5.65s\n + coverage==7.6.10\n + docopt==0.6.2\n + exceptiongroup==1.2.2\n + grabbit==0.2.6\n + importlib-resources==6.4.5\n + iniconfig==2.0.0\n + nibabel==5.3.2\n + num2words==0.5.14\n + numpy==2.0.2\n + packaging==24.2\n + pandas==2.2.3\n + patsy==1.0.1\n + pluggy==1.5.0\n + pybids==0.6.5\n + pytest==8.3.4\n + pytest-cov==6.0.0\n + python-dateutil==2.9.0.post0\n + pytz==2024.2\n + scipy==1.13.1\n + setuptools==75.6.0\n + six==1.17.0\n + tomli==2.2.1\n + typing-extensions==4.12.2\n + tzdata==2024.2\n + zipp==3.21.0\nResolved 63 packages in 3.73s\nPrepared 1 package in 5.64s\nInstalled 57 packages in 360ms\n + annexremote==1.6.6\n + appdirs==1.4.4\n + backports-tarfile==1.2.0\n + beautifulsoup4==4.12.3\n + boto==2.49.0\n + certifi==2024.12.14\n + cffi==1.17.1\n + chardet==5.2.0\n + charset-normalizer==3.4.1\n + citeproc-py==0.6.0\n + cryptography==44.0.0\n + datalad==0.12.6 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402)\n + deprecated==1.2.15\n + distro==1.9.0\n + duecredit==0.10.2\n + exifread==3.0.0\n + fasteners==0.19\n + httpretty==1.1.4\n + humanize==4.11.0\n + idna==3.10\n + importlib-metadata==8.5.0\n + iso8601==2.1.0\n + jaraco-classes==3.4.0\n + jaraco-context==6.0.1\n + jaraco-functools==4.1.0\n + jeepney==0.8.0\n + jsmin==3.0.1\n + keyring==25.6.0\n + keyrings-alt==5.0.2\n + looseversion==1.3.0\n + lxml==5.3.0\n + more-itertools==10.5.0\n + msgpack==1.1.0\n + multidict==6.1.0\n + mutagen==1.47.0\n + nose==1.3.7\n + patool==1.15.0\n + pillow==11.0.0\n + propcache==0.2.1\n + pycparser==2.22\n + pygithub==2.5.0\n + pyjwt==2.10.1\n + pynacl==1.5.0\n + pyperclip==1.9.0\n + python-xmp-toolkit==2.0.2\n + pyyaml==6.0.2\n + requests==2.32.3\n + requests-ftp==0.3.1\n + secretstorage==3.3.3\n + simplejson==3.19.3\n + soupsieve==2.6\n + tqdm==4.67.1\n + urllib3==1.26.20\n + vcrpy==7.0.0\n + whoosh==2.7.4\n + wrapt==1.17.0\n + yarl==1.18.3\nResolved 97 packages in 207ms\nInstalled 32 packages in 564ms\n + alabaster==0.7.16\n + asv==0.6.4\n + asv-runner==0.2.1\n + babel==2.16.0\n + build==1.2.2.post1\n + distlib==0.3.9\n + docutils==0.21.2\n + filelock==3.16.1\n + gprof2dot==2024.6.6\n + imagesize==1.4.1\n + jinja2==3.1.5\n + json5==0.10.0\n + markupsafe==3.0.2\n + nose-timer==1.0.1\n + platformdirs==4.3.6\n + psutil==6.1.1\n + pygments==2.18.0\n + pympler==1.1\n + pypandoc==1.14\n + pyproject-hooks==1.2.0\n + snowballstemmer==2.2.0\n + sphinx==7.4.7\n + sphinx-rtd-theme==3.0.2\n + sphinxcontrib-applehelp==2.0.0\n + sphinxcontrib-devhelp==2.0.0\n + sphinxcontrib-htmlhelp==2.1.0\n + sphinxcontrib-jquery==4.1\n + sphinxcontrib-jsmath==1.0.1\n + sphinxcontrib-qthelp==2.0.0\n + sphinxcontrib-serializinghtml==2.0.0\n + tabulate==0.9.0\n + virtualenv==20.28.0\n",
    "new_commit_res_code": 1,
    "new_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.9.21, pytest-8.3.4, pluggy-1.5.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402\nplugins: cov-6.0.0\ncollected 30 items\n\nr2e_tests/test_1.py EEEEEEEEEEEEEEFE.EFsE.EEFEFFFF                       [100%]\n\n==================================== ERRORS ====================================\n_____________________ ERROR at setup of test_invalid_args ______________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 79\n  @with_tempfile(mkdir=True)\n  @with_tempfile(mkdir=True)\n  @with_tempfile(mkdir=True)\n  def test_invalid_args(path, otherpath, alienpath):\nE       fixture 'otherpath' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:79\n______________________ ERROR at setup of test_clone_crcns ______________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 111\n  @integration\n  @skip_if_no_network\n  @use_cassette('test_install_crcns')\n  @with_tempfile(mkdir=True)\n  @with_tempfile(mkdir=True)\n  def test_clone_crcns(tdir, ds_path):\nE       fixture 'tdir' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:111\n__________________ ERROR at setup of test_clone_datasets_root __________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 130\n  @integration\n  @skip_if_no_network\n  @use_cassette('test_install_crcns')\n  @with_tree(tree={'sub': {}})\n  def test_clone_datasets_root(tdir):\nE       fixture 'tdir' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:130\n__________________ ERROR at setup of test_clone_simple_local ___________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 158\n  @with_testrepos('.*basic.*', flavors=['local-url', 'network', 'local'])\n  @with_tempfile(mkdir=True)\n  def test_clone_simple_local(src, path):\nE       fixture 'src' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:158\n____________ ERROR at setup of test_clone_dataset_from_just_source _____________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 200\n  @with_testrepos(flavors=['local-url', 'network', 'local'])\n  @with_tempfile\n  def test_clone_dataset_from_just_source(url, path):\nE       fixture 'url' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:200\n____________________ ERROR at setup of test_clone_dataladri ____________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 215\n  @known_failure\n  @with_tree(tree={\n      'ds': {'test.txt': 'some'},\n      })\n  @serve_path_via_http\n  @with_tempfile(mkdir=True)\n  def test_clone_dataladri(src, topurl, path):\nE       fixture 'src' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:215\n_________________ ERROR at setup of test_clone_isnot_recursive _________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 236\n  @with_testrepos('submodule_annex', flavors=['local', 'local-url', 'network'])\n  @with_tempfile(mkdir=True)\n  @with_tempfile(mkdir=True)\n  def test_clone_isnot_recursive(src, path_nr, path_r):\nE       fixture 'src' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:236\n__________________ ERROR at setup of test_clone_into_dataset ___________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 250\n  @slow  # 23.1478s\n  @with_testrepos(flavors=['local'])\n  # 'local-url', 'network'\n  # TODO: Somehow annex gets confused while initializing installed ds, whose\n  # .git/config show a submodule url \"file:///aaa/bbb%20b/...\"\n  # this is delivered by with_testrepos as the url to clone\n  @with_tempfile\n  def test_clone_into_dataset(source, top_path):\nE       fixture 'source' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:250\n_______________ ERROR at setup of test_notclone_known_subdataset _______________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 283\n  @with_testrepos('submodule_annex', flavors=['local', 'local-url', 'network'])\n  @with_tempfile(mkdir=True)\n  def test_notclone_known_subdataset(src, path):\nE       fixture 'src' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:283\n_____________________ ERROR at setup of test_failed_clone ______________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 313\n  @with_tempfile(mkdir=True)\n  def test_failed_clone(dspath):\nE       fixture 'dspath' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:313\n_______________________ ERROR at setup of test_reckless ________________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 323\n  @with_testrepos('submodule_annex', flavors=['local'])\n  @with_tempfile(mkdir=True)\n  @with_tempfile(mkdir=True)\n  def test_reckless(src, top_path, sharedpath):\nE       fixture 'src' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:323\n________________ ERROR at setup of test_install_source_relpath _________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 355\n  @with_tempfile\n  @with_tempfile\n  def test_install_source_relpath(src, dest):\nE       fixture 'src' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:355\n_________________ ERROR at setup of test_clone_isnt_a_smartass _________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 365\n  @with_tempfile\n  @with_tempfile\n  def test_clone_isnt_a_smartass(origin_path, path):\nE       fixture 'origin_path' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:365\n_____________ ERROR at setup of test_clone_report_permission_issue _____________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 383\n  @with_tempfile(mkdir=True)\n  def test_clone_report_permission_issue(tdir):\nE       fixture 'tdir' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:383\n__________ ERROR at setup of test_clone_autoenable_msg_handles_sameas __________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 423\n  @with_sameas_remote(autoenabled=True)\n  @with_tempfile(mkdir=True)\n  def test_clone_autoenable_msg_handles_sameas(repo, clone_path):\nE       fixture 'repo' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:423\n______________________ ERROR at setup of test_expanduser _______________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 477\n  @with_tempfile(mkdir=True)\n  @with_tempfile(mkdir=True)\n  def test_expanduser(srcpath, destpath):\nE       fixture 'srcpath' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:477\n_________________ ERROR at setup of test_local_url_with_fetch __________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 567\n  @with_tree(tree={\"subdir\": {}})\n  @with_tempfile(mkdir=True)\n  def test_local_url_with_fetch(path, path_other):\nE       fixture 'path_other' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:567\n_______________________ ERROR at setup of test_ria_http ________________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 658\n  @with_tree(tree={\n      'ds': {\n          'test.txt': 'some',\n          'subdir': {\n              'subds': {'testsub.txt': 'somemore'},\n          },\n      },\n  })\n  @with_tempfile(mkdir=True)\n  @serve_path_via_http\n  def test_ria_http(lcl, storepath, url):\nE       fixture 'lcl' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:658\n________________ ERROR at setup of test_inherit_src_candidates _________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 773\n  @with_tempfile(mkdir=True)\n  @with_tempfile(mkdir=True)\n  @serve_path_via_http\n  def test_inherit_src_candidates(lcl, storepath, url):\nE       fixture 'lcl' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:773\n_______________________ ERROR at setup of test_ephemeral _______________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 821\n  @skip_if_on_windows  # see gh-4131\n  @with_tree(tree={\n      'ds': {\n          'test.txt': 'some',\n          'subdir': {'testsub.txt': 'somemore'},\n      },\n  })\n  @with_tempfile\n  @with_tempfile\n  def test_ephemeral(origin_path, clone1_path, clone2_path):\nE       fixture 'origin_path' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:821\n=================================== FAILURES ===================================\n_________________________ test_autoenabled_remote_msg __________________________\n\nargs = (), kwargs = {'path': '/tmp/tmp-page2annexvexj8dhm'}\n\n    @wraps(func)\n    @attr('network')\n    @attr('skip_if_no_network')\n    def newfunc(*args, **kwargs):\n        check_and_raise()\n>       return func(*args, **kwargs)\n\ndatalad/tests/utils.py:166: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\narg = (), kw = {'path': '/tmp/tmp-page2annexvexj8dhm'}\nfilename = '/tmp/datalad_temp_test_autoenabled_remote_msgo3uqh5s0'\n\n    @wraps(t)\n    def newfunc(*arg, **kw):\n        with make_tempfile(wrapped=t, **tkwargs) as filename:\n>           return t(*(arg + (filename,)), **kw)\nE           TypeError: test_autoenabled_remote_msg() got multiple values for argument 'path'\n\ndatalad/tests/utils.py:691: TypeError\n____________________________ test_cfg_originorigin _____________________________\n\narg = (), kw = {'path': '/tmp/tmp-page2annexxkw0g6og'}\nfilename = '/tmp/datalad_temp_test_cfg_originorigin8kq7i9i6'\n\n    @wraps(t)\n    def newfunc(*arg, **kw):\n        with make_tempfile(wrapped=t, **tkwargs) as filename:\n>           return t(*(arg + (filename,)), **kw)\nE           TypeError: test_cfg_originorigin() got multiple values for argument 'path'\n\ndatalad/tests/utils.py:691: TypeError\n________________________ test_ria_http_storedataladorg _________________________\n\nargs = (), kwargs = {'path': '/tmp/tmp-page2annextn0w88me'}\n\n    @wraps(func)\n    @attr('network')\n    @attr('skip_if_no_network')\n    def newfunc(*args, **kwargs):\n        check_and_raise()\n>       return func(*args, **kwargs)\n\ndatalad/tests/utils.py:166: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\narg = (), kw = {'path': '/tmp/tmp-page2annextn0w88me'}\nfilename = '/tmp/datalad_temp_test_ria_http_storedataladorg2zbcv9n2'\n\n    @wraps(t)\n    def newfunc(*arg, **kw):\n        with make_tempfile(wrapped=t, **tkwargs) as filename:\n>           return t(*(arg + (filename,)), **kw)\nE           TypeError: test_ria_http_storedataladorg() got multiple values for argument 'path'\n\ndatalad/tests/utils.py:691: TypeError\n____________________________ test_clone_unborn_head ____________________________\n\narg = (), kw = {'path': '/tmp/tmp-page2annex3w92wxuc'}\nfilename = '/tmp/datalad_temp_test_clone_unborn_heada36k9j1j'\n\n    @wraps(t)\n    def newfunc(*arg, **kw):\n        with make_tempfile(wrapped=t, **tkwargs) as filename:\n>           return t(*(arg + (filename,)), **kw)\nE           TypeError: test_clone_unborn_head() got multiple values for argument 'path'\n\ndatalad/tests/utils.py:691: TypeError\n_____________________ test_clone_unborn_head_no_other_ref ______________________\n\narg = (), kw = {'path': '/tmp/tmp-page2annexff66tazx'}\nfilename = '/tmp/datalad_temp_test_clone_unborn_head_no_other_ref3og7i83t'\n\n    @wraps(t)\n    def newfunc(*arg, **kw):\n        with make_tempfile(wrapped=t, **tkwargs) as filename:\n>           return t(*(arg + (filename,)), **kw)\nE           TypeError: test_clone_unborn_head_no_other_ref() got multiple values for argument 'path'\n\ndatalad/tests/utils.py:691: TypeError\n__________________________ test_clone_unborn_head_sub __________________________\n\narg = (), kw = {'path': '/tmp/tmp-page2annexjy9osrr8'}\nfilename = '/tmp/datalad_temp_test_clone_unborn_head_subgveytpnu'\n\n    @wraps(t)\n    def newfunc(*arg, **kw):\n        with make_tempfile(wrapped=t, **tkwargs) as filename:\n>           return t(*(arg + (filename,)), **kw)\nE           TypeError: test_clone_unborn_head_sub() got multiple values for argument 'path'\n\ndatalad/tests/utils.py:691: TypeError\n_______________________________ test_gin_cloning _______________________________\n\nargs = (), kwargs = {'path': '/tmp/tmp-page2annexsnbww7w_'}\n\n    @wraps(func)\n    @attr('network')\n    @attr('skip_if_no_network')\n    def newfunc(*args, **kwargs):\n        check_and_raise()\n>       return func(*args, **kwargs)\n\ndatalad/tests/utils.py:166: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\narg = (), kw = {'path': '/tmp/tmp-page2annexsnbww7w_'}\nfilename = '/tmp/datalad_temp_test_gin_cloning02vdeuyp'\n\n    @wraps(t)\n    def newfunc(*arg, **kw):\n        with make_tempfile(wrapped=t, **tkwargs) as filename:\n>           return t(*(arg + (filename,)), **kw)\nE           TypeError: test_gin_cloning() got multiple values for argument 'path'\n\ndatalad/tests/utils.py:691: TypeError\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::test_installationpath_from_url\nPASSED r2e_tests/test_1.py::test_decode_source_spec\nSKIPPED [1] .venv/lib/python3.9/site-packages/_pytest/unittest.py:385: Skip test known to fail\nERROR r2e_tests/test_1.py::test_invalid_args\nERROR r2e_tests/test_1.py::test_clone_crcns\nERROR r2e_tests/test_1.py::test_clone_datasets_root\nERROR r2e_tests/test_1.py::test_clone_simple_local\nERROR r2e_tests/test_1.py::test_clone_dataset_from_just_source\nERROR r2e_tests/test_1.py::test_clone_dataladri\nERROR r2e_tests/test_1.py::test_clone_isnot_recursive\nERROR r2e_tests/test_1.py::test_clone_into_dataset\nERROR r2e_tests/test_1.py::test_notclone_known_subdataset\nERROR r2e_tests/test_1.py::test_failed_clone\nERROR r2e_tests/test_1.py::test_reckless\nERROR r2e_tests/test_1.py::test_install_source_relpath\nERROR r2e_tests/test_1.py::test_clone_isnt_a_smartass\nERROR r2e_tests/test_1.py::test_clone_report_permission_issue\nERROR r2e_tests/test_1.py::test_clone_autoenable_msg_handles_sameas\nERROR r2e_tests/test_1.py::test_expanduser\nERROR r2e_tests/test_1.py::test_local_url_with_fetch\nERROR r2e_tests/test_1.py::test_ria_http\nERROR r2e_tests/test_1.py::test_inherit_src_candidates\nERROR r2e_tests/test_1.py::test_ephemeral\nFAILED r2e_tests/test_1.py::test_autoenabled_remote_msg - TypeError: test_aut...\nFAILED r2e_tests/test_1.py::test_cfg_originorigin - TypeError: test_cfg_origi...\nFAILED r2e_tests/test_1.py::test_ria_http_storedataladorg - TypeError: test_r...\nFAILED r2e_tests/test_1.py::test_clone_unborn_head - TypeError: test_clone_un...\nFAILED r2e_tests/test_1.py::test_clone_unborn_head_no_other_ref - TypeError: ...\nFAILED r2e_tests/test_1.py::test_clone_unborn_head_sub - TypeError: test_clon...\nFAILED r2e_tests/test_1.py::test_gin_cloning - TypeError: test_gin_cloning() ...\n============== 7 failed, 2 passed, 1 skipped, 20 errors in 2.57s ===============\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.9.21, pytest-8.3.4, pluggy-1.5.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402\nplugins: cov-6.0.0\ncollected 30 items\n\nr2e_tests/test_1.py EEEEEEEEEEEEEEFE.EFsEFEEFEFFFF                       [100%]\n\n==================================== ERRORS ====================================\n_____________________ ERROR at setup of test_invalid_args ______________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 79\n  @with_tempfile(mkdir=True)\n  @with_tempfile(mkdir=True)\n  @with_tempfile(mkdir=True)\n  def test_invalid_args(path, otherpath, alienpath):\nE       fixture 'otherpath' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:79\n______________________ ERROR at setup of test_clone_crcns ______________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 111\n  @integration\n  @skip_if_no_network\n  @use_cassette('test_install_crcns')\n  @with_tempfile(mkdir=True)\n  @with_tempfile(mkdir=True)\n  def test_clone_crcns(tdir, ds_path):\nE       fixture 'tdir' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:111\n__________________ ERROR at setup of test_clone_datasets_root __________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 130\n  @integration\n  @skip_if_no_network\n  @use_cassette('test_install_crcns')\n  @with_tree(tree={'sub': {}})\n  def test_clone_datasets_root(tdir):\nE       fixture 'tdir' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:130\n__________________ ERROR at setup of test_clone_simple_local ___________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 158\n  @with_testrepos('.*basic.*', flavors=['local-url', 'network', 'local'])\n  @with_tempfile(mkdir=True)\n  def test_clone_simple_local(src, path):\nE       fixture 'src' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:158\n____________ ERROR at setup of test_clone_dataset_from_just_source _____________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 200\n  @with_testrepos(flavors=['local-url', 'network', 'local'])\n  @with_tempfile\n  def test_clone_dataset_from_just_source(url, path):\nE       fixture 'url' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:200\n____________________ ERROR at setup of test_clone_dataladri ____________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 215\n  @known_failure\n  @with_tree(tree={\n      'ds': {'test.txt': 'some'},\n      })\n  @serve_path_via_http\n  @with_tempfile(mkdir=True)\n  def test_clone_dataladri(src, topurl, path):\nE       fixture 'src' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:215\n_________________ ERROR at setup of test_clone_isnot_recursive _________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 236\n  @with_testrepos('submodule_annex', flavors=['local', 'local-url', 'network'])\n  @with_tempfile(mkdir=True)\n  @with_tempfile(mkdir=True)\n  def test_clone_isnot_recursive(src, path_nr, path_r):\nE       fixture 'src' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:236\n__________________ ERROR at setup of test_clone_into_dataset ___________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 250\n  @slow  # 23.1478s\n  @with_testrepos(flavors=['local'])\n  # 'local-url', 'network'\n  # TODO: Somehow annex gets confused while initializing installed ds, whose\n  # .git/config show a submodule url \"file:///aaa/bbb%20b/...\"\n  # this is delivered by with_testrepos as the url to clone\n  @with_tempfile\n  def test_clone_into_dataset(source, top_path):\nE       fixture 'source' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:250\n_______________ ERROR at setup of test_notclone_known_subdataset _______________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 283\n  @with_testrepos('submodule_annex', flavors=['local', 'local-url', 'network'])\n  @with_tempfile(mkdir=True)\n  def test_notclone_known_subdataset(src, path):\nE       fixture 'src' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:283\n_____________________ ERROR at setup of test_failed_clone ______________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 313\n  @with_tempfile(mkdir=True)\n  def test_failed_clone(dspath):\nE       fixture 'dspath' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:313\n_______________________ ERROR at setup of test_reckless ________________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 323\n  @with_testrepos('submodule_annex', flavors=['local'])\n  @with_tempfile(mkdir=True)\n  @with_tempfile(mkdir=True)\n  def test_reckless(src, top_path, sharedpath):\nE       fixture 'src' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:323\n________________ ERROR at setup of test_install_source_relpath _________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 355\n  @with_tempfile\n  @with_tempfile\n  def test_install_source_relpath(src, dest):\nE       fixture 'src' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:355\n_________________ ERROR at setup of test_clone_isnt_a_smartass _________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 365\n  @with_tempfile\n  @with_tempfile\n  def test_clone_isnt_a_smartass(origin_path, path):\nE       fixture 'origin_path' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:365\n_____________ ERROR at setup of test_clone_report_permission_issue _____________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 383\n  @with_tempfile(mkdir=True)\n  def test_clone_report_permission_issue(tdir):\nE       fixture 'tdir' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:383\n__________ ERROR at setup of test_clone_autoenable_msg_handles_sameas __________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 423\n  @with_sameas_remote(autoenabled=True)\n  @with_tempfile(mkdir=True)\n  def test_clone_autoenable_msg_handles_sameas(repo, clone_path):\nE       fixture 'repo' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:423\n______________________ ERROR at setup of test_expanduser _______________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 477\n  @with_tempfile(mkdir=True)\n  @with_tempfile(mkdir=True)\n  def test_expanduser(srcpath, destpath):\nE       fixture 'srcpath' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:477\n_________________ ERROR at setup of test_local_url_with_fetch __________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 567\n  @with_tree(tree={\"subdir\": {}})\n  @with_tempfile(mkdir=True)\n  def test_local_url_with_fetch(path, path_other):\nE       fixture 'path_other' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:567\n_______________________ ERROR at setup of test_ria_http ________________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 658\n  @with_tree(tree={\n      'ds': {\n          'test.txt': 'some',\n          'subdir': {\n              'subds': {'testsub.txt': 'somemore'},\n          },\n      },\n  })\n  @with_tempfile(mkdir=True)\n  @serve_path_via_http\n  def test_ria_http(lcl, storepath, url):\nE       fixture 'lcl' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:658\n________________ ERROR at setup of test_inherit_src_candidates _________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 773\n  @with_tempfile(mkdir=True)\n  @with_tempfile(mkdir=True)\n  @serve_path_via_http\n  def test_inherit_src_candidates(lcl, storepath, url):\nE       fixture 'lcl' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:773\n_______________________ ERROR at setup of test_ephemeral _______________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py, line 821\n  @skip_if_on_windows  # see gh-4131\n  @with_tree(tree={\n      'ds': {\n          'test.txt': 'some',\n          'subdir': {'testsub.txt': 'somemore'},\n      },\n  })\n  @with_tempfile\n  @with_tempfile\n  def test_ephemeral(origin_path, clone1_path, clone2_path):\nE       fixture 'origin_path' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_6b6d671fe7a7efffe0106c3607d89143ea428402/r2e_tests/test_1.py:821\n=================================== FAILURES ===================================\n_________________________ test_autoenabled_remote_msg __________________________\n\nargs = (), kwargs = {'path': '/tmp/tmp-page2annexbqyd_gar'}\n\n    @wraps(func)\n    @attr('network')\n    @attr('skip_if_no_network')\n    def newfunc(*args, **kwargs):\n        check_and_raise()\n>       return func(*args, **kwargs)\n\ndatalad/tests/utils.py:166: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\narg = (), kw = {'path': '/tmp/tmp-page2annexbqyd_gar'}\nfilename = '/tmp/datalad_temp_test_autoenabled_remote_msgipig53p6'\n\n    @wraps(t)\n    def newfunc(*arg, **kw):\n        with make_tempfile(wrapped=t, **tkwargs) as filename:\n>           return t(*(arg + (filename,)), **kw)\nE           TypeError: test_autoenabled_remote_msg() got multiple values for argument 'path'\n\ndatalad/tests/utils.py:691: TypeError\n____________________________ test_cfg_originorigin _____________________________\n\narg = (), kw = {'path': '/tmp/tmp-page2annexd2a76t8v'}\nfilename = '/tmp/datalad_temp_test_cfg_originoriginb93ld5en'\n\n    @wraps(t)\n    def newfunc(*arg, **kw):\n        with make_tempfile(wrapped=t, **tkwargs) as filename:\n>           return t(*(arg + (filename,)), **kw)\nE           TypeError: test_cfg_originorigin() got multiple values for argument 'path'\n\ndatalad/tests/utils.py:691: TypeError\n___________________________ test_decode_source_spec ____________________________\n\n    def test_decode_source_spec():\n        # resolves datalad RIs:\n        eq_(decode_source_spec('///subds'),\n            dict(source='///subds', giturl=consts.DATASETS_TOPURL + 'subds', version=None,\n                 type='dataladri', default_destpath='subds'))\n        assert_raises(NotImplementedError, decode_source_spec,\n                      '//custom/subds')\n    \n        # doesn't harm others:\n        for url in (\n                'http://example.com',\n                '/absolute/path',\n                'file://localhost/some',\n                'localhost/another/path',\n                'user@someho.st/mydir',\n                'ssh://somewhe.re/else',\n                'git://github.com/datalad/testrepo--basic--r1',\n        ):\n            props = decode_source_spec(url)\n            dest = props.pop('default_destpath')\n            eq_(props, dict(source=url, version=None, giturl=url, type='giturl'))\n    \n        # RIA URIs with and without version specification\n        dsid = '6d69ca68-7e85-11e6-904c-002590f97d84'\n        for proto, loc, version in (\n                ('http', 'example.com', None),\n                ('http', 'example.com', 'v1.0'),\n                ('http', 'example.com', 'some_with@in_it'),\n                ('ssh', 'example.com', 'some_with@in_it'),\n        ):\n            spec = 'ria+{}://{}{}{}'.format(\n                proto,\n                loc,\n                '#{}'.format(dsid),\n                '@{}'.format(version) if version else '')\n            eq_(decode_source_spec(spec),\n                dict(\n                    source=spec,\n                    giturl='{}://{}/{}/{}'.format(\n                        proto,\n                        loc,\n                        dsid[:3],\n                        dsid[3:]),\n                    version=version,\n                    default_destpath=dsid,\n                    type='ria')\n            )\n        # not a dataset UUID\n        assert_raises(ValueError, decode_source_spec, 'ria+http://example.com#123')\n    \n        # literal dataset name/location\n>       eq_(decode_source_spec('ria+http://example.com#~rootds'),\n            {'source': 'ria+http://example.com#~rootds',\n             'version': None, 'type': 'ria',\n             'giturl': 'http://example.com/alias/rootds',\n             'default_destpath': 'rootds'})\n\nr2e_tests/test_1.py:635: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nspec = 'ria+http://example.com#~rootds'\ncfg = <datalad.config.ConfigManager object at 0x73e9e664d130>\n\n    def decode_source_spec(spec, cfg=None):\n        \"\"\"Decode information from a clone source specification\n    \n        Parameters\n        ----------\n        spec : str\n          Any supported clone source specification\n        cfg : ConfigManager, optional\n          Configuration will be queried from the instance (i.e. from a particular\n          dataset). If None is given, the global DataLad configuration will be\n          queried.\n    \n        Returns\n        -------\n        dict\n          The value of each decoded property is stored under its own key in this\n          dict. By default the following keys are return: 'type', a specification\n          type label {'giturl', 'dataladri', 'ria'}; 'source' the original\n          source specification; 'giturl' a URL for the source that is a suitable\n          source argument for git-clone; 'version' a version-identifer, if present\n          (None else); 'default_destpath' a relative path that that can be used as\n          a clone destination.\n        \"\"\"\n        if cfg is None:\n            from datalad import cfg\n        # standard property dict composition\n        props = dict(\n            source=spec,\n            version=None,\n        )\n    \n        # Git never gets to see these URLs, so let's manually apply any\n        # rewrite configuration Git might know about.\n        # Note: We need to rewrite before parsing, otherwise parsing might go wrong.\n        # This is particularly true for insteadOf labels replacing even the URL\n        # scheme.\n        spec = cfg.rewrite_url(spec)\n        # common starting point is a RI instance, support for accepting an RI\n        # instance is kept for backward-compatibility reasons\n        source_ri = RI(spec) if not isinstance(spec, RI) else spec\n    \n        # scenario switch, each case must set 'giturl' at the very minimum\n        if isinstance(source_ri, DataLadRI):\n            # we have got our DataLadRI as the source, so expand it\n            props['type'] = 'dataladri'\n            props['giturl'] = source_ri.as_git_url()\n        elif isinstance(source_ri, URL) and source_ri.scheme.startswith('ria+'):\n            # parse a RIA URI\n            dsid, version = source_ri.fragment.split('@', maxsplit=1) \\\n                if '@' in source_ri.fragment else (source_ri.fragment, None)\n            uuid_regex = r'[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}'\n            if not re.match(uuid_regex, dsid):\n>               raise ValueError('RIA URI does not contain a valid dataset ID: {}'.format(spec))\nE               ValueError: RIA URI does not contain a valid dataset ID: ria+http://example.com#~rootds\n\ndatalad/core/distributed/clone.py:930: ValueError\n________________________ test_ria_http_storedataladorg _________________________\n\nargs = (), kwargs = {'path': '/tmp/tmp-page2annexan8f9owp'}\n\n    @wraps(func)\n    @attr('network')\n    @attr('skip_if_no_network')\n    def newfunc(*args, **kwargs):\n        check_and_raise()\n>       return func(*args, **kwargs)\n\ndatalad/tests/utils.py:166: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\narg = (), kw = {'path': '/tmp/tmp-page2annexan8f9owp'}\nfilename = '/tmp/datalad_temp_test_ria_http_storedataladorgo7ybx_op'\n\n    @wraps(t)\n    def newfunc(*arg, **kw):\n        with make_tempfile(wrapped=t, **tkwargs) as filename:\n>           return t(*(arg + (filename,)), **kw)\nE           TypeError: test_ria_http_storedataladorg() got multiple values for argument 'path'\n\ndatalad/tests/utils.py:691: TypeError\n____________________________ test_clone_unborn_head ____________________________\n\narg = (), kw = {'path': '/tmp/tmp-page2annex6khzuxpn'}\nfilename = '/tmp/datalad_temp_test_clone_unborn_headn9m_n5rg'\n\n    @wraps(t)\n    def newfunc(*arg, **kw):\n        with make_tempfile(wrapped=t, **tkwargs) as filename:\n>           return t(*(arg + (filename,)), **kw)\nE           TypeError: test_clone_unborn_head() got multiple values for argument 'path'\n\ndatalad/tests/utils.py:691: TypeError\n_____________________ test_clone_unborn_head_no_other_ref ______________________\n\narg = (), kw = {'path': '/tmp/tmp-page2annex5p5q4p8t'}\nfilename = '/tmp/datalad_temp_test_clone_unborn_head_no_other_ref1fl_b1tp'\n\n    @wraps(t)\n    def newfunc(*arg, **kw):\n        with make_tempfile(wrapped=t, **tkwargs) as filename:\n>           return t(*(arg + (filename,)), **kw)\nE           TypeError: test_clone_unborn_head_no_other_ref() got multiple values for argument 'path'\n\ndatalad/tests/utils.py:691: TypeError\n__________________________ test_clone_unborn_head_sub __________________________\n\narg = (), kw = {'path': '/tmp/tmp-page2annexon1l8swe'}\nfilename = '/tmp/datalad_temp_test_clone_unborn_head_subk6688pqd'\n\n    @wraps(t)\n    def newfunc(*arg, **kw):\n        with make_tempfile(wrapped=t, **tkwargs) as filename:\n>           return t(*(arg + (filename,)), **kw)\nE           TypeError: test_clone_unborn_head_sub() got multiple values for argument 'path'\n\ndatalad/tests/utils.py:691: TypeError\n_______________________________ test_gin_cloning _______________________________\n\nargs = (), kwargs = {'path': '/tmp/tmp-page2annexsmzbxap7'}\n\n    @wraps(func)\n    @attr('network')\n    @attr('skip_if_no_network')\n    def newfunc(*args, **kwargs):\n        check_and_raise()\n>       return func(*args, **kwargs)\n\ndatalad/tests/utils.py:166: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\narg = (), kw = {'path': '/tmp/tmp-page2annexsmzbxap7'}\nfilename = '/tmp/datalad_temp_test_gin_cloning95gyhdm6'\n\n    @wraps(t)\n    def newfunc(*arg, **kw):\n        with make_tempfile(wrapped=t, **tkwargs) as filename:\n>           return t(*(arg + (filename,)), **kw)\nE           TypeError: test_gin_cloning() got multiple values for argument 'path'\n\ndatalad/tests/utils.py:691: TypeError\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::test_installationpath_from_url\nSKIPPED [1] .venv/lib/python3.9/site-packages/_pytest/unittest.py:385: Skip test known to fail\nERROR r2e_tests/test_1.py::test_invalid_args\nERROR r2e_tests/test_1.py::test_clone_crcns\nERROR r2e_tests/test_1.py::test_clone_datasets_root\nERROR r2e_tests/test_1.py::test_clone_simple_local\nERROR r2e_tests/test_1.py::test_clone_dataset_from_just_source\nERROR r2e_tests/test_1.py::test_clone_dataladri\nERROR r2e_tests/test_1.py::test_clone_isnot_recursive\nERROR r2e_tests/test_1.py::test_clone_into_dataset\nERROR r2e_tests/test_1.py::test_notclone_known_subdataset\nERROR r2e_tests/test_1.py::test_failed_clone\nERROR r2e_tests/test_1.py::test_reckless\nERROR r2e_tests/test_1.py::test_install_source_relpath\nERROR r2e_tests/test_1.py::test_clone_isnt_a_smartass\nERROR r2e_tests/test_1.py::test_clone_report_permission_issue\nERROR r2e_tests/test_1.py::test_clone_autoenable_msg_handles_sameas\nERROR r2e_tests/test_1.py::test_expanduser\nERROR r2e_tests/test_1.py::test_local_url_with_fetch\nERROR r2e_tests/test_1.py::test_ria_http\nERROR r2e_tests/test_1.py::test_inherit_src_candidates\nERROR r2e_tests/test_1.py::test_ephemeral\nFAILED r2e_tests/test_1.py::test_autoenabled_remote_msg - TypeError: test_aut...\nFAILED r2e_tests/test_1.py::test_cfg_originorigin - TypeError: test_cfg_origi...\nFAILED r2e_tests/test_1.py::test_decode_source_spec - ValueError: RIA URI doe...\nFAILED r2e_tests/test_1.py::test_ria_http_storedataladorg - TypeError: test_r...\nFAILED r2e_tests/test_1.py::test_clone_unborn_head - TypeError: test_clone_un...\nFAILED r2e_tests/test_1.py::test_clone_unborn_head_no_other_ref - TypeError: ...\nFAILED r2e_tests/test_1.py::test_clone_unborn_head_sub - TypeError: test_clon...\nFAILED r2e_tests/test_1.py::test_gin_cloning - TypeError: test_gin_cloning() ...\n============== 8 failed, 1 passed, 1 skipped, 20 errors in 1.45s ===============\n",
    "old_commit_res_stderr": ""
}
datalad/core/distributed/clone.py datalad/core/distributed/tests/test_clone.py datalad/distributed/create_sibling_ria.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `decode_source_spec` Fails to Handle Dataset Aliases in RIA URIs

**Description:**
When attempting to decode a RIA URI that includes a dataset alias, the `decode_source_spec` function raises a `ValueError` instead of successfully parsing the alias. This prevents the proper installation of datasets identified by their aliases.

**Example Code:**
```python
source = 'ria+http://store.datalad.org#~hcp-openaccess'
result = decode_source_spec(source)
```

**Expected Behavior:**
The function should return a dictionary with the parsed details, correctly handling the alias. For example:
```python
{
    'source': 'ria+http://store.datalad.org#~hcp-openaccess',
    'version': None,
    'type': 'ria',
    'giturl': 'http://store.datalad.org/alias/hcp-openaccess',
    'default_destpath': 'hcp-openaccess'
}
```

**Actual Behavior:**
Instead of returning the expected dictionary, the function raises the following error:
```
ValueError: RIA URI does not contain a valid dataset ID: ria+http://store.datalad.org#~hcp-openaccess
```
This error occurs because the function does not recognize the alias format starting with `~`, leading to an inability to handle dataset aliases properly.
[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### datalad/core/distributed/clone.py
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
#   See COPYING file distributed along with the datalad package for the
#   copyright and license terms.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""Plumbing command for dataset installation"""


import logging
import re
from os.path import expanduser
from collections import OrderedDict
from urllib.parse import unquote as urlunquote

from datalad.interface.base import Interface
from datalad.interface.utils import eval_results
from datalad.interface.base import build_doc
from datalad.interface.results import get_status_dict
from datalad.interface.common_opts import (
    location_description,
    reckless_opt,
)
from datalad.log import log_progress
from datalad.support.gitrepo import (
    GitRepo,
)
from datalad.cmd import (
    CommandError,
)
from datalad.support.annexrepo import AnnexRepo
from datalad.support.constraints import (
    EnsureNone,
    EnsureStr,
    EnsureKeyChoice,
)
from datalad.support.param import Parameter
from datalad.support.network import (
    get_local_file_url,
    URL,
    RI,
    DataLadRI,
    PathRI,
)
from datalad.dochelpers import (
    exc_str,
    single_or_plural,
)
from datalad.utils import (
    rmtree,
    assure_bool,
    knows_annex,
    Path,
)

from datalad.distribution.dataset import (
    Dataset,
    datasetmethod,
    resolve_path,
    require_dataset,
    EnsureDataset,
)
from datalad.distribution.utils import (
    _get_flexible_source_candidates,
)
from datalad.utils import (
    check_symlink_capability
)

__docformat__ = 'restructuredtext'

lgr = logging.getLogger('datalad.core.distributed.clone')


@build_doc
class Clone(Interface):
    """Obtain a dataset (copy) from a URL or local directory

    The purpose of this command is to obtain a new clone (copy) of a dataset
    and place it into a not-yet-existing or empty directory. As such `clone`
    provides a strict subset of the functionality offered by `install`. Only a
    single dataset can be obtained, and immediate recursive installation of
    subdatasets is not supported. However, once a (super)dataset is installed
    via `clone`, any content, including subdatasets can be obtained by a
    subsequent `get` command.

    Primary differences over a direct `git clone` call are 1) the automatic
    initialization of a dataset annex (pure Git repositories are equally
    supported); 2) automatic registration of the newly obtained dataset as a
    subdataset (submodule), if a parent dataset is specified; 3) support
    for additional resource identifiers (DataLad resource identifiers as used
    on datasets.datalad.org, and RIA store URLs as used for store.datalad.org
    - optionally in specific versions as identified by a branch or a tag; see
    examples); and 4) automatic configurable generation of alternative access
    URL for common cases (such as appending '.git' to the URL in case the
    accessing the base URL failed).

    || PYTHON >>By default, the command returns a single Dataset instance for
    an installed dataset, regardless of whether it was newly installed ('ok'
    result), or found already installed from the specified source ('notneeded'
    result).<< PYTHON ||

    .. seealso::

      :ref:`handbook:3-001`
        More information on Remote Indexed Archive (RIA) stores
    """
    # by default ignore everything but install results
    # i.e. no "add to super dataset"
    result_filter = EnsureKeyChoice('action', ('install',))
    # very frequently this command will yield exactly one installed dataset
    # spare people the pain of going through a list by default
    return_type = 'item-or-list'
    # as discussed in #1409 and #1470, we want to return dataset instances
    # matching what is actually available after command completion (and
    # None for any failed dataset installation)
    result_xfm = 'successdatasets-or-none'

    _examples_ = [
        dict(text="Install a dataset from Github into the current directory",
             code_py="clone("
             "source='https://github.com/datalad-datasets/longnow"
             "-podcasts.git')",
             code_cmd="datalad clone "
             "https://github.com/datalad-datasets/longnow-podcasts.git"),
        dict(text="Install a dataset into a specific directory",
             code_py="""\
             clone(source='https://github.com/datalad-datasets/longnow-podcasts.git',
                   path='myfavpodcasts')""",
             code_cmd="""\
             datalad clone https://github.com/datalad-datasets/longnow-podcasts.git \\
             myfavpodcasts"""),
        dict(text="Install a dataset as a subdataset into the current dataset",
             code_py="""\
             clone(dataset='.',
                   source='https://github.com/datalad-datasets/longnow-podcasts.git')""",
             code_cmd="datalad clone -d . "
             "https://github.com/datalad-datasets/longnow-podcasts.git"),
        dict(text="Install the main superdataset from datasets.datalad.org",
             code_py="clone(source='///')",
             code_cmd="datalad clone ///"),
        dict(text="Install a dataset identified by its ID from store.datalad.org",
             code_py="clone(source='ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561')",
             code_cmd="datalad clone ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561"),
        dict(
            text="Install a dataset in a specific version as identified by a"
                 "branch or tag name from store.datalad.org",
            code_py="clone(source='ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561@myidentifier')",
            code_cmd="datalad clone ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561@myidentifier"),
        dict(
            text="Install a dataset with group-write access permissions",
            code_py=\
            "clone(source='http://example.com/dataset', reckless='shared-group')",
            code_cmd=\
            "datalad clone http://example.com/dataset --reckless shared-group"),
    ]

    _params_ = dict(
        dataset=Parameter(
            args=("-d", "--dataset"),
            doc="""(parent) dataset to clone into. If given, the newly cloned
            dataset is registered as a subdataset of the parent. Also, if given,
            relative paths are interpreted as being relative to the parent
            dataset, and not relative to the working directory.""",
            constraints=EnsureDataset() | EnsureNone()),
        source=Parameter(
            args=("source",),
            metavar='SOURCE',
            doc="""URL, DataLad resource identifier, local path or instance of
            dataset to be cloned""",
            constraints=EnsureStr() | EnsureNone()),
        path=Parameter(
            args=("path",),
            metavar='PATH',
            nargs="?",
            doc="""path to clone into.  If no `path` is provided a
            destination path will be derived from a source URL
            similar to :command:`git clone`"""),
        description=location_description,
        reckless=reckless_opt,
    )

    @staticmethod
    @datasetmethod(name='clone')
    @eval_results
    def __call__(
            source,
            path=None,
            dataset=None,
            description=None,
            reckless=None):
        # did we explicitly get a dataset to install into?
        # if we got a dataset, path will be resolved against it.
        # Otherwise path will be resolved first.
        ds = require_dataset(
            dataset, check_installed=True, purpose='cloning') \
            if dataset is not None else dataset
        refds_path = ds.path if ds else None

        # legacy compatibility
        if reckless is True:
            # so that we can forget about how things used to be
            reckless = 'auto'
        if reckless is None and ds:
            # if reckless is not explicitly given, but we operate on a
            # superdataset, query whether it has been instructed to operate
            # in a reckless mode, and inherit it for the coming clone
            reckless = ds.config.get('datalad.clone.reckless', None)

        if isinstance(source, Dataset):
            source = source.path

        if source == path:
            # even if they turn out to be identical after resolving symlinks
            # and more sophisticated witchcraft, it would still happily say
            # "it appears to be already installed", so we just catch an
            # obviously pointless input combination
            raise ValueError(
                "clone `source` and destination `path` are identical [{}]. "
                "If you are trying to add a subdataset simply use `save`".format(
                    path))

        if path is not None:
            path = resolve_path(path, dataset)

        # derive target from source:
        if path is None:
            # we got nothing but a source. do something similar to git clone
            # and derive the path from the source and continue
            # since this is a relative `path`, resolve it:
            # we are not going to reuse the decoded URL, as this is done for
            # all source candidates in clone_dataset(), we just use to determine
            # a destination path here in order to perform a bunch of additional
            # checks that shall not pollute the helper function
            source_ = decode_source_spec(
                source, cfg=None if ds is None else ds.config)
            path = resolve_path(source_['default_destpath'], dataset)
            lgr.debug("Determined clone target path from source")
        lgr.debug("Resolved clone target path to: '%s'", path)

        # there is no other way -- my intoxicated brain tells me
        assert(path is not None)

        result_props = dict(
            action='install',
            logger=lgr,
            refds=refds_path,
            source_url=source)

        try:
            # this will implicitly cause pathlib to run a bunch of checks
            # whether the present path makes any sense on the platform
            # we are running on -- we don't care if the path actually
            # exists at this point, but we want to abort early if the path
            # spec is determined to be useless
            path.exists()
        except OSError as e:
            yield get_status_dict(
                status='error',
                path=path,
                message=('cannot handle target path: %s', exc_str(e)),
                **result_props)
            return

        destination_dataset = Dataset(path)
        result_props['ds'] = destination_dataset

        if ds is not None and ds.pathobj not in path.parents:
            yield get_status_dict(
                status='error',
                message=("clone target path '%s' not in specified target dataset '%s'",
                         path, ds),
                **result_props)
            return

        # perform the actual cloning operation
        yield from clone_dataset(
            [source],
            destination_dataset,
            reckless,
            description,
            result_props,
            cfg=None if ds is None else ds.config,
        )

        # TODO handle any 'version' property handling and verification using a dedicated
        # public helper

        if ds is not None:
            # we created a dataset in another dataset
            # -> make submodule
            for r in ds.save(
                    path,
                    return_type='generator',
                    result_filter=None,
                    result_xfm=None,
                    on_failure='ignore'):
                yield r


def clone_dataset(
        srcs,
        destds,
        reckless=None,
        description=None,
        result_props=None,
        cfg=None):
    """Internal helper to perform cloning without sanity checks (assumed done)

    This helper does not handle any saving of subdataset modification or adding
    in a superdataset.

    Parameters
    ----------
    srcs : list
      Any suitable clone source specifications (paths, URLs)
    destds : Dataset
      Dataset instance for the clone destination
    reckless : {None, 'auto', 'ephemeral', 'shared-...'}, optional
      Mode switch to put cloned dataset into unsafe/throw-away configurations, i.e.
      sacrifice data safety for performance or resource footprint.
    description : str, optional
      Location description for the annex of the dataset clone (if there is any).
    result_props : dict, optional
      Default properties for any yielded result, passed on to get_status_dict().
    cfg : ConfigManager, optional
      Configuration will be queried from this instance (i.e. from a particular
      dataset). If None is given, the global DataLad configuration will be
      queried.

    Yields
    ------
    dict
      DataLad result records
    """
    if not result_props:
        # in case the caller had no specific idea on how results should look
        # like, provide sensible defaults
        result_props = dict(
            action='install',
            logger=lgr,
            ds=destds,
        )

    dest_path = destds.pathobj

    # decode all source candidate specifications
    candidate_sources = [decode_source_spec(s, cfg=cfg) for s in srcs]

    # now expand the candidate sources with additional variants of the decoded
    # giturl, while duplicating the other properties in the additional records
    # for simplicity. The hope is to overcome a few corner cases and be more
    # robust than git clone
    candidate_sources = [
        dict(props, giturl=s) for props in candidate_sources
        for s in _get_flexible_source_candidates(props['giturl'])
    ]

    # important test! based on this `rmtree` will happen below after failed clone
    dest_path_existed = dest_path.exists()
    if dest_path_existed and any(dest_path.iterdir()):
        if destds.is_installed():
            # check if dest was cloned from the given source before
            # this is where we would have installed this from
            # this is where it was actually installed from
            track_name, track_url = _get_tracking_source(destds)
            try:
                # this will get us track_url in system native path conventions,
                # whenever it is a path (and not a URL)
                # this is needed to match it to any potentially incoming local
                # source path in the 'notneeded' test below
                track_path = str(Path(track_url))
            except Exception:
                # this should never happen, because Path() will let any non-path stringification
                # pass through unmodified, but we do not want any potential crash due to
                # pathlib behavior changes
                lgr.debug("Unexpected behavior of pathlib!")
                track_path = None
            for cand in candidate_sources:
                src = cand['giturl']
                if track_url == src \
                        or get_local_file_url(track_url, compatibility='git') == src \
                        or track_path == expanduser(src):
                    yield get_status_dict(
                        status='notneeded',
                        message=("dataset %s was already cloned from '%s'",
                                 destds,
                                 src),
                        **result_props)
                    return
        # anything else is an error
        yield get_status_dict(
            status='error',
            message='target path already exists and not empty, refuse to clone into target path',
            **result_props)
        return

    log_progress(
        lgr.info,
        'cloneds',
        'Cloning dataset to %s', destds,
        total=len(candidate_sources),
        label='Clone attempt',
        unit=' Candidate locations',
    )
    error_msgs = OrderedDict()  # accumulate all error messages formatted per each url
    for cand in candidate_sources:
        log_progress(
            lgr.info,
            'cloneds',
            'Attempting to clone from %s to %s', cand['giturl'], dest_path,
            update=1,
            increment=True)

        clone_opts = {}

        if cand.get('version', None):
            clone_opts['branch'] = cand['version']
        try:
            # TODO for now GitRepo.clone() cannot handle Path instances, and PY35
            # doesn't make it happen seemlessly
            GitRepo.clone(
                path=str(dest_path),
                url=cand['giturl'],
                clone_options=clone_opts,
                create=True)

        except CommandError as e:
            e_stderr = e.stderr

            error_msgs[cand['giturl']] = e
            lgr.debug("Failed to clone from URL: %s (%s)",
                      cand['giturl'], exc_str(e))
            if dest_path.exists():
                lgr.debug("Wiping out unsuccessful clone attempt at: %s",
                          dest_path)
                # We must not just rmtree since it might be curdir etc
                # we should remove all files/directories under it
                # TODO stringification can be removed once patlib compatible
                # or if PY35 is no longer supported
                rmtree(str(dest_path), children_only=dest_path_existed)

            if 'could not create work tree' in e_stderr.lower():
                # this cannot be fixed by trying another URL
                re_match = re.match(r".*fatal: (.*)$", e_stderr,
                                    flags=re.MULTILINE | re.DOTALL)
                # cancel progress bar
                log_progress(
                    lgr.info,
                    'cloneds',
                    'Completed clone attempts for %s', destds
                )
                yield get_status_dict(
                    status='error',
                    message=re_match.group(1).strip()
                    if re_match else "stderr: " + e_stderr,
                    **result_props)
                return
            # next candidate
            continue

        result_props['source'] = cand
        # do not bother with other sources if succeeded
        break

    log_progress(
        lgr.info,
        'cloneds',
        'Completed clone attempts for %s', destds
    )

    if not destds.is_installed():
        if len(error_msgs):
            if all(not e.stdout and not e.stderr for e in error_msgs.values()):
                # there is nothing we can learn from the actual exception,
                # the exit code is uninformative, the command is predictable
                error_msg = "Failed to clone from all attempted sources: %s"
                error_args = list(error_msgs.keys())
            else:
                error_msg = "Failed to clone from any candidate source URL. " \
                            "Encountered errors per each url were:\n- %s"
                error_args = '\n- '.join(
                    '{}\n  {}'.format(url, exc_str(exc))
                    for url, exc in error_msgs.items()
                )
        else:
            # yoh: Not sure if we ever get here but I felt that there could
            #      be a case when this might happen and original error would
            #      not be sufficient to troubleshoot what is going on.
            error_msg = "Awkward error -- we failed to clone properly. " \
                        "Although no errors were encountered, target " \
                        "dataset at %s seems to be not fully installed. " \
                        "The 'succesful' source was: %s"
            error_args = (destds.path, cand['giturl'])
        yield get_status_dict(
            status='error',
            message=(error_msg, error_args),
            **result_props)
        return

    if not cand.get("version"):
        postclone_check_head(destds)

    # act on --reckless=shared-...
    # must happen prior git-annex-init, where we can cheaply alter the repo
    # setup through safe re-init'ing
    if reckless and reckless.startswith('shared-'):
        lgr.debug('Reinit %s to enable shared access permissions', destds)
        destds.repo.call_git(['init', '--shared={}'.format(reckless[7:])])

    yield from postclonecfg_annexdataset(
        destds,
        reckless,
        description)

    # perform any post-processing that needs to know details of the clone
    # source
    if result_props['source']['type'] == 'ria':
        yield from postclonecfg_ria(destds, result_props['source'])

    # yield successful clone of the base dataset now, as any possible
    # subdataset clone down below will not alter the Git-state of the
    # parent
    yield get_status_dict(status='ok', **result_props)


def postclone_check_head(ds):
    repo = ds.repo
    if not repo.commit_exists("HEAD"):
        # HEAD points to an unborn branch. A likely cause of this is that the
        # remote's main branch is something other than master but HEAD wasn't
        # adjusted accordingly.
        #
        # Let's choose the most recently updated remote ref (according to
        # commit date). In the case of a submodule, switching to a ref with
        # commits prevents .update_submodule() from failing. It is likely that
        # the ref includes the registered commit, but we don't have the
        # information here to know for sure. If it doesn't, .update_submodule()
        # will check out a detached HEAD.
        remote_branches = (
            b["refname:strip=2"] for b in repo.for_each_ref_(
                fields="refname:strip=2", sort="-committerdate",
                pattern="refs/remotes/origin"))
        for rbranch in remote_branches:
            if rbranch in ["origin/git-annex", "HEAD"]:
                continue
            repo.call_git(["checkout", "-b", rbranch[7:],  # drop "origin/"
                           "--track", rbranch])
            lgr.debug("Checked out local branch from %s", rbranch)
            return
        lgr.warning("Cloned %s but could not find a branch "
                    "with commits", ds.path)


def postclonecfg_ria(ds, props):
    """Configure a dataset freshly cloned from a RIA store"""
    # RIA uses hashdir mixed, copying data to it via git-annex (if cloned via
    # ssh) would make it see a bare repo and establish a hashdir lower annex
    # object tree.
    # Moreover, we want the RIA remote to receive all data for the store, so its
    # objects could be moved into archives (the main point of a RIA store).
    ds.config.set(
        'remote.origin.annex-ignore', 'true',
        where='local')

    # chances are that if this dataset came from a RIA store, its subdatasets
    # may live there too. Place a subdataset source candidate config that makes
    # get probe this RIA store when obtaining subdatasets
    ds.config.set(
        # we use the label 'origin' for this candidate in order to not have to
        # generate a complicated name from the actual source specification
        'datalad.get.subdataset-source-candidate-origin',
        # use the entire original URL, up to the fragment + plus dataset ID
        # placeholder, this should make things work with any store setup we
        # support (paths, ports, ...)
        props['source'].split('#', maxsplit=1)[0] + '#{id}',
        where='local')

    # setup publication dependency, if a corresponding special remote exists
    # and was enabled (there could be RIA stores that actually only have repos)
    # make this function be a generator
    ria_remotes = [s for s in ds.siblings('query', result_renderer='disabled')
                   if s.get('annex-externaltype', None) == 'ora'
    ]
    if not ria_remotes:
        lgr.debug("Found no RIA special remote")
    elif len(ria_remotes) == 1:
        yield from ds.siblings('configure',
                               name='origin',
                               publish_depends=ria_remotes[0]['name'],
                               result_filter=None,
                               result_renderer='disabled')
    else:
        lgr.warning("Found multiple RIA remotes. Couldn't decide which "
                    "publishing to origin should depend on: %s",
                    [r['name'] for r in ria_remotes])


def postclonecfg_annexdataset(ds, reckless, description=None):
    """If ds "knows annex" -- annex init it, set into reckless etc

    Provides additional tune up to a possibly an annex repo, e.g.
    "enables" reckless mode, sets up description
    """
    # in any case check whether we need to annex-init the installed thing:
    if not knows_annex(ds.path):
        # not for us
        return

    # init annex when traces of a remote annex can be detected
    if reckless == 'auto':
        lgr.debug(
            "Instruct annex to hardlink content in %s from local "
            "sources, if possible (reckless)", ds.path)
        ds.config.set(
            'annex.hardlink', 'true', where='local', reload=True)

    lgr.debug("Initializing annex repo at %s", ds.path)
    # Note, that we cannot enforce annex-init via AnnexRepo().
    # If such an instance already exists, its __init__ will not be executed.
    # Therefore do quick test once we have an object and decide whether to call
    # its _init().
    #
    # Additionally, call init if we need to add a description (see #1403),
    # since AnnexRepo.__init__ can only do it with create=True
    repo = AnnexRepo(ds.path, init=True)
    if not repo.is_initialized() or description:
        repo._init(description=description)
    if reckless == 'auto' or (reckless and reckless.startswith('shared-')):
        repo._run_annex_command('untrust', annex_options=['here'])

    elif reckless == 'ephemeral':
        # with ephemeral we declare 'here' as 'dead' right away, whenever
        # we symlink origin's annex, since availability from 'here' should
        # not be propagated for an ephemeral clone when we publish back to
        # origin.
        # This will cause stuff like this for a locally present annexed file:
        # % git annex whereis d1
        # whereis d1 (0 copies) failed
        # BUT this works:
        # % git annex find . --not --in here
        # % git annex find . --in here
        # d1

        # we don't want annex copy-to origin
        ds.config.set(
            'remote.origin.annex-ignore', 'true',
            where='local')

        ds.repo.set_remote_dead('here')

        if check_symlink_capability(ds.repo.dot_git / 'dl_link_test',
                                    ds.repo.dot_git / 'dl_target_test'):
            # symlink the annex to avoid needless copies in an emphemeral clone
            annex_dir = ds.repo.dot_git / 'annex'
            origin_annex_url = ds.config.get("remote.origin.url", None)
            origin_git_path = None
            if origin_annex_url:
                try:
                    # Deal with file:// scheme URLs as well as plain paths.
                    # If origin isn't local, we have nothing to do.
                    origin_git_path = Path(RI(origin_annex_url).localpath)
                    if origin_git_path.name != '.git':
                        origin_git_path /= '.git'
                except ValueError:
                    # Note, that accessing localpath on a non-local RI throws
                    # ValueError rather than resulting in an AttributeError.
                    # TODO: Warning level okay or is info level sufficient?
                    # Note, that setting annex-dead is independent of
                    # symlinking .git/annex. It might still make sense to
                    # have an ephemeral clone that doesn't propagate its avail.
                    # info. Therefore don't fail altogether.
                    lgr.warning("reckless=ephemeral mode: origin doesn't seem "
                                "local: %s\nno symlinks being used",
                                origin_annex_url)
            if origin_git_path:
                # TODO make sure that we do not delete any unique data
                rmtree(str(annex_dir)) \
                    if not annex_dir.is_symlink() else annex_dir.unlink()
                annex_dir.symlink_to(origin_git_path / 'annex',
                                     target_is_directory=True)
        else:
            # TODO: What level? + note, that annex-dead is independ
            lgr.warning("reckless=ephemeral mode: Unable to create symlinks on "
                        "this file system.")

    if reckless:
        # we successfully dealt with reckless here.
        # store the reckless setting in the dataset to make it
        # known to later clones of subdatasets via get()
        ds.config.set(
            'datalad.clone.reckless', reckless,
            where='local',
            reload=True)

    srs = {True: [], False: []}  # special remotes by "autoenable" key
    remote_uuids = None  # might be necessary to discover known UUIDs

    # Note: The purpose of this function is to inform the user. So if something
    # looks misconfigured, we'll warn and move on to the next item.
    for uuid, config in repo.get_special_remotes().items():
        sr_name = config.get('name', None)
        if sr_name is None:
            lgr.warning(
                'Ignoring special remote %s because it does not have a name. '
                'Known information: %s',
                uuid, config)
            continue
        sr_autoenable = config.get('autoenable', False)
        try:
            sr_autoenable = assure_bool(sr_autoenable)
        except ValueError:
            lgr.warning(
                'Failed to process "autoenable" value %r for sibling %s in '
                'dataset %s as bool.'
                'You might need to enable it later manually and/or fix it up to'
                ' avoid this message in the future.',
                sr_autoenable, sr_name, ds.path)
            continue

        # determine whether there is a registered remote with matching UUID
        if uuid:
            if remote_uuids is None:
                remote_uuids = {
                    # Check annex-config-uuid first. For sameas annex remotes,
                    # this will point to the UUID for the configuration (i.e.
                    # the key returned by get_special_remotes) rather than the
                    # shared UUID.
                    (repo.config.get('remote.%s.annex-config-uuid' % r) or
                     repo.config.get('remote.%s.annex-uuid' % r))
                    for r in repo.get_remotes()
                }
            if uuid not in remote_uuids:
                srs[sr_autoenable].append(sr_name)

    if srs[True]:
        lgr.debug(
            "configuration for %s %s added because of autoenable,"
            " but no UUIDs for them yet known for dataset %s",
            # since we are only at debug level, we could call things their
            # proper names
            single_or_plural("special remote",
                             "special remotes", len(srs[True]), True),
            ", ".join(srs[True]),
            ds.path
        )

    if srs[False]:
        # if has no auto-enable special remotes
        lgr.info(
            'access to %s %s not auto-enabled, enable with:\n'
            '\t\tdatalad siblings -d "%s" enable -s %s',
            # but since humans might read it, we better confuse them with our
            # own terms!
            single_or_plural("dataset sibling",
                             "dataset siblings", len(srs[False]), True),
            ", ".join(srs[False]),
            ds.path,
            srs[False][0] if len(srs[False]) == 1 else "SIBLING",
        )

    # we have just cloned the repo, so it has 'origin', configure any
    # reachable origin of origins
    yield from configure_origins(ds, ds)


_handle_possible_annex_dataset = postclonecfg_annexdataset


def configure_origins(cfgds, probeds, label=None):
    """Configure any discoverable local dataset 'origin' sibling as a remote

    Parameters
    ----------
    cfgds : Dataset
      Dataset to receive the remote configurations
    probeds : Dataset
      Dataset to start looking for 'origin' remotes. May be identical with
      `cfgds`.
    label : int, optional
      Each discovered 'origin' will be configured as a remote under the name
      'origin-<label>'. If no label is given, '2' will be used by default,
      given that there is typically a 'origin' remote already.
    """
    if label is None:
        label = 1
    # let's look at the URL for that remote and see if it is a local
    # dataset
    origin_url = probeds.config.get('remote.origin.url')
    if not origin_url:
        # no origin, nothing to do
        return
    if not cfgds.config.obtain(
            'datalad.install.inherit-local-origin',
            default=True):
        # no inheritance wanted
        return
    if not isinstance(RI(origin_url), PathRI):
        # not local path
        return

    # no need to reconfigure original/direct origin again
    if cfgds != probeds:
        # prevent duplicates
        known_remote_urls = set(
            cfgds.config.get(r + '.url', None)
            for r in cfgds.config.sections()
            if r.startswith('remote.')
        )
        if origin_url not in known_remote_urls:
            yield from cfgds.siblings(
                'configure',
                # no chance for conflict, can only be the second configured
                # remote
                name='origin-{}'.format(label),
                url=origin_url,
                # fetch to get all annex info
                fetch=True,
                result_renderer='disabled',
                on_failure='ignore',
            )
    # and dive deeper
    # given the clone source is a local dataset, we can have a
    # cheap look at it, and configure its own 'origin' as a remote
    # (if there is any), and benefit from additional annex availability
    yield from configure_origins(
        cfgds,
        Dataset(probeds.pathobj / origin_url),
        label=label + 1)


def _get_tracking_source(ds):
    """Returns name and url of a potential configured source
    tracking remote"""
    vcs = ds.repo
    # if we have a remote, let's check the location of that remote
    # for the presence of the desired submodule

    remote_name, tracking_branch = vcs.get_tracking_branch()
    if not remote_name and isinstance(vcs, AnnexRepo):
        # maybe cloned from a source repo that was in adjusted mode
        # https://github.com/datalad/datalad/issues/3969
        remote_name, tracking_branch = vcs.get_tracking_branch(
            corresponding=False)
    # TODO: better default `None`? Check where we might rely on '':
    remote_url = ''
    if remote_name:
        remote_url = vcs.get_remote_url(remote_name, push=False)

    return remote_name, remote_url


def _get_installationpath_from_url(url):
    """Returns a relative path derived from the trailing end of a URL

    This can be used to determine an installation path of a Dataset
    from a URL, analog to what `git clone` does.
    """
    ri = RI(url)
    if isinstance(ri, (URL, DataLadRI)):  # decode only if URL
        path = ri.path.rstrip('/')
        path = urlunquote(path) if path else ri.hostname
        if '/' in path:
            path = path.split('/')
            if path[-1] == '.git':
                path = path[-2]
            else:
                path = path[-1]
    else:
        path = Path(url).parts[-1]
    if path.endswith('.git'):
        path = path[:-4]
    return path


def decode_source_spec(spec, cfg=None):
    """Decode information from a clone source specification

    Parameters
    ----------
    spec : str
      Any supported clone source specification
    cfg : ConfigManager, optional
      Configuration will be queried from the instance (i.e. from a particular
      dataset). If None is given, the global DataLad configuration will be
      queried.

    Returns
    -------
    dict
      The value of each decoded property is stored under its own key in this
      dict. By default the following keys are return: 'type', a specification
      type label {'giturl', 'dataladri', 'ria'}; 'source' the original
      source specification; 'giturl' a URL for the source that is a suitable
      source argument for git-clone; 'version' a version-identifer, if present
      (None else); 'default_destpath' a relative path that that can be used as
      a clone destination.
    """
    if cfg is None:
        from datalad import cfg
    # standard property dict composition
    props = dict(
        source=spec,
        version=None,
    )

    # Git never gets to see these URLs, so let's manually apply any
    # rewrite configuration Git might know about.
    # Note: We need to rewrite before parsing, otherwise parsing might go wrong.
    # This is particularly true for insteadOf labels replacing even the URL
    # scheme.
    spec = cfg.rewrite_url(spec)
    # common starting point is a RI instance, support for accepting an RI
    # instance is kept for backward-compatibility reasons
    source_ri = RI(spec) if not isinstance(spec, RI) else spec

    # scenario switch, each case must set 'giturl' at the very minimum
    if isinstance(source_ri, DataLadRI):
        # we have got our DataLadRI as the source, so expand it
        props['type'] = 'dataladri'
        props['giturl'] = source_ri.as_git_url()
    elif isinstance(source_ri, URL) and source_ri.scheme.startswith('ria+'):
        # parse a RIA URI
        dsid, version = source_ri.fragment.split('@', maxsplit=1) \
            if '@' in source_ri.fragment else (source_ri.fragment, None)
        uuid_regex = r'[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}'
        if not re.match(uuid_regex, dsid):
            raise ValueError('RIA URI does not contain a valid dataset ID: {}'.format(spec))
        # now we cancel the fragment in the original URL, but keep everthing else
        # in order to be able to support the various combinations of ports, paths,
        # and everything else
        source_ri.fragment = ''
        # strip the custom protocol and go with standard one
        source_ri.scheme = source_ri.scheme[4:]
        # take any existing path, and add trace to dataset within the store
        source_ri.path = '{urlpath}{urldelim}{trace}'.format(
            urlpath=source_ri.path if source_ri.path else '',
            urldelim='' if not source_ri.path or source_ri.path.endswith('/') else '/',
            trace='{}/{}'.format(dsid[:3], dsid[3:]),
        )
        props.update(
            type='ria',
            giturl=str(source_ri),
            version=version,
            default_destpath=dsid,
        )
    else:
        # let's assume that anything else is a URI that Git can handle
        props['type'] = 'giturl'
        # use original input verbatim
        props['giturl'] = spec

    if 'default_destpath' not in props:
        # if we still have no good idea on where a dataset could be cloned to if no
        # path was given, do something similar to git clone and derive the path from
        # the source
        props['default_destpath'] = _get_installationpath_from_url(props['giturl'])

    return props

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]
**Title:** `decode_source_spec` Fails to Handle Dataset Aliases in RIA URIs

**Description:**
When attempting to decode a RIA URI that includes a dataset alias, the `decode_source_spec` function raises a `ValueError` instead of successfully parsing the alias. This prevents the proper installation of datasets identified by their aliases.

**Example Code:**
```python
source = 'ria+http://store.datalad.org#~hcp-openaccess'
result = decode_source_spec(source)
```

**Expected Behavior:**
The function should return a dictionary with the parsed details, correctly handling the alias. For example:
```python
{
    'source': 'ria+http://store.datalad.org#~hcp-openaccess',
    'version': None,
    'type': 'ria',
    'giturl': 'http://store.datalad.org/alias/hcp-openaccess',
    'default_destpath': 'hcp-openaccess'
}
```

**Actual Behavior:**
Instead of returning the expected dictionary, the function raises the following error:
```
ValueError: RIA URI does not contain a valid dataset ID: ria+http://store.datalad.org#~hcp-openaccess
```
This error occurs because the function does not recognize the alias format starting with `~`, leading to an inability to handle dataset aliases properly.
[/ISSUE]
{
    "test_installationpath_from_url": "PASSED",
    "test_decode_source_spec": "PASSED",
    "test_invalid_args": "ERROR",
    "test_clone_crcns": "ERROR",
    "test_clone_datasets_root": "ERROR",
    "test_clone_simple_local": "ERROR",
    "test_clone_dataset_from_just_source": "ERROR",
    "test_clone_dataladri": "ERROR",
    "test_clone_isnot_recursive": "ERROR",
    "test_clone_into_dataset": "ERROR",
    "test_notclone_known_subdataset": "ERROR",
    "test_failed_clone": "ERROR",
    "test_reckless": "ERROR",
    "test_install_source_relpath": "ERROR",
    "test_clone_isnt_a_smartass": "ERROR",
    "test_clone_report_permission_issue": "ERROR",
    "test_clone_autoenable_msg_handles_sameas": "ERROR",
    "test_expanduser": "ERROR",
    "test_local_url_with_fetch": "ERROR",
    "test_ria_http": "ERROR",
    "test_inherit_src_candidates": "ERROR",
    "test_ephemeral": "ERROR",
    "test_autoenabled_remote_msg": "FAILED",
    "test_cfg_originorigin": "FAILED",
    "test_ria_http_storedataladorg": "FAILED",
    "test_clone_unborn_head": "FAILED",
    "test_clone_unborn_head_no_other_ref": "FAILED",
    "test_clone_unborn_head_sub": "FAILED",
    "test_gin_cloning": "FAILED"
}
diff --git a/datalad/core/distributed/clone.py b/datalad/core/distributed/clone.py
index e84f8f1d6..41e2dce9f 100644
--- a/datalad/core/distributed/clone.py
+++ b/datalad/core/distributed/clone.py
@@ -141,9 +141,9 @@ class Clone(Interface):
         dict(text="Install the main superdataset from datasets.datalad.org",
              code_py="clone(source='///')",
              code_cmd="datalad clone ///"),
-        dict(text="Install a dataset identified by its ID from store.datalad.org",
-             code_py="clone(source='ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561')",
-             code_cmd="datalad clone ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561"),
+        dict(text="Install a dataset identified by a literal alias from store.datalad.org",
+             code_py="clone(source='ria+http://store.datalad.org#~hcp-openaccess')",
+             code_cmd="datalad clone ria+http://store.datalad.org#~hcp-openaccess"),
         dict(
             text="Install a dataset in a specific version as identified by a"
                  "branch or tag name from store.datalad.org",
@@ -926,8 +926,16 @@ def decode_source_spec(spec, cfg=None):
         dsid, version = source_ri.fragment.split('@', maxsplit=1) \
             if '@' in source_ri.fragment else (source_ri.fragment, None)
         uuid_regex = r'[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}'
-        if not re.match(uuid_regex, dsid):
-            raise ValueError('RIA URI does not contain a valid dataset ID: {}'.format(spec))
+        if re.match(uuid_regex, dsid):
+            trace = '{}/{}'.format(dsid[:3], dsid[3:])
+            default_destpath = dsid
+        elif dsid.startswith('~'):
+            trace = 'alias/{}'.format(dsid[1:])
+            default_destpath = dsid[1:]
+        else:
+            raise ValueError(
+                'RIA URI not recognized, no valid dataset ID or other supported '
+                'scheme: {}'.format(spec))
         # now we cancel the fragment in the original URL, but keep everthing else
         # in order to be able to support the various combinations of ports, paths,
         # and everything else
@@ -938,13 +946,13 @@ def decode_source_spec(spec, cfg=None):
         source_ri.path = '{urlpath}{urldelim}{trace}'.format(
             urlpath=source_ri.path if source_ri.path else '',
             urldelim='' if not source_ri.path or source_ri.path.endswith('/') else '/',
-            trace='{}/{}'.format(dsid[:3], dsid[3:]),
+            trace=trace,
         )
         props.update(
             type='ria',
             giturl=str(source_ri),
             version=version,
-            default_destpath=dsid,
+            default_destpath=default_destpath,
         )
     else:
         # let's assume that anything else is a URI that Git can handle
diff --git a/datalad/distributed/create_sibling_ria.py b/datalad/distributed/create_sibling_ria.py
index a9ae43afd..b4d49e682 100644
--- a/datalad/distributed/create_sibling_ria.py
+++ b/datalad/distributed/create_sibling_ria.py
@@ -108,6 +108,11 @@ class CreateSiblingRia(Interface):
     located. At present, this file must contain a single line stating the
     version (currently "1"). This line MUST end with a newline character.
 
+    It is possible to define an alias for an individual dataset in a store by
+    placing a symlink to the dataset location into an 'alias/' directory
+    in the root of the store. This enables dataset access via URLs of format:
+    'ria+<protocol>://<storelocation>#~<aliasname>'.
+
     Error logging
     ~~~~~~~~~~~~~
 
 

{"datalad/core/distributed/clone.py": "# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-\n# ex: set sts=4 ts=4 sw=4 noet:\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n#   See COPYING file distributed along with the datalad package for the\n#   copyright and license terms.\n#\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n\"\"\"Plumbing command for dataset installation\"\"\"\n\n\nimport logging\nimport re\nfrom os.path import expanduser\nfrom collections import OrderedDict\nfrom urllib.parse import unquote as urlunquote\n\nfrom datalad.interface.base import Interface\nfrom datalad.interface.utils import eval_results\nfrom datalad.interface.base import build_doc\nfrom datalad.interface.results import get_status_dict\nfrom datalad.interface.common_opts import (\n    location_description,\n    reckless_opt,\n)\nfrom datalad.log import log_progress\nfrom datalad.support.gitrepo import (\n    GitRepo,\n)\nfrom datalad.cmd import (\n    CommandError,\n)\nfrom datalad.support.annexrepo import AnnexRepo\nfrom datalad.support.constraints import (\n    EnsureNone,\n    EnsureStr,\n    EnsureKeyChoice,\n)\nfrom datalad.support.param import Parameter\nfrom datalad.support.network import (\n    get_local_file_url,\n    URL,\n    RI,\n    DataLadRI,\n    PathRI,\n)\nfrom datalad.dochelpers import (\n    exc_str,\n    single_or_plural,\n)\nfrom datalad.utils import (\n    rmtree,\n    assure_bool,\n    knows_annex,\n    Path,\n)\n\nfrom datalad.distribution.dataset import (\n    Dataset,\n    datasetmethod,\n    resolve_path,\n    require_dataset,\n    EnsureDataset,\n)\nfrom datalad.distribution.utils import (\n    _get_flexible_source_candidates,\n)\nfrom datalad.utils import (\n    check_symlink_capability\n)\n\n__docformat__ = 'restructuredtext'\n\nlgr = logging.getLogger('datalad.core.distributed.clone')\n\n\n@build_doc\nclass Clone(Interface):\n    \"\"\"Obtain a dataset (copy) from a URL or local directory\n\n    The purpose of this command is to obtain a new clone (copy) of a dataset\n    and place it into a not-yet-existing or empty directory. As such `clone`\n    provides a strict subset of the functionality offered by `install`. Only a\n    single dataset can be obtained, and immediate recursive installation of\n    subdatasets is not supported. However, once a (super)dataset is installed\n    via `clone`, any content, including subdatasets can be obtained by a\n    subsequent `get` command.\n\n    Primary differences over a direct `git clone` call are 1) the automatic\n    initialization of a dataset annex (pure Git repositories are equally\n    supported); 2) automatic registration of the newly obtained dataset as a\n    subdataset (submodule), if a parent dataset is specified; 3) support\n    for additional resource identifiers (DataLad resource identifiers as used\n    on datasets.datalad.org, and RIA store URLs as used for store.datalad.org\n    - optionally in specific versions as identified by a branch or a tag; see\n    examples); and 4) automatic configurable generation of alternative access\n    URL for common cases (such as appending '.git' to the URL in case the\n    accessing the base URL failed).\n\n    || PYTHON >>By default, the command returns a single Dataset instance for\n    an installed dataset, regardless of whether it was newly installed ('ok'\n    result), or found already installed from the specified source ('notneeded'\n    result).<< PYTHON ||\n\n    .. seealso::\n\n      :ref:`handbook:3-001`\n        More information on Remote Indexed Archive (RIA) stores\n    \"\"\"\n    # by default ignore everything but install results\n    # i.e. no \"add to super dataset\"\n    result_filter = EnsureKeyChoice('action', ('install',))\n    # very frequently this command will yield exactly one installed dataset\n    # spare people the pain of going through a list by default\n    return_type = 'item-or-list'\n    # as discussed in #1409 and #1470, we want to return dataset instances\n    # matching what is actually available after command completion (and\n    # None for any failed dataset installation)\n    result_xfm = 'successdatasets-or-none'\n\n    _examples_ = [\n        dict(text=\"Install a dataset from Github into the current directory\",\n             code_py=\"clone(\"\n             \"source='https://github.com/datalad-datasets/longnow\"\n             \"-podcasts.git')\",\n             code_cmd=\"datalad clone \"\n             \"https://github.com/datalad-datasets/longnow-podcasts.git\"),\n        dict(text=\"Install a dataset into a specific directory\",\n             code_py=\"\"\"\\\n             clone(source='https://github.com/datalad-datasets/longnow-podcasts.git',\n                   path='myfavpodcasts')\"\"\",\n             code_cmd=\"\"\"\\\n             datalad clone https://github.com/datalad-datasets/longnow-podcasts.git \\\\\n             myfavpodcasts\"\"\"),\n        dict(text=\"Install a dataset as a subdataset into the current dataset\",\n             code_py=\"\"\"\\\n             clone(dataset='.',\n                   source='https://github.com/datalad-datasets/longnow-podcasts.git')\"\"\",\n             code_cmd=\"datalad clone -d . \"\n             \"https://github.com/datalad-datasets/longnow-podcasts.git\"),\n        dict(text=\"Install the main superdataset from datasets.datalad.org\",\n             code_py=\"clone(source='///')\",\n             code_cmd=\"datalad clone ///\"),\n        dict(text=\"Install a dataset identified by its ID from store.datalad.org\",\n             code_py=\"clone(source='ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561')\",\n             code_cmd=\"datalad clone ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561\"),\n        dict(\n            text=\"Install a dataset in a specific version as identified by a\"\n                 \"branch or tag name from store.datalad.org\",\n            code_py=\"clone(source='ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561@myidentifier')\",\n            code_cmd=\"datalad clone ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561@myidentifier\"),\n        dict(\n            text=\"Install a dataset with group-write access permissions\",\n            code_py=\\\n            \"clone(source='http://example.com/dataset', reckless='shared-group')\",\n            code_cmd=\\\n            \"datalad clone http://example.com/dataset --reckless shared-group\"),\n    ]\n\n    _params_ = dict(\n        dataset=Parameter(\n            args=(\"-d\", \"--dataset\"),\n            doc=\"\"\"(parent) dataset to clone into. If given, the newly cloned\n            dataset is registered as a subdataset of the parent. Also, if given,\n            relative paths are interpreted as being relative to the parent\n            dataset, and not relative to the working directory.\"\"\",\n            constraints=EnsureDataset() | EnsureNone()),\n        source=Parameter(\n            args=(\"source\",),\n            metavar='SOURCE',\n            doc=\"\"\"URL, DataLad resource identifier, local path or instance of\n            dataset to be cloned\"\"\",\n            constraints=EnsureStr() | EnsureNone()),\n        path=Parameter(\n            args=(\"path\",),\n            metavar='PATH',\n            nargs=\"?\",\n            doc=\"\"\"path to clone into.  If no `path` is provided a\n            destination path will be derived from a source URL\n            similar to :command:`git clone`\"\"\"),\n        description=location_description,\n        reckless=reckless_opt,\n    )\n\n    @staticmethod\n    @datasetmethod(name='clone')\n    @eval_results\n    def __call__(\n            source,\n            path=None,\n            dataset=None,\n            description=None,\n            reckless=None):\n        # did we explicitly get a dataset to install into?\n        # if we got a dataset, path will be resolved against it.\n        # Otherwise path will be resolved first.\n        ds = require_dataset(\n            dataset, check_installed=True, purpose='cloning') \\\n            if dataset is not None else dataset\n        refds_path = ds.path if ds else None\n\n        # legacy compatibility\n        if reckless is True:\n            # so that we can forget about how things used to be\n            reckless = 'auto'\n        if reckless is None and ds:\n            # if reckless is not explicitly given, but we operate on a\n            # superdataset, query whether it has been instructed to operate\n            # in a reckless mode, and inherit it for the coming clone\n            reckless = ds.config.get('datalad.clone.reckless', None)\n\n        if isinstance(source, Dataset):\n            source = source.path\n\n        if source == path:\n            # even if they turn out to be identical after resolving symlinks\n            # and more sophisticated witchcraft, it would still happily say\n            # \"it appears to be already installed\", so we just catch an\n            # obviously pointless input combination\n            raise ValueError(\n                \"clone `source` and destination `path` are identical [{}]. \"\n                \"If you are trying to add a subdataset simply use `save`\".format(\n                    path))\n\n        if path is not None:\n            path = resolve_path(path, dataset)\n\n        # derive target from source:\n        if path is None:\n            # we got nothing but a source. do something similar to git clone\n            # and derive the path from the source and continue\n            # since this is a relative `path`, resolve it:\n            # we are not going to reuse the decoded URL, as this is done for\n            # all source candidates in clone_dataset(), we just use to determine\n            # a destination path here in order to perform a bunch of additional\n            # checks that shall not pollute the helper function\n            source_ = decode_source_spec(\n                source, cfg=None if ds is None else ds.config)\n            path = resolve_path(source_['default_destpath'], dataset)\n            lgr.debug(\"Determined clone target path from source\")\n        lgr.debug(\"Resolved clone target path to: '%s'\", path)\n\n        # there is no other way -- my intoxicated brain tells me\n        assert(path is not None)\n\n        result_props = dict(\n            action='install',\n            logger=lgr,\n            refds=refds_path,\n            source_url=source)\n\n        try:\n            # this will implicitly cause pathlib to run a bunch of checks\n            # whether the present path makes any sense on the platform\n            # we are running on -- we don't care if the path actually\n            # exists at this point, but we want to abort early if the path\n            # spec is determined to be useless\n            path.exists()\n        except OSError as e:\n            yield get_status_dict(\n                status='error',\n                path=path,\n                message=('cannot handle target path: %s', exc_str(e)),\n                **result_props)\n            return\n\n        destination_dataset = Dataset(path)\n        result_props['ds'] = destination_dataset\n\n        if ds is not None and ds.pathobj not in path.parents:\n            yield get_status_dict(\n                status='error',\n                message=(\"clone target path '%s' not in specified target dataset '%s'\",\n                         path, ds),\n                **result_props)\n            return\n\n        # perform the actual cloning operation\n        yield from clone_dataset(\n            [source],\n            destination_dataset,\n            reckless,\n            description,\n            result_props,\n            cfg=None if ds is None else ds.config,\n        )\n\n        # TODO handle any 'version' property handling and verification using a dedicated\n        # public helper\n\n        if ds is not None:\n            # we created a dataset in another dataset\n            # -> make submodule\n            for r in ds.save(\n                    path,\n                    return_type='generator',\n                    result_filter=None,\n                    result_xfm=None,\n                    on_failure='ignore'):\n                yield r\n\n\ndef clone_dataset(\n        srcs,\n        destds,\n        reckless=None,\n        description=None,\n        result_props=None,\n        cfg=None):\n    \"\"\"Internal helper to perform cloning without sanity checks (assumed done)\n\n    This helper does not handle any saving of subdataset modification or adding\n    in a superdataset.\n\n    Parameters\n    ----------\n    srcs : list\n      Any suitable clone source specifications (paths, URLs)\n    destds : Dataset\n      Dataset instance for the clone destination\n    reckless : {None, 'auto', 'ephemeral', 'shared-...'}, optional\n      Mode switch to put cloned dataset into unsafe/throw-away configurations, i.e.\n      sacrifice data safety for performance or resource footprint.\n    description : str, optional\n      Location description for the annex of the dataset clone (if there is any).\n    result_props : dict, optional\n      Default properties for any yielded result, passed on to get_status_dict().\n    cfg : ConfigManager, optional\n      Configuration will be queried from this instance (i.e. from a particular\n      dataset). If None is given, the global DataLad configuration will be\n      queried.\n\n    Yields\n    ------\n    dict\n      DataLad result records\n    \"\"\"\n    if not result_props:\n        # in case the caller had no specific idea on how results should look\n        # like, provide sensible defaults\n        result_props = dict(\n            action='install',\n            logger=lgr,\n            ds=destds,\n        )\n\n    dest_path = destds.pathobj\n\n    # decode all source candidate specifications\n    candidate_sources = [decode_source_spec(s, cfg=cfg) for s in srcs]\n\n    # now expand the candidate sources with additional variants of the decoded\n    # giturl, while duplicating the other properties in the additional records\n    # for simplicity. The hope is to overcome a few corner cases and be more\n    # robust than git clone\n    candidate_sources = [\n        dict(props, giturl=s) for props in candidate_sources\n        for s in _get_flexible_source_candidates(props['giturl'])\n    ]\n\n    # important test! based on this `rmtree` will happen below after failed clone\n    dest_path_existed = dest_path.exists()\n    if dest_path_existed and any(dest_path.iterdir()):\n        if destds.is_installed():\n            # check if dest was cloned from the given source before\n            # this is where we would have installed this from\n            # this is where it was actually installed from\n            track_name, track_url = _get_tracking_source(destds)\n            try:\n                # this will get us track_url in system native path conventions,\n                # whenever it is a path (and not a URL)\n                # this is needed to match it to any potentially incoming local\n                # source path in the 'notneeded' test below\n                track_path = str(Path(track_url))\n            except Exception:\n                # this should never happen, because Path() will let any non-path stringification\n                # pass through unmodified, but we do not want any potential crash due to\n                # pathlib behavior changes\n                lgr.debug(\"Unexpected behavior of pathlib!\")\n                track_path = None\n            for cand in candidate_sources:\n                src = cand['giturl']\n                if track_url == src \\\n                        or get_local_file_url(track_url, compatibility='git') == src \\\n                        or track_path == expanduser(src):\n                    yield get_status_dict(\n                        status='notneeded',\n                        message=(\"dataset %s was already cloned from '%s'\",\n                                 destds,\n                                 src),\n                        **result_props)\n                    return\n        # anything else is an error\n        yield get_status_dict(\n            status='error',\n            message='target path already exists and not empty, refuse to clone into target path',\n            **result_props)\n        return\n\n    log_progress(\n        lgr.info,\n        'cloneds',\n        'Cloning dataset to %s', destds,\n        total=len(candidate_sources),\n        label='Clone attempt',\n        unit=' Candidate locations',\n    )\n    error_msgs = OrderedDict()  # accumulate all error messages formatted per each url\n    for cand in candidate_sources:\n        log_progress(\n            lgr.info,\n            'cloneds',\n            'Attempting to clone from %s to %s', cand['giturl'], dest_path,\n            update=1,\n            increment=True)\n\n        clone_opts = {}\n\n        if cand.get('version', None):\n            clone_opts['branch'] = cand['version']\n        try:\n            # TODO for now GitRepo.clone() cannot handle Path instances, and PY35\n            # doesn't make it happen seemlessly\n            GitRepo.clone(\n                path=str(dest_path),\n                url=cand['giturl'],\n                clone_options=clone_opts,\n                create=True)\n\n        except CommandError as e:\n            e_stderr = e.stderr\n\n            error_msgs[cand['giturl']] = e\n            lgr.debug(\"Failed to clone from URL: %s (%s)\",\n                      cand['giturl'], exc_str(e))\n            if dest_path.exists():\n                lgr.debug(\"Wiping out unsuccessful clone attempt at: %s\",\n                          dest_path)\n                # We must not just rmtree since it might be curdir etc\n                # we should remove all files/directories under it\n                # TODO stringification can be removed once patlib compatible\n                # or if PY35 is no longer supported\n                rmtree(str(dest_path), children_only=dest_path_existed)\n\n            if 'could not create work tree' in e_stderr.lower():\n                # this cannot be fixed by trying another URL\n                re_match = re.match(r\".*fatal: (.*)$\", e_stderr,\n                                    flags=re.MULTILINE | re.DOTALL)\n                # cancel progress bar\n                log_progress(\n                    lgr.info,\n                    'cloneds',\n                    'Completed clone attempts for %s', destds\n                )\n                yield get_status_dict(\n                    status='error',\n                    message=re_match.group(1).strip()\n                    if re_match else \"stderr: \" + e_stderr,\n                    **result_props)\n                return\n            # next candidate\n            continue\n\n        result_props['source'] = cand\n        # do not bother with other sources if succeeded\n        break\n\n    log_progress(\n        lgr.info,\n        'cloneds',\n        'Completed clone attempts for %s', destds\n    )\n\n    if not destds.is_installed():\n        if len(error_msgs):\n            if all(not e.stdout and not e.stderr for e in error_msgs.values()):\n                # there is nothing we can learn from the actual exception,\n                # the exit code is uninformative, the command is predictable\n                error_msg = \"Failed to clone from all attempted sources: %s\"\n                error_args = list(error_msgs.keys())\n            else:\n                error_msg = \"Failed to clone from any candidate source URL. \" \\\n                            \"Encountered errors per each url were:\\n- %s\"\n                error_args = '\\n- '.join(\n                    '{}\\n  {}'.format(url, exc_str(exc))\n                    for url, exc in error_msgs.items()\n                )\n        else:\n            # yoh: Not sure if we ever get here but I felt that there could\n            #      be a case when this might happen and original error would\n            #      not be sufficient to troubleshoot what is going on.\n            error_msg = \"Awkward error -- we failed to clone properly. \" \\\n                        \"Although no errors were encountered, target \" \\\n                        \"dataset at %s seems to be not fully installed. \" \\\n                        \"The 'succesful' source was: %s\"\n            error_args = (destds.path, cand['giturl'])\n        yield get_status_dict(\n            status='error',\n            message=(error_msg, error_args),\n            **result_props)\n        return\n\n    if not cand.get(\"version\"):\n        postclone_check_head(destds)\n\n    # act on --reckless=shared-...\n    # must happen prior git-annex-init, where we can cheaply alter the repo\n    # setup through safe re-init'ing\n    if reckless and reckless.startswith('shared-'):\n        lgr.debug('Reinit %s to enable shared access permissions', destds)\n        destds.repo.call_git(['init', '--shared={}'.format(reckless[7:])])\n\n    yield from postclonecfg_annexdataset(\n        destds,\n        reckless,\n        description)\n\n    # perform any post-processing that needs to know details of the clone\n    # source\n    if result_props['source']['type'] == 'ria':\n        yield from postclonecfg_ria(destds, result_props['source'])\n\n    # yield successful clone of the base dataset now, as any possible\n    # subdataset clone down below will not alter the Git-state of the\n    # parent\n    yield get_status_dict(status='ok', **result_props)\n\n\ndef postclone_check_head(ds):\n    repo = ds.repo\n    if not repo.commit_exists(\"HEAD\"):\n        # HEAD points to an unborn branch. A likely cause of this is that the\n        # remote's main branch is something other than master but HEAD wasn't\n        # adjusted accordingly.\n        #\n        # Let's choose the most recently updated remote ref (according to\n        # commit date). In the case of a submodule, switching to a ref with\n        # commits prevents .update_submodule() from failing. It is likely that\n        # the ref includes the registered commit, but we don't have the\n        # information here to know for sure. If it doesn't, .update_submodule()\n        # will check out a detached HEAD.\n        remote_branches = (\n            b[\"refname:strip=2\"] for b in repo.for_each_ref_(\n                fields=\"refname:strip=2\", sort=\"-committerdate\",\n                pattern=\"refs/remotes/origin\"))\n        for rbranch in remote_branches:\n            if rbranch in [\"origin/git-annex\", \"HEAD\"]:\n                continue\n            repo.call_git([\"checkout\", \"-b\", rbranch[7:],  # drop \"origin/\"\n                           \"--track\", rbranch])\n            lgr.debug(\"Checked out local branch from %s\", rbranch)\n            return\n        lgr.warning(\"Cloned %s but could not find a branch \"\n                    \"with commits\", ds.path)\n\n\ndef postclonecfg_ria(ds, props):\n    \"\"\"Configure a dataset freshly cloned from a RIA store\"\"\"\n    # RIA uses hashdir mixed, copying data to it via git-annex (if cloned via\n    # ssh) would make it see a bare repo and establish a hashdir lower annex\n    # object tree.\n    # Moreover, we want the RIA remote to receive all data for the store, so its\n    # objects could be moved into archives (the main point of a RIA store).\n    ds.config.set(\n        'remote.origin.annex-ignore', 'true',\n        where='local')\n\n    # chances are that if this dataset came from a RIA store, its subdatasets\n    # may live there too. Place a subdataset source candidate config that makes\n    # get probe this RIA store when obtaining subdatasets\n    ds.config.set(\n        # we use the label 'origin' for this candidate in order to not have to\n        # generate a complicated name from the actual source specification\n        'datalad.get.subdataset-source-candidate-origin',\n        # use the entire original URL, up to the fragment + plus dataset ID\n        # placeholder, this should make things work with any store setup we\n        # support (paths, ports, ...)\n        props['source'].split('#', maxsplit=1)[0] + '#{id}',\n        where='local')\n\n    # setup publication dependency, if a corresponding special remote exists\n    # and was enabled (there could be RIA stores that actually only have repos)\n    # make this function be a generator\n    ria_remotes = [s for s in ds.siblings('query', result_renderer='disabled')\n                   if s.get('annex-externaltype', None) == 'ora'\n    ]\n    if not ria_remotes:\n        lgr.debug(\"Found no RIA special remote\")\n    elif len(ria_remotes) == 1:\n        yield from ds.siblings('configure',\n                               name='origin',\n                               publish_depends=ria_remotes[0]['name'],\n                               result_filter=None,\n                               result_renderer='disabled')\n    else:\n        lgr.warning(\"Found multiple RIA remotes. Couldn't decide which \"\n                    \"publishing to origin should depend on: %s\",\n                    [r['name'] for r in ria_remotes])\n\n\ndef postclonecfg_annexdataset(ds, reckless, description=None):\n    \"\"\"If ds \"knows annex\" -- annex init it, set into reckless etc\n\n    Provides additional tune up to a possibly an annex repo, e.g.\n    \"enables\" reckless mode, sets up description\n    \"\"\"\n    # in any case check whether we need to annex-init the installed thing:\n    if not knows_annex(ds.path):\n        # not for us\n        return\n\n    # init annex when traces of a remote annex can be detected\n    if reckless == 'auto':\n        lgr.debug(\n            \"Instruct annex to hardlink content in %s from local \"\n            \"sources, if possible (reckless)\", ds.path)\n        ds.config.set(\n            'annex.hardlink', 'true', where='local', reload=True)\n\n    lgr.debug(\"Initializing annex repo at %s\", ds.path)\n    # Note, that we cannot enforce annex-init via AnnexRepo().\n    # If such an instance already exists, its __init__ will not be executed.\n    # Therefore do quick test once we have an object and decide whether to call\n    # its _init().\n    #\n    # Additionally, call init if we need to add a description (see #1403),\n    # since AnnexRepo.__init__ can only do it with create=True\n    repo = AnnexRepo(ds.path, init=True)\n    if not repo.is_initialized() or description:\n        repo._init(description=description)\n    if reckless == 'auto' or (reckless and reckless.startswith('shared-')):\n        repo._run_annex_command('untrust', annex_options=['here'])\n\n    elif reckless == 'ephemeral':\n        # with ephemeral we declare 'here' as 'dead' right away, whenever\n        # we symlink origin's annex, since availability from 'here' should\n        # not be propagated for an ephemeral clone when we publish back to\n        # origin.\n        # This will cause stuff like this for a locally present annexed file:\n        # % git annex whereis d1\n        # whereis d1 (0 copies) failed\n        # BUT this works:\n        # % git annex find . --not --in here\n        # % git annex find . --in here\n        # d1\n\n        # we don't want annex copy-to origin\n        ds.config.set(\n            'remote.origin.annex-ignore', 'true',\n            where='local')\n\n        ds.repo.set_remote_dead('here')\n\n        if check_symlink_capability(ds.repo.dot_git / 'dl_link_test',\n                                    ds.repo.dot_git / 'dl_target_test'):\n            # symlink the annex to avoid needless copies in an emphemeral clone\n            annex_dir = ds.repo.dot_git / 'annex'\n            origin_annex_url = ds.config.get(\"remote.origin.url\", None)\n            origin_git_path = None\n            if origin_annex_url:\n                try:\n                    # Deal with file:// scheme URLs as well as plain paths.\n                    # If origin isn't local, we have nothing to do.\n                    origin_git_path = Path(RI(origin_annex_url).localpath)\n                    if origin_git_path.name != '.git':\n                        origin_git_path /= '.git'\n                except ValueError:\n                    # Note, that accessing localpath on a non-local RI throws\n                    # ValueError rather than resulting in an AttributeError.\n                    # TODO: Warning level okay or is info level sufficient?\n                    # Note, that setting annex-dead is independent of\n                    # symlinking .git/annex. It might still make sense to\n                    # have an ephemeral clone that doesn't propagate its avail.\n                    # info. Therefore don't fail altogether.\n                    lgr.warning(\"reckless=ephemeral mode: origin doesn't seem \"\n                                \"local: %s\\nno symlinks being used\",\n                                origin_annex_url)\n            if origin_git_path:\n                # TODO make sure that we do not delete any unique data\n                rmtree(str(annex_dir)) \\\n                    if not annex_dir.is_symlink() else annex_dir.unlink()\n                annex_dir.symlink_to(origin_git_path / 'annex',\n                                     target_is_directory=True)\n        else:\n            # TODO: What level? + note, that annex-dead is independ\n            lgr.warning(\"reckless=ephemeral mode: Unable to create symlinks on \"\n                        \"this file system.\")\n\n    if reckless:\n        # we successfully dealt with reckless here.\n        # store the reckless setting in the dataset to make it\n        # known to later clones of subdatasets via get()\n        ds.config.set(\n            'datalad.clone.reckless', reckless,\n            where='local',\n            reload=True)\n\n    srs = {True: [], False: []}  # special remotes by \"autoenable\" key\n    remote_uuids = None  # might be necessary to discover known UUIDs\n\n    # Note: The purpose of this function is to inform the user. So if something\n    # looks misconfigured, we'll warn and move on to the next item.\n    for uuid, config in repo.get_special_remotes().items():\n        sr_name = config.get('name', None)\n        if sr_name is None:\n            lgr.warning(\n                'Ignoring special remote %s because it does not have a name. '\n                'Known information: %s',\n                uuid, config)\n            continue\n        sr_autoenable = config.get('autoenable', False)\n        try:\n            sr_autoenable = assure_bool(sr_autoenable)\n        except ValueError:\n            lgr.warning(\n                'Failed to process \"autoenable\" value %r for sibling %s in '\n                'dataset %s as bool.'\n                'You might need to enable it later manually and/or fix it up to'\n                ' avoid this message in the future.',\n                sr_autoenable, sr_name, ds.path)\n            continue\n\n        # determine whether there is a registered remote with matching UUID\n        if uuid:\n            if remote_uuids is None:\n                remote_uuids = {\n                    # Check annex-config-uuid first. For sameas annex remotes,\n                    # this will point to the UUID for the configuration (i.e.\n                    # the key returned by get_special_remotes) rather than the\n                    # shared UUID.\n                    (repo.config.get('remote.%s.annex-config-uuid' % r) or\n                     repo.config.get('remote.%s.annex-uuid' % r))\n                    for r in repo.get_remotes()\n                }\n            if uuid not in remote_uuids:\n                srs[sr_autoenable].append(sr_name)\n\n    if srs[True]:\n        lgr.debug(\n            \"configuration for %s %s added because of autoenable,\"\n            \" but no UUIDs for them yet known for dataset %s\",\n            # since we are only at debug level, we could call things their\n            # proper names\n            single_or_plural(\"special remote\",\n                             \"special remotes\", len(srs[True]), True),\n            \", \".join(srs[True]),\n            ds.path\n        )\n\n    if srs[False]:\n        # if has no auto-enable special remotes\n        lgr.info(\n            'access to %s %s not auto-enabled, enable with:\\n'\n            '\\t\\tdatalad siblings -d \"%s\" enable -s %s',\n            # but since humans might read it, we better confuse them with our\n            # own terms!\n            single_or_plural(\"dataset sibling\",\n                             \"dataset siblings\", len(srs[False]), True),\n            \", \".join(srs[False]),\n            ds.path,\n            srs[False][0] if len(srs[False]) == 1 else \"SIBLING\",\n        )\n\n    # we have just cloned the repo, so it has 'origin', configure any\n    # reachable origin of origins\n    yield from configure_origins(ds, ds)\n\n\n_handle_possible_annex_dataset = postclonecfg_annexdataset\n\n\ndef configure_origins(cfgds, probeds, label=None):\n    \"\"\"Configure any discoverable local dataset 'origin' sibling as a remote\n\n    Parameters\n    ----------\n    cfgds : Dataset\n      Dataset to receive the remote configurations\n    probeds : Dataset\n      Dataset to start looking for 'origin' remotes. May be identical with\n      `cfgds`.\n    label : int, optional\n      Each discovered 'origin' will be configured as a remote under the name\n      'origin-<label>'. If no label is given, '2' will be used by default,\n      given that there is typically a 'origin' remote already.\n    \"\"\"\n    if label is None:\n        label = 1\n    # let's look at the URL for that remote and see if it is a local\n    # dataset\n    origin_url = probeds.config.get('remote.origin.url')\n    if not origin_url:\n        # no origin, nothing to do\n        return\n    if not cfgds.config.obtain(\n            'datalad.install.inherit-local-origin',\n            default=True):\n        # no inheritance wanted\n        return\n    if not isinstance(RI(origin_url), PathRI):\n        # not local path\n        return\n\n    # no need to reconfigure original/direct origin again\n    if cfgds != probeds:\n        # prevent duplicates\n        known_remote_urls = set(\n            cfgds.config.get(r + '.url', None)\n            for r in cfgds.config.sections()\n            if r.startswith('remote.')\n        )\n        if origin_url not in known_remote_urls:\n            yield from cfgds.siblings(\n                'configure',\n                # no chance for conflict, can only be the second configured\n                # remote\n                name='origin-{}'.format(label),\n                url=origin_url,\n                # fetch to get all annex info\n                fetch=True,\n                result_renderer='disabled',\n                on_failure='ignore',\n            )\n    # and dive deeper\n    # given the clone source is a local dataset, we can have a\n    # cheap look at it, and configure its own 'origin' as a remote\n    # (if there is any), and benefit from additional annex availability\n    yield from configure_origins(\n        cfgds,\n        Dataset(probeds.pathobj / origin_url),\n        label=label + 1)\n\n\ndef _get_tracking_source(ds):\n    \"\"\"Returns name and url of a potential configured source\n    tracking remote\"\"\"\n    vcs = ds.repo\n    # if we have a remote, let's check the location of that remote\n    # for the presence of the desired submodule\n\n    remote_name, tracking_branch = vcs.get_tracking_branch()\n    if not remote_name and isinstance(vcs, AnnexRepo):\n        # maybe cloned from a source repo that was in adjusted mode\n        # https://github.com/datalad/datalad/issues/3969\n        remote_name, tracking_branch = vcs.get_tracking_branch(\n            corresponding=False)\n    # TODO: better default `None`? Check where we might rely on '':\n    remote_url = ''\n    if remote_name:\n        remote_url = vcs.get_remote_url(remote_name, push=False)\n\n    return remote_name, remote_url\n\n\ndef _get_installationpath_from_url(url):\n    \"\"\"Returns a relative path derived from the trailing end of a URL\n\n    This can be used to determine an installation path of a Dataset\n    from a URL, analog to what `git clone` does.\n    \"\"\"\n    ri = RI(url)\n    if isinstance(ri, (URL, DataLadRI)):  # decode only if URL\n        path = ri.path.rstrip('/')\n        path = urlunquote(path) if path else ri.hostname\n        if '/' in path:\n            path = path.split('/')\n            if path[-1] == '.git':\n                path = path[-2]\n            else:\n                path = path[-1]\n    else:\n        path = Path(url).parts[-1]\n    if path.endswith('.git'):\n        path = path[:-4]\n    return path\n\n\ndef decode_source_spec(spec, cfg=None):\n    \"\"\"Decode information from a clone source specification\n\n    Parameters\n    ----------\n    spec : str\n      Any supported clone source specification\n    cfg : ConfigManager, optional\n      Configuration will be queried from the instance (i.e. from a particular\n      dataset). If None is given, the global DataLad configuration will be\n      queried.\n\n    Returns\n    -------\n    dict\n      The value of each decoded property is stored under its own key in this\n      dict. By default the following keys are return: 'type', a specification\n      type label {'giturl', 'dataladri', 'ria'}; 'source' the original\n      source specification; 'giturl' a URL for the source that is a suitable\n      source argument for git-clone; 'version' a version-identifer, if present\n      (None else); 'default_destpath' a relative path that that can be used as\n      a clone destination.\n    \"\"\"\n    if cfg is None:\n        from datalad import cfg\n    # standard property dict composition\n    props = dict(\n        source=spec,\n        version=None,\n    )\n\n    # Git never gets to see these URLs, so let's manually apply any\n    # rewrite configuration Git might know about.\n    # Note: We need to rewrite before parsing, otherwise parsing might go wrong.\n    # This is particularly true for insteadOf labels replacing even the URL\n    # scheme.\n    spec = cfg.rewrite_url(spec)\n    # common starting point is a RI instance, support for accepting an RI\n    # instance is kept for backward-compatibility reasons\n    source_ri = RI(spec) if not isinstance(spec, RI) else spec\n\n    # scenario switch, each case must set 'giturl' at the very minimum\n    if isinstance(source_ri, DataLadRI):\n        # we have got our DataLadRI as the source, so expand it\n        props['type'] = 'dataladri'\n        props['giturl'] = source_ri.as_git_url()\n    elif isinstance(source_ri, URL) and source_ri.scheme.startswith('ria+'):\n        # parse a RIA URI\n        dsid, version = source_ri.fragment.split('@', maxsplit=1) \\\n            if '@' in source_ri.fragment else (source_ri.fragment, None)\n        uuid_regex = r'[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}'\n        if not re.match(uuid_regex, dsid):\n            raise ValueError('RIA URI does not contain a valid dataset ID: {}'.format(spec))\n        # now we cancel the fragment in the original URL, but keep everthing else\n        # in order to be able to support the various combinations of ports, paths,\n        # and everything else\n        source_ri.fragment = ''\n        # strip the custom protocol and go with standard one\n        source_ri.scheme = source_ri.scheme[4:]\n        # take any existing path, and add trace to dataset within the store\n        source_ri.path = '{urlpath}{urldelim}{trace}'.format(\n            urlpath=source_ri.path if source_ri.path else '',\n            urldelim='' if not source_ri.path or source_ri.path.endswith('/') else '/',\n            trace='{}/{}'.format(dsid[:3], dsid[3:]),\n        )\n        props.update(\n            type='ria',\n            giturl=str(source_ri),\n            version=version,\n            default_destpath=dsid,\n        )\n    else:\n        # let's assume that anything else is a URI that Git can handle\n        props['type'] = 'giturl'\n        # use original input verbatim\n        props['giturl'] = spec\n\n    if 'default_destpath' not in props:\n        # if we still have no good idea on where a dataset could be cloned to if no\n        # path was given, do something similar to git clone and derive the path from\n        # the source\n        props['default_destpath'] = _get_installationpath_from_url(props['giturl'])\n\n    return props\n"}
A user will ask you to solve a task. You should first draft your thinking process (inner monologue). Then, generate the solution.

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `decode_source_spec` Fails to Handle Dataset Aliases in RIA URIs

**Description:**
When attempting to decode a RIA URI that includes a dataset alias, the `decode_source_spec` function raises a `ValueError` instead of successfully parsing the alias. This prevents the proper installation of datasets identified by their aliases.

**Example Code:**
```python
source = 'ria+http://store.datalad.org#~hcp-openaccess'
result = decode_source_spec(source)
```

**Expected Behavior:**
The function should return a dictionary with the parsed details, correctly handling the alias. For example:
```python
{
    'source': 'ria+http://store.datalad.org#~hcp-openaccess',
    'version': None,
    'type': 'ria',
    'giturl': 'http://store.datalad.org/alias/hcp-openaccess',
    'default_destpath': 'hcp-openaccess'
}
```

**Actual Behavior:**
Instead of returning the expected dictionary, the function raises the following error:
```
ValueError: RIA URI does not contain a valid dataset ID: ria+http://store.datalad.org#~hcp-openaccess
```
This error occurs because the function does not recognize the alias format starting with `~`, leading to an inability to handle dataset aliases properly.
[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### datalad/core/distributed/clone.py
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
#   See COPYING file distributed along with the datalad package for the
#   copyright and license terms.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""Plumbing command for dataset installation"""


import logging
import re
from os.path import expanduser
from collections import OrderedDict
from urllib.parse import unquote as urlunquote

from datalad.interface.base import Interface
from datalad.interface.utils import eval_results
from datalad.interface.base import build_doc
from datalad.interface.results import get_status_dict
from datalad.interface.common_opts import (
    location_description,
    reckless_opt,
)
from datalad.log import log_progress
from datalad.support.gitrepo import (
    GitRepo,
)
from datalad.cmd import (
    CommandError,
)
from datalad.support.annexrepo import AnnexRepo
from datalad.support.constraints import (
    EnsureNone,
    EnsureStr,
    EnsureKeyChoice,
)
from datalad.support.param import Parameter
from datalad.support.network import (
    get_local_file_url,
    URL,
    RI,
    DataLadRI,
    PathRI,
)
from datalad.dochelpers import (
    exc_str,
    single_or_plural,
)
from datalad.utils import (
    rmtree,
    assure_bool,
    knows_annex,
    Path,
)

from datalad.distribution.dataset import (
    Dataset,
    datasetmethod,
    resolve_path,
    require_dataset,
    EnsureDataset,
)
from datalad.distribution.utils import (
    _get_flexible_source_candidates,
)
from datalad.utils import (
    check_symlink_capability
)

__docformat__ = 'restructuredtext'

lgr = logging.getLogger('datalad.core.distributed.clone')


@build_doc
class Clone(Interface):
    """Obtain a dataset (copy) from a URL or local directory

    The purpose of this command is to obtain a new clone (copy) of a dataset
    and place it into a not-yet-existing or empty directory. As such `clone`
    provides a strict subset of the functionality offered by `install`. Only a
    single dataset can be obtained, and immediate recursive installation of
    subdatasets is not supported. However, once a (super)dataset is installed
    via `clone`, any content, including subdatasets can be obtained by a
    subsequent `get` command.

    Primary differences over a direct `git clone` call are 1) the automatic
    initialization of a dataset annex (pure Git repositories are equally
    supported); 2) automatic registration of the newly obtained dataset as a
    subdataset (submodule), if a parent dataset is specified; 3) support
    for additional resource identifiers (DataLad resource identifiers as used
    on datasets.datalad.org, and RIA store URLs as used for store.datalad.org
    - optionally in specific versions as identified by a branch or a tag; see
    examples); and 4) automatic configurable generation of alternative access
    URL for common cases (such as appending '.git' to the URL in case the
    accessing the base URL failed).

    || PYTHON >>By default, the command returns a single Dataset instance for
    an installed dataset, regardless of whether it was newly installed ('ok'
    result), or found already installed from the specified source ('notneeded'
    result).<< PYTHON ||

    .. seealso::

      :ref:`handbook:3-001`
        More information on Remote Indexed Archive (RIA) stores
    """
    # by default ignore everything but install results
    # i.e. no "add to super dataset"
    result_filter = EnsureKeyChoice('action', ('install',))
    # very frequently this command will yield exactly one installed dataset
    # spare people the pain of going through a list by default
    return_type = 'item-or-list'
    # as discussed in #1409 and #1470, we want to return dataset instances
    # matching what is actually available after command completion (and
    # None for any failed dataset installation)
    result_xfm = 'successdatasets-or-none'

    _examples_ = [
        dict(text="Install a dataset from Github into the current directory",
             code_py="clone("
             "source='https://github.com/datalad-datasets/longnow"
             "-podcasts.git')",
             code_cmd="datalad clone "
             "https://github.com/datalad-datasets/longnow-podcasts.git"),
        dict(text="Install a dataset into a specific directory",
             code_py="""\
             clone(source='https://github.com/datalad-datasets/longnow-podcasts.git',
                   path='myfavpodcasts')""",
             code_cmd="""\
             datalad clone https://github.com/datalad-datasets/longnow-podcasts.git \\
             myfavpodcasts"""),
        dict(text="Install a dataset as a subdataset into the current dataset",
             code_py="""\
             clone(dataset='.',
                   source='https://github.com/datalad-datasets/longnow-podcasts.git')""",
             code_cmd="datalad clone -d . "
             "https://github.com/datalad-datasets/longnow-podcasts.git"),
        dict(text="Install the main superdataset from datasets.datalad.org",
             code_py="clone(source='///')",
             code_cmd="datalad clone ///"),
        dict(text="Install a dataset identified by its ID from store.datalad.org",
             code_py="clone(source='ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561')",
             code_cmd="datalad clone ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561"),
        dict(
            text="Install a dataset in a specific version as identified by a"
                 "branch or tag name from store.datalad.org",
            code_py="clone(source='ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561@myidentifier')",
            code_cmd="datalad clone ria+http://store.datalad.org#76b6ca66-36b1-11ea-a2e6-f0d5bf7b5561@myidentifier"),
        dict(
            text="Install a dataset with group-write access permissions",
            code_py=\
            "clone(source='http://example.com/dataset', reckless='shared-group')",
            code_cmd=\
            "datalad clone http://example.com/dataset --reckless shared-group"),
    ]

    _params_ = dict(
        dataset=Parameter(
            args=("-d", "--dataset"),
            doc="""(parent) dataset to clone into. If given, the newly cloned
            dataset is registered as a subdataset of the parent. Also, if given,
            relative paths are interpreted as being relative to the parent
            dataset, and not relative to the working directory.""",
            constraints=EnsureDataset() | EnsureNone()),
        source=Parameter(
            args=("source",),
            metavar='SOURCE',
            doc="""URL, DataLad resource identifier, local path or instance of
            dataset to be cloned""",
            constraints=EnsureStr() | EnsureNone()),
        path=Parameter(
            args=("path",),
            metavar='PATH',
            nargs="?",
            doc="""path to clone into.  If no `path` is provided a
            destination path will be derived from a source URL
            similar to :command:`git clone`"""),
        description=location_description,
        reckless=reckless_opt,
    )

    @staticmethod
    @datasetmethod(name='clone')
    @eval_results
    def __call__(
            source,
            path=None,
            dataset=None,
            description=None,
            reckless=None):
        # did we explicitly get a dataset to install into?
        # if we got a dataset, path will be resolved against it.
        # Otherwise path will be resolved first.
        ds = require_dataset(
            dataset, check_installed=True, purpose='cloning') \
            if dataset is not None else dataset
        refds_path = ds.path if ds else None

        # legacy compatibility
        if reckless is True:
            # so that we can forget about how things used to be
            reckless = 'auto'
        if reckless is None and ds:
            # if reckless is not explicitly given, but we operate on a
            # superdataset, query whether it has been instructed to operate
            # in a reckless mode, and inherit it for the coming clone
            reckless = ds.config.get('datalad.clone.reckless', None)

        if isinstance(source, Dataset):
            source = source.path

        if source == path:
            # even if they turn out to be identical after resolving symlinks
            # and more sophisticated witchcraft, it would still happily say
            # "it appears to be already installed", so we just catch an
            # obviously pointless input combination
            raise ValueError(
                "clone `source` and destination `path` are identical [{}]. "
                "If you are trying to add a subdataset simply use `save`".format(
                    path))

        if path is not None:
            path = resolve_path(path, dataset)

        # derive target from source:
        if path is None:
            # we got nothing but a source. do something similar to git clone
            # and derive the path from the source and continue
            # since this is a relative `path`, resolve it:
            # we are not going to reuse the decoded URL, as this is done for
            # all source candidates in clone_dataset(), we just use to determine
            # a destination path here in order to perform a bunch of additional
            # checks that shall not pollute the helper function
            source_ = decode_source_spec(
                source, cfg=None if ds is None else ds.config)
            path = resolve_path(source_['default_destpath'], dataset)
            lgr.debug("Determined clone target path from source")
        lgr.debug("Resolved clone target path to: '%s'", path)

        # there is no other way -- my intoxicated brain tells me
        assert(path is not None)

        result_props = dict(
            action='install',
            logger=lgr,
            refds=refds_path,
            source_url=source)

        try:
            # this will implicitly cause pathlib to run a bunch of checks
            # whether the present path makes any sense on the platform
            # we are running on -- we don't care if the path actually
            # exists at this point, but we want to abort early if the path
            # spec is determined to be useless
            path.exists()
        except OSError as e:
            yield get_status_dict(
                status='error',
                path=path,
                message=('cannot handle target path: %s', exc_str(e)),
                **result_props)
            return

        destination_dataset = Dataset(path)
        result_props['ds'] = destination_dataset

        if ds is not None and ds.pathobj not in path.parents:
            yield get_status_dict(
                status='error',
                message=("clone target path '%s' not in specified target dataset '%s'",
                         path, ds),
                **result_props)
            return

        # perform the actual cloning operation
        yield from clone_dataset(
            [source],
            destination_dataset,
            reckless,
            description,
            result_props,
            cfg=None if ds is None else ds.config,
        )

        # TODO handle any 'version' property handling and verification using a dedicated
        # public helper

        if ds is not None:
            # we created a dataset in another dataset
            # -> make submodule
            for r in ds.save(
                    path,
                    return_type='generator',
                    result_filter=None,
                    result_xfm=None,
                    on_failure='ignore'):
                yield r


def clone_dataset(
        srcs,
        destds,
        reckless=None,
        description=None,
        result_props=None,
        cfg=None):
    """Internal helper to perform cloning without sanity checks (assumed done)

    This helper does not handle any saving of subdataset modification or adding
    in a superdataset.

    Parameters
    ----------
    srcs : list
      Any suitable clone source specifications (paths, URLs)
    destds : Dataset
      Dataset instance for the clone destination
    reckless : {None, 'auto', 'ephemeral', 'shared-...'}, optional
      Mode switch to put cloned dataset into unsafe/throw-away configurations, i.e.
      sacrifice data safety for performance or resource footprint.
    description : str, optional
      Location description for the annex of the dataset clone (if there is any).
    result_props : dict, optional
      Default properties for any yielded result, passed on to get_status_dict().
    cfg : ConfigManager, optional
      Configuration will be queried from this instance (i.e. from a particular
      dataset). If None is given, the global DataLad configuration will be
      queried.

    Yields
    ------
    dict
      DataLad result records
    """
    if not result_props:
        # in case the caller had no specific idea on how results should look
        # like, provide sensible defaults
        result_props = dict(
            action='install',
            logger=lgr,
            ds=destds,
        )

    dest_path = destds.pathobj

    # decode all source candidate specifications
    candidate_sources = [decode_source_spec(s, cfg=cfg) for s in srcs]

    # now expand the candidate sources with additional variants of the decoded
    # giturl, while duplicating the other properties in the additional records
    # for simplicity. The hope is to overcome a few corner cases and be more
    # robust than git clone
    candidate_sources = [
        dict(props, giturl=s) for props in candidate_sources
        for s in _get_flexible_source_candidates(props['giturl'])
    ]

    # important test! based on this `rmtree` will happen below after failed clone
    dest_path_existed = dest_path.exists()
    if dest_path_existed and any(dest_path.iterdir()):
        if destds.is_installed():
            # check if dest was cloned from the given source before
            # this is where we would have installed this from
            # this is where it was actually installed from
            track_name, track_url = _get_tracking_source(destds)
            try:
                # this will get us track_url in system native path conventions,
                # whenever it is a path (and not a URL)
                # this is needed to match it to any potentially incoming local
                # source path in the 'notneeded' test below
                track_path = str(Path(track_url))
            except Exception:
                # this should never happen, because Path() will let any non-path stringification
                # pass through unmodified, but we do not want any potential crash due to
                # pathlib behavior changes
                lgr.debug("Unexpected behavior of pathlib!")
                track_path = None
            for cand in candidate_sources:
                src = cand['giturl']
                if track_url == src \
                        or get_local_file_url(track_url, compatibility='git') == src \
                        or track_path == expanduser(src):
                    yield get_status_dict(
                        status='notneeded',
                        message=("dataset %s was already cloned from '%s'",
                                 destds,
                                 src),
                        **result_props)
                    return
        # anything else is an error
        yield get_status_dict(
            status='error',
            message='target path already exists and not empty, refuse to clone into target path',
            **result_props)
        return

    log_progress(
        lgr.info,
        'cloneds',
        'Cloning dataset to %s', destds,
        total=len(candidate_sources),
        label='Clone attempt',
        unit=' Candidate locations',
    )
    error_msgs = OrderedDict()  # accumulate all error messages formatted per each url
    for cand in candidate_sources:
        log_progress(
            lgr.info,
            'cloneds',
            'Attempting to clone from %s to %s', cand['giturl'], dest_path,
            update=1,
            increment=True)

        clone_opts = {}

        if cand.get('version', None):
            clone_opts['branch'] = cand['version']
        try:
            # TODO for now GitRepo.clone() cannot handle Path instances, and PY35
            # doesn't make it happen seemlessly
            GitRepo.clone(
                path=str(dest_path),
                url=cand['giturl'],
                clone_options=clone_opts,
                create=True)

        except CommandError as e:
            e_stderr = e.stderr

            error_msgs[cand['giturl']] = e
            lgr.debug("Failed to clone from URL: %s (%s)",
                      cand['giturl'], exc_str(e))
            if dest_path.exists():
                lgr.debug("Wiping out unsuccessful clone attempt at: %s",
                          dest_path)
                # We must not just rmtree since it might be curdir etc
                # we should remove all files/directories under it
                # TODO stringification can be removed once patlib compatible
                # or if PY35 is no longer supported
                rmtree(str(dest_path), children_only=dest_path_existed)

            if 'could not create work tree' in e_stderr.lower():
                # this cannot be fixed by trying another URL
                re_match = re.match(r".*fatal: (.*)$", e_stderr,
                                    flags=re.MULTILINE | re.DOTALL)
                # cancel progress bar
                log_progress(
                    lgr.info,
                    'cloneds',
                    'Completed clone attempts for %s', destds
                )
                yield get_status_dict(
                    status='error',
                    message=re_match.group(1).strip()
                    if re_match else "stderr: " + e_stderr,
                    **result_props)
                return
            # next candidate
            continue

        result_props['source'] = cand
        # do not bother with other sources if succeeded
        break

    log_progress(
        lgr.info,
        'cloneds',
        'Completed clone attempts for %s', destds
    )

    if not destds.is_installed():
        if len(error_msgs):
            if all(not e.stdout and not e.stderr for e in error_msgs.values()):
                # there is nothing we can learn from the actual exception,
                # the exit code is uninformative, the command is predictable
                error_msg = "Failed to clone from all attempted sources: %s"
                error_args = list(error_msgs.keys())
            else:
                error_msg = "Failed to clone from any candidate source URL. " \
                            "Encountered errors per each url were:\n- %s"
                error_args = '\n- '.join(
                    '{}\n  {}'.format(url, exc_str(exc))
                    for url, exc in error_msgs.items()
                )
        else:
            # yoh: Not sure if we ever get here but I felt that there could
            #      be a case when this might happen and original error would
            #      not be sufficient to troubleshoot what is going on.
            error_msg = "Awkward error -- we failed to clone properly. " \
                        "Although no errors were encountered, target " \
                        "dataset at %s seems to be not fully installed. " \
                        "The 'succesful' source was: %s"
            error_args = (destds.path, cand['giturl'])
        yield get_status_dict(
            status='error',
            message=(error_msg, error_args),
            **result_props)
        return

    if not cand.get("version"):
        postclone_check_head(destds)

    # act on --reckless=shared-...
    # must happen prior git-annex-init, where we can cheaply alter the repo
    # setup through safe re-init'ing
    if reckless and reckless.startswith('shared-'):
        lgr.debug('Reinit %s to enable shared access permissions', destds)
        destds.repo.call_git(['init', '--shared={}'.format(reckless[7:])])

    yield from postclonecfg_annexdataset(
        destds,
        reckless,
        description)

    # perform any post-processing that needs to know details of the clone
    # source
    if result_props['source']['type'] == 'ria':
        yield from postclonecfg_ria(destds, result_props['source'])

    # yield successful clone of the base dataset now, as any possible
    # subdataset clone down below will not alter the Git-state of the
    # parent
    yield get_status_dict(status='ok', **result_props)


def postclone_check_head(ds):
    repo = ds.repo
    if not repo.commit_exists("HEAD"):
        # HEAD points to an unborn branch. A likely cause of this is that the
        # remote's main branch is something other than master but HEAD wasn't
        # adjusted accordingly.
        #
        # Let's choose the most recently updated remote ref (according to
        # commit date). In the case of a submodule, switching to a ref with
        # commits prevents .update_submodule() from failing. It is likely that
        # the ref includes the registered commit, but we don't have the
        # information here to know for sure. If it doesn't, .update_submodule()
        # will check out a detached HEAD.
        remote_branches = (
            b["refname:strip=2"] for b in repo.for_each_ref_(
                fields="refname:strip=2", sort="-committerdate",
                pattern="refs/remotes/origin"))
        for rbranch in remote_branches:
            if rbranch in ["origin/git-annex", "HEAD"]:
                continue
            repo.call_git(["checkout", "-b", rbranch[7:],  # drop "origin/"
                           "--track", rbranch])
            lgr.debug("Checked out local branch from %s", rbranch)
            return
        lgr.warning("Cloned %s but could not find a branch "
                    "with commits", ds.path)


def postclonecfg_ria(ds, props):
    """Configure a dataset freshly cloned from a RIA store"""
    # RIA uses hashdir mixed, copying data to it via git-annex (if cloned via
    # ssh) would make it see a bare repo and establish a hashdir lower annex
    # object tree.
    # Moreover, we want the RIA remote to receive all data for the store, so its
    # objects could be moved into archives (the main point of a RIA store).
    ds.config.set(
        'remote.origin.annex-ignore', 'true',
        where='local')

    # chances are that if this dataset came from a RIA store, its subdatasets
    # may live there too. Place a subdataset source candidate config that makes
    # get probe this RIA store when obtaining subdatasets
    ds.config.set(
        # we use the label 'origin' for this candidate in order to not have to
        # generate a complicated name from the actual source specification
        'datalad.get.subdataset-source-candidate-origin',
        # use the entire original URL, up to the fragment + plus dataset ID
        # placeholder, this should make things work with any store setup we
        # support (paths, ports, ...)
        props['source'].split('#', maxsplit=1)[0] + '#{id}',
        where='local')

    # setup publication dependency, if a corresponding special remote exists
    # and was enabled (there could be RIA stores that actually only have repos)
    # make this function be a generator
    ria_remotes = [s for s in ds.siblings('query', result_renderer='disabled')
                   if s.get('annex-externaltype', None) == 'ora'
    ]
    if not ria_remotes:
        lgr.debug("Found no RIA special remote")
    elif len(ria_remotes) == 1:
        yield from ds.siblings('configure',
                               name='origin',
                               publish_depends=ria_remotes[0]['name'],
                               result_filter=None,
                               result_renderer='disabled')
    else:
        lgr.warning("Found multiple RIA remotes. Couldn't decide which "
                    "publishing to origin should depend on: %s",
                    [r['name'] for r in ria_remotes])


def postclonecfg_annexdataset(ds, reckless, description=None):
    """If ds "knows annex" -- annex init it, set into reckless etc

    Provides additional tune up to a possibly an annex repo, e.g.
    "enables" reckless mode, sets up description
    """
    # in any case check whether we need to annex-init the installed thing:
    if not knows_annex(ds.path):
        # not for us
        return

    # init annex when traces of a remote annex can be detected
    if reckless == 'auto':
        lgr.debug(
            "Instruct annex to hardlink content in %s from local "
            "sources, if possible (reckless)", ds.path)
        ds.config.set(
            'annex.hardlink', 'true', where='local', reload=True)

    lgr.debug("Initializing annex repo at %s", ds.path)
    # Note, that we cannot enforce annex-init via AnnexRepo().
    # If such an instance already exists, its __init__ will not be executed.
    # Therefore do quick test once we have an object and decide whether to call
    # its _init().
    #
    # Additionally, call init if we need to add a description (see #1403),
    # since AnnexRepo.__init__ can only do it with create=True
    repo = AnnexRepo(ds.path, init=True)
    if not repo.is_initialized() or description:
        repo._init(description=description)
    if reckless == 'auto' or (reckless and reckless.startswith('shared-')):
        repo._run_annex_command('untrust', annex_options=['here'])

    elif reckless == 'ephemeral':
        # with ephemeral we declare 'here' as 'dead' right away, whenever
        # we symlink origin's annex, since availability from 'here' should
        # not be propagated for an ephemeral clone when we publish back to
        # origin.
        # This will cause stuff like this for a locally present annexed file:
        # % git annex whereis d1
        # whereis d1 (0 copies) failed
        # BUT this works:
        # % git annex find . --not --in here
        # % git annex find . --in here
        # d1

        # we don't want annex copy-to origin
        ds.config.set(
            'remote.origin.annex-ignore', 'true',
            where='local')

        ds.repo.set_remote_dead('here')

        if check_symlink_capability(ds.repo.dot_git / 'dl_link_test',
                                    ds.repo.dot_git / 'dl_target_test'):
            # symlink the annex to avoid needless copies in an emphemeral clone
            annex_dir = ds.repo.dot_git / 'annex'
            origin_annex_url = ds.config.get("remote.origin.url", None)
            origin_git_path = None
            if origin_annex_url:
                try:
                    # Deal with file:// scheme URLs as well as plain paths.
                    # If origin isn't local, we have nothing to do.
                    origin_git_path = Path(RI(origin_annex_url).localpath)
                    if origin_git_path.name != '.git':
                        origin_git_path /= '.git'
                except ValueError:
                    # Note, that accessing localpath on a non-local RI throws
                    # ValueError rather than resulting in an AttributeError.
                    # TODO: Warning level okay or is info level sufficient?
                    # Note, that setting annex-dead is independent of
                    # symlinking .git/annex. It might still make sense to
                    # have an ephemeral clone that doesn't propagate its avail.
                    # info. Therefore don't fail altogether.
                    lgr.warning("reckless=ephemeral mode: origin doesn't seem "
                                "local: %s\nno symlinks being used",
                                origin_annex_url)
            if origin_git_path:
                # TODO make sure that we do not delete any unique data
                rmtree(str(annex_dir)) \
                    if not annex_dir.is_symlink() else annex_dir.unlink()
                annex_dir.symlink_to(origin_git_path / 'annex',
                                     target_is_directory=True)
        else:
            # TODO: What level? + note, that annex-dead is independ
            lgr.warning("reckless=ephemeral mode: Unable to create symlinks on "
                        "this file system.")

    if reckless:
        # we successfully dealt with reckless here.
        # store the reckless setting in the dataset to make it
        # known to later clones of subdatasets via get()
        ds.config.set(
            'datalad.clone.reckless', reckless,
            where='local',
            reload=True)

    srs = {True: [], False: []}  # special remotes by "autoenable" key
    remote_uuids = None  # might be necessary to discover known UUIDs

    # Note: The purpose of this function is to inform the user. So if something
    # looks misconfigured, we'll warn and move on to the next item.
    for uuid, config in repo.get_special_remotes().items():
        sr_name = config.get('name', None)
        if sr_name is None:
            lgr.warning(
                'Ignoring special remote %s because it does not have a name. '
                'Known information: %s',
                uuid, config)
            continue
        sr_autoenable = config.get('autoenable', False)
        try:
            sr_autoenable = assure_bool(sr_autoenable)
        except ValueError:
            lgr.warning(
                'Failed to process "autoenable" value %r for sibling %s in '
                'dataset %s as bool.'
                'You might need to enable it later manually and/or fix it up to'
                ' avoid this message in the future.',
                sr_autoenable, sr_name, ds.path)
            continue

        # determine whether there is a registered remote with matching UUID
        if uuid:
            if remote_uuids is None:
                remote_uuids = {
                    # Check annex-config-uuid first. For sameas annex remotes,
                    # this will point to the UUID for the configuration (i.e.
                    # the key returned by get_special_remotes) rather than the
                    # shared UUID.
                    (repo.config.get('remote.%s.annex-config-uuid' % r) or
                     repo.config.get('remote.%s.annex-uuid' % r))
                    for r in repo.get_remotes()
                }
            if uuid not in remote_uuids:
                srs[sr_autoenable].append(sr_name)

    if srs[True]:
        lgr.debug(
            "configuration for %s %s added because of autoenable,"
            " but no UUIDs for them yet known for dataset %s",
            # since we are only at debug level, we could call things their
            # proper names
            single_or_plural("special remote",
                             "special remotes", len(srs[True]), True),
            ", ".join(srs[True]),
            ds.path
        )

    if srs[False]:
        # if has no auto-enable special remotes
        lgr.info(
            'access to %s %s not auto-enabled, enable with:\n'
            '\t\tdatalad siblings -d "%s" enable -s %s',
            # but since humans might read it, we better confuse them with our
            # own terms!
            single_or_plural("dataset sibling",
                             "dataset siblings", len(srs[False]), True),
            ", ".join(srs[False]),
            ds.path,
            srs[False][0] if len(srs[False]) == 1 else "SIBLING",
        )

    # we have just cloned the repo, so it has 'origin', configure any
    # reachable origin of origins
    yield from configure_origins(ds, ds)


_handle_possible_annex_dataset = postclonecfg_annexdataset


def configure_origins(cfgds, probeds, label=None):
    """Configure any discoverable local dataset 'origin' sibling as a remote

    Parameters
    ----------
    cfgds : Dataset
      Dataset to receive the remote configurations
    probeds : Dataset
      Dataset to start looking for 'origin' remotes. May be identical with
      `cfgds`.
    label : int, optional
      Each discovered 'origin' will be configured as a remote under the name
      'origin-<label>'. If no label is given, '2' will be used by default,
      given that there is typically a 'origin' remote already.
    """
    if label is None:
        label = 1
    # let's look at the URL for that remote and see if it is a local
    # dataset
    origin_url = probeds.config.get('remote.origin.url')
    if not origin_url:
        # no origin, nothing to do
        return
    if not cfgds.config.obtain(
            'datalad.install.inherit-local-origin',
            default=True):
        # no inheritance wanted
        return
    if not isinstance(RI(origin_url), PathRI):
        # not local path
        return

    # no need to reconfigure original/direct origin again
    if cfgds != probeds:
        # prevent duplicates
        known_remote_urls = set(
            cfgds.config.get(r + '.url', None)
            for r in cfgds.config.sections()
            if r.startswith('remote.')
        )
        if origin_url not in known_remote_urls:
            yield from cfgds.siblings(
                'configure',
                # no chance for conflict, can only be the second configured
                # remote
                name='origin-{}'.format(label),
                url=origin_url,
                # fetch to get all annex info
                fetch=True,
                result_renderer='disabled',
                on_failure='ignore',
            )
    # and dive deeper
    # given the clone source is a local dataset, we can have a
    # cheap look at it, and configure its own 'origin' as a remote
    # (if there is any), and benefit from additional annex availability
    yield from configure_origins(
        cfgds,
        Dataset(probeds.pathobj / origin_url),
        label=label + 1)


def _get_tracking_source(ds):
    """Returns name and url of a potential configured source
    tracking remote"""
    vcs = ds.repo
    # if we have a remote, let's check the location of that remote
    # for the presence of the desired submodule

    remote_name, tracking_branch = vcs.get_tracking_branch()
    if not remote_name and isinstance(vcs, AnnexRepo):
        # maybe cloned from a source repo that was in adjusted mode
        # https://github.com/datalad/datalad/issues/3969
        remote_name, tracking_branch = vcs.get_tracking_branch(
            corresponding=False)
    # TODO: better default `None`? Check where we might rely on '':
    remote_url = ''
    if remote_name:
        remote_url = vcs.get_remote_url(remote_name, push=False)

    return remote_name, remote_url


def _get_installationpath_from_url(url):
    """Returns a relative path derived from the trailing end of a URL

    This can be used to determine an installation path of a Dataset
    from a URL, analog to what `git clone` does.
    """
    ri = RI(url)
    if isinstance(ri, (URL, DataLadRI)):  # decode only if URL
        path = ri.path.rstrip('/')
        path = urlunquote(path) if path else ri.hostname
        if '/' in path:
            path = path.split('/')
            if path[-1] == '.git':
                path = path[-2]
            else:
                path = path[-1]
    else:
        path = Path(url).parts[-1]
    if path.endswith('.git'):
        path = path[:-4]
    return path


def decode_source_spec(spec, cfg=None):
    """Decode information from a clone source specification

    Parameters
    ----------
    spec : str
      Any supported clone source specification
    cfg : ConfigManager, optional
      Configuration will be queried from the instance (i.e. from a particular
      dataset). If None is given, the global DataLad configuration will be
      queried.

    Returns
    -------
    dict
      The value of each decoded property is stored under its own key in this
      dict. By default the following keys are return: 'type', a specification
      type label {'giturl', 'dataladri', 'ria'}; 'source' the original
      source specification; 'giturl' a URL for the source that is a suitable
      source argument for git-clone; 'version' a version-identifer, if present
      (None else); 'default_destpath' a relative path that that can be used as
      a clone destination.
    """
    if cfg is None:
        from datalad import cfg
    # standard property dict composition
    props = dict(
        source=spec,
        version=None,
    )

    # Git never gets to see these URLs, so let's manually apply any
    # rewrite configuration Git might know about.
    # Note: We need to rewrite before parsing, otherwise parsing might go wrong.
    # This is particularly true for insteadOf labels replacing even the URL
    # scheme.
    spec = cfg.rewrite_url(spec)
    # common starting point is a RI instance, support for accepting an RI
    # instance is kept for backward-compatibility reasons
    source_ri = RI(spec) if not isinstance(spec, RI) else spec

    # scenario switch, each case must set 'giturl' at the very minimum
    if isinstance(source_ri, DataLadRI):
        # we have got our DataLadRI as the source, so expand it
        props['type'] = 'dataladri'
        props['giturl'] = source_ri.as_git_url()
    elif isinstance(source_ri, URL) and source_ri.scheme.startswith('ria+'):
        # parse a RIA URI
        dsid, version = source_ri.fragment.split('@', maxsplit=1) \
            if '@' in source_ri.fragment else (source_ri.fragment, None)
        uuid_regex = r'[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}'
        if not re.match(uuid_regex, dsid):
            raise ValueError('RIA URI does not contain a valid dataset ID: {}'.format(spec))
        # now we cancel the fragment in the original URL, but keep everthing else
        # in order to be able to support the various combinations of ports, paths,
        # and everything else
        source_ri.fragment = ''
        # strip the custom protocol and go with standard one
        source_ri.scheme = source_ri.scheme[4:]
        # take any existing path, and add trace to dataset within the store
        source_ri.path = '{urlpath}{urldelim}{trace}'.format(
            urlpath=source_ri.path if source_ri.path else '',
            urldelim='' if not source_ri.path or source_ri.path.endswith('/') else '/',
            trace='{}/{}'.format(dsid[:3], dsid[3:]),
        )
        props.update(
            type='ria',
            giturl=str(source_ri),
            version=version,
            default_destpath=dsid,
        )
    else:
        # let's assume that anything else is a URI that Git can handle
        props['type'] = 'giturl'
        # use original input verbatim
        props['giturl'] = spec

    if 'default_destpath' not in props:
        # if we still have no good idea on where a dataset could be cloned to if no
        # path was given, do something similar to git clone and derive the path from
        # the source
        props['default_destpath'] = _get_installationpath_from_url(props['giturl'])

    return props

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
user