{
    "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\"\"\"Implements class Dataset\n\"\"\"\n\nimport logging\nfrom os.path import abspath, join as opj, normpath\nfrom six import string_types, PY2\nfrom functools import wraps\n\nfrom datalad.support.gitrepo import GitRepo\nfrom datalad.support.annexrepo import AnnexRepo\nfrom datalad.support.gitrepo import InvalidGitRepositoryError, NoSuchPathError\nfrom datalad.support.constraints import Constraint\nfrom datalad.utils import optional_args, expandpath, is_explicit_path\nfrom datalad.utils import swallow_logs\n\nlgr = logging.getLogger('datalad.dataset')\n\n\ndef resolve_path(path, ds=None):\n    \"\"\"Resolve a path specification (against a Dataset location)\n\n    Any explicit path (absolute or relative) is return as an absolute path.\n    In case of an explicit relative path, the current working directory is\n    used as a reference. Any non-explicit relative path is resolved against\n    as dataset location, i.e. considered relative to the location of the\n    dataset. If no dataset is provided, the current working directory is\n    used.\n\n    Returns\n    -------\n    Absolute path\n    \"\"\"\n    path = expandpath(path, force_absolute=False)\n    if is_explicit_path(path):\n        return abspath(path)\n    if ds is None:\n        # no dataset given, use CWD as reference\n        # TODO: Check whether we should use PWD instead of CWD here. Is it done\n        # by abspath?\n        return abspath(path)\n    else:\n        return normpath(opj(ds.path, path))\n\n\nclass Dataset(object):\n    __slots__ = ['_path', '_repo']\n\n    def __init__(self, path):\n        self._path = abspath(path)\n        self._repo = None\n\n    def __repr__(self):\n        return \"<Dataset path=%s>\" % self.path\n\n    def __eq__(self, other):\n        return self.path == other.path\n\n    @property\n    def path(self):\n        \"\"\"path to the dataset\"\"\"\n        return self._path\n\n    @property\n    def repo(self):\n        \"\"\"Get an instance of the version control system/repo for this dataset,\n        or None if there is none yet.\n\n        If creating an instance of GitRepo is guaranteed to be really cheap\n        this could also serve as a test whether a repo is present.\n\n        Returns\n        -------\n        GitRepo\n        \"\"\"\n        if self._repo is None:\n            with swallow_logs():\n                try:\n                    self._repo = AnnexRepo(self._path, create=False, init=False)\n                except (InvalidGitRepositoryError, NoSuchPathError, RuntimeError):\n                    try:\n                        self._repo = GitRepo(self._path, create=False)\n                    except (InvalidGitRepositoryError, NoSuchPathError):\n                        pass\n        elif not isinstance(self._repo, AnnexRepo):\n            # repo was initially set to be self._repo but might become AnnexRepo\n            # at a later moment, so check if it didn't happen\n            if 'git-annex' in self._repo.get_branches():\n                # we acquired git-annex branch\n                self._repo = AnnexRepo(self._repo.path, create=False)\n        return self._repo\n\n    def register_sibling(self, name, url, publish_url=None, verify=None):\n        \"\"\"Register the location of a sibling dataset under a given name.\n\n        Optionally, different URLs can be given for retrieving information from\n        the sibling and for publishing information to it.\n        This is a cheap operation that does not confirm that at the given\n        location an actual sibling dataset is available, unless verify is set.\n        The value \"dataset\" verifies, that at the given URL an accessible\n        dataset is available and the value \"sibling\" furthermore verifies, that\n        this dataset shares at least one commit with self.\n\n        Parameters\n        ----------\n        name\n        url\n        publish_url\n        verify\n          None | \"dataset\" | \"sibling\"\n        \"\"\"\n        repo = self.repo\n\n        if verify is not None:\n            raise NotImplementedError(\"TODO: verify not implemented yet\")\n\n        if name not in repo.get_remotes():\n            # Add remote\n            repo.add_remote(name, url)\n            if publish_url is not None:\n                # set push url:\n                repo._git_custom_command('', [\"git\", \"remote\",\n                                              \"set-url\",\n                                              \"--push\", name,\n                                              publish_url])\n            lgr.info(\"Added remote '%s':\\n %s (pull)\\n%s (push).\" %\n                     (name, url, publish_url if publish_url else url))\n        else:\n            lgr.warning(\"Remote '%s' already exists. Ignore.\")\n            raise ValueError(\"'%s' already exists. Couldn't register sibling.\")\n\n    def get_subdatasets(self, pattern=None, fulfilled=None, absolute=False,\n                            recursive=False):\n        \"\"\"Get names/paths of all known dataset_datasets (subdatasets),\n        optionally matching a specific name pattern.\n\n\n        Parameters\n        ----------\n        pattern : None\n          Not implemented\n        fulfilled : None or bool\n          If not None, return either only present or absent datasets.\n        absolute : bool\n          If True, absolute paths will be returned.\n        recursive : bool\n          If True, recurse into all subdatasets and report them too.\n\n        Returns\n        -------\n        list(Dataset paths) or None\n          None is return if there is not repository instance yet. For an\n          existing repository with no subdatasets an empty list is returned.\n        \"\"\"\n        if pattern is not None:\n            raise NotImplementedError\n\n        repo = self.repo\n        if repo is None:\n            return []\n\n        # check whether we have anything in the repo. if not go home early\n        if not repo.repo.head.is_valid():\n            return []\n\n        try:\n            submodules = repo.get_submodules()\n        except InvalidGitRepositoryError:\n            # this happens when we access a repository with a submodule that\n            # has no commits, hence doesn't appear in the index and\n            # 'git submodule status' also doesn't list it\n            return []\n\n        # filter if desired\n        if fulfilled is None:\n            submodules = [sm.path for sm in submodules]\n        else:\n            submodules = [sm.path for sm in submodules\n                          if sm.module_exists() == fulfilled]\n\n        # expand list with child submodules. keep all paths relative to parent\n        # and convert jointly at the end\n        if recursive:\n            rsm = []\n            for sm in submodules:\n                rsm.append(sm)\n                sdspath = opj(self._path, sm)\n                rsm.extend(\n                    [opj(sm, sdsh)\n                     for sdsh in Dataset(sdspath).get_subdatasets(\n                         pattern=pattern, fulfilled=fulfilled, absolute=False,\n                         recursive=recursive)])\n            submodules = rsm\n\n        if absolute:\n            return [opj(self._path, sm) for sm in submodules]\n        else:\n            return submodules\n\n#    def get_file_handles(self, pattern=None, fulfilled=None):\n#        \"\"\"Get paths to all known file_handles, optionally matching a specific\n#        name pattern.\n#\n#        If fulfilled is True, only paths to fullfiled handles are returned,\n#        if False, only paths to unfulfilled handles are returned.\n#\n#        Parameters\n#        ----------\n#        pattern: str\n#        fulfilled: bool\n#\n#        Returns\n#        -------\n#        list of str\n#          (paths)\n#        \"\"\"\n#        raise NotImplementedError(\"TODO\")\n\n    def recall_state(self, whereto):\n        \"\"\"Something that can be used to checkout a particular state\n        (tag, commit) to \"undo\" a change or switch to a otherwise desired\n        previous state.\n\n        Parameters\n        ----------\n        whereto: str\n        \"\"\"\n        if not self.is_installed():\n            raise RuntimeError(\n                \"cannot remember a state when a dataset is not yet installed\")\n        self.repo.checkout(whereto)\n\n    def is_installed(self):\n        \"\"\"Returns whether a dataset is installed.\n\n        A dataset is installed when a repository for it exists on the filesystem.\n\n        Returns\n        -------\n        bool\n        \"\"\"\n        return self.path is not None and self.repo is not None\n\n\n@optional_args\ndef datasetmethod(f, name=None, dataset_argname='dataset'):\n    \"\"\"Decorator to bind functions to Dataset class.\n\n    The decorated function is still directly callable and additionally serves\n    as method `name` of class Dataset.  To achieve this, the first positional\n    argument is redirected to original keyword argument 'dataset_argname'. All\n    other arguments stay in order (and keep their names, of course). That\n    means, that the signature of the bound function is name(self, a, b) if the\n    original signature is name(a, dataset, b) for example.\n\n    The decorator has no effect on the actual function decorated with it.\n    \"\"\"\n    if not name:\n        name = f.func_name if PY2 else f.__name__\n\n    @wraps(f)\n    def apply_func(*args, **kwargs):\n        \"\"\"Wrapper function to assign arguments of the bound function to\n        original function.\n\n        Note\n        ----\n        This wrapper is NOT returned by the decorator, but only used to bind\n        the function `f` to the Dataset class.\n        \"\"\"\n        kwargs = kwargs.copy()\n        from inspect import getargspec\n        orig_pos = getargspec(f).args\n\n        # If bound function is used with wrong signature (especially by\n        # explicitly passing a dataset, let's raise a proper exception instead\n        # of a 'list index out of range', that is not very telling to the user.\n        if len(args) > len(orig_pos) or dataset_argname in kwargs:\n            raise TypeError(\"{0}() takes at most {1} arguments ({2} given):\"\n                            \" {3}\".format(name, len(orig_pos), len(args),\n                                          ['self'] + [a for a in orig_pos\n                                                      if a != dataset_argname]))\n        kwargs[dataset_argname] = args[0]\n        ds_index = orig_pos.index(dataset_argname)\n        for i in range(1, len(args)):\n            if i <= ds_index:\n                kwargs[orig_pos[i-1]] = args[i]\n            elif i > ds_index:\n                kwargs[orig_pos[i]] = args[i]\n        return f(**kwargs)\n\n    setattr(Dataset, name, apply_func)\n    return f\n\n\n# Note: Cannot be defined with constraints.py, since then dataset.py needs to\n# be imported from constraints.py, which needs to be imported from dataset.py\n# for another constraint\nclass EnsureDataset(Constraint):\n\n    def __call__(self, value):\n        if isinstance(value, Dataset):\n            return value\n        elif isinstance(value, string_types):\n            return Dataset(path=value)\n        else:\n            raise ValueError(\"Can't create Dataset from %s.\" % type(value))\n\n    # TODO: Proper description? Mentioning Dataset class doesn't make sense for\n    # commandline doc!\n    def short_description(self):\n        return \"Dataset\"\n\n    def long_description(self):\n        return \"\"\"Value must be a Dataset or a valid identifier of a Dataset\n        (e.g. a path)\"\"\"\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\"\"\"Implements class Dataset\n\"\"\"\n\nimport logging\nfrom os.path import abspath, join as opj, normpath\nfrom six import string_types, PY2\nfrom functools import wraps\n\nfrom datalad.support.gitrepo import GitRepo\nfrom datalad.support.annexrepo import AnnexRepo\nfrom datalad.support.gitrepo import InvalidGitRepositoryError, NoSuchPathError\nfrom datalad.support.constraints import Constraint\nfrom datalad.utils import optional_args, expandpath, is_explicit_path\nfrom datalad.utils import swallow_logs\n\nlgr = logging.getLogger('datalad.dataset')\n\n\ndef resolve_path(path, ds=None):\n    \"\"\"Resolve a path specification (against a Dataset location)\n\n    Any explicit path (absolute or relative) is returned as an absolute path.\n    In case of an explicit relative path, the current working directory is\n    used as a reference. Any non-explicit relative path is resolved against\n    as dataset location, i.e. considered relative to the location of the\n    dataset. If no dataset is provided, the current working directory is\n    used.\n\n    Returns\n    -------\n    Absolute path\n    \"\"\"\n    path = expandpath(path, force_absolute=False)\n    if is_explicit_path(path):\n        return abspath(path)\n    if ds is None:\n        # no dataset given, use CWD as reference\n        # TODO: Check whether we should use PWD instead of CWD here. Is it done\n        # by abspath?\n        return abspath(path)\n    else:\n        return normpath(opj(ds.path, path))\n\n\nclass Dataset(object):\n    __slots__ = ['_path', '_repo']\n\n    def __init__(self, path):\n        self._path = abspath(path)\n        self._repo = None\n\n    def __repr__(self):\n        return \"<Dataset path=%s>\" % self.path\n\n    def __eq__(self, other):\n        return self.path == other.path\n\n    @property\n    def path(self):\n        \"\"\"path to the dataset\"\"\"\n        return self._path\n\n    @property\n    def repo(self):\n        \"\"\"Get an instance of the version control system/repo for this dataset,\n        or None if there is none yet.\n\n        If creating an instance of GitRepo is guaranteed to be really cheap\n        this could also serve as a test whether a repo is present.\n\n        Returns\n        -------\n        GitRepo\n        \"\"\"\n        if self._repo is None:\n            with swallow_logs():\n                try:\n                    self._repo = AnnexRepo(self._path, create=False, init=False)\n                except (InvalidGitRepositoryError, NoSuchPathError, RuntimeError):\n                    try:\n                        self._repo = GitRepo(self._path, create=False)\n                    except (InvalidGitRepositoryError, NoSuchPathError):\n                        pass\n        elif not isinstance(self._repo, AnnexRepo):\n            # repo was initially set to be self._repo but might become AnnexRepo\n            # at a later moment, so check if it didn't happen\n            if 'git-annex' in self._repo.get_branches():\n                # we acquired git-annex branch\n                self._repo = AnnexRepo(self._repo.path, create=False)\n        return self._repo\n\n    def register_sibling(self, name, url, publish_url=None, verify=None):\n        \"\"\"Register the location of a sibling dataset under a given name.\n\n        Optionally, different URLs can be given for retrieving information from\n        the sibling and for publishing information to it.\n        This is a cheap operation that does not confirm that at the given\n        location an actual sibling dataset is available, unless verify is set.\n        The value \"dataset\" verifies, that at the given URL an accessible\n        dataset is available and the value \"sibling\" furthermore verifies, that\n        this dataset shares at least one commit with self.\n\n        Parameters\n        ----------\n        name\n        url\n        publish_url\n        verify\n          None | \"dataset\" | \"sibling\"\n        \"\"\"\n        repo = self.repo\n\n        if verify is not None:\n            raise NotImplementedError(\"TODO: verify not implemented yet\")\n\n        if name not in repo.get_remotes():\n            # Add remote\n            repo.add_remote(name, url)\n            if publish_url is not None:\n                # set push url:\n                repo._git_custom_command('', [\"git\", \"remote\",\n                                              \"set-url\",\n                                              \"--push\", name,\n                                              publish_url])\n            lgr.info(\"Added remote '%s':\\n %s (pull)\\n%s (push).\" %\n                     (name, url, publish_url if publish_url else url))\n        else:\n            lgr.warning(\"Remote '%s' already exists. Ignore.\")\n            raise ValueError(\"'%s' already exists. Couldn't register sibling.\")\n\n    def get_subdatasets(self, pattern=None, fulfilled=None, absolute=False,\n                            recursive=False):\n        \"\"\"Get names/paths of all known dataset_datasets (subdatasets),\n        optionally matching a specific name pattern.\n\n\n        Parameters\n        ----------\n        pattern : None\n          Not implemented\n        fulfilled : None or bool\n          If not None, return either only present or absent datasets.\n        absolute : bool\n          If True, absolute paths will be returned.\n        recursive : bool\n          If True, recurse into all subdatasets and report them too.\n\n        Returns\n        -------\n        list(Dataset paths) or None\n          None is return if there is not repository instance yet. For an\n          existing repository with no subdatasets an empty list is returned.\n        \"\"\"\n        if pattern is not None:\n            raise NotImplementedError\n\n        repo = self.repo\n        if repo is None:\n            return []\n\n        # check whether we have anything in the repo. if not go home early\n        if not repo.repo.head.is_valid():\n            return []\n\n        try:\n            submodules = repo.get_submodules()\n        except InvalidGitRepositoryError:\n            # this happens when we access a repository with a submodule that\n            # has no commits, hence doesn't appear in the index and\n            # 'git submodule status' also doesn't list it\n            return []\n\n        # filter if desired\n        if fulfilled is None:\n            submodules = [sm.path for sm in submodules]\n        else:\n            submodules = [sm.path for sm in submodules\n                          if sm.module_exists() == fulfilled]\n\n        # expand list with child submodules. keep all paths relative to parent\n        # and convert jointly at the end\n        if recursive:\n            rsm = []\n            for sm in submodules:\n                rsm.append(sm)\n                sdspath = opj(self._path, sm)\n                rsm.extend(\n                    [opj(sm, sdsh)\n                     for sdsh in Dataset(sdspath).get_subdatasets(\n                         pattern=pattern, fulfilled=fulfilled, absolute=False,\n                         recursive=recursive)])\n            submodules = rsm\n\n        if absolute:\n            return [opj(self._path, sm) for sm in submodules]\n        else:\n            return submodules\n\n#    def get_file_handles(self, pattern=None, fulfilled=None):\n#        \"\"\"Get paths to all known file_handles, optionally matching a specific\n#        name pattern.\n#\n#        If fulfilled is True, only paths to fullfiled handles are returned,\n#        if False, only paths to unfulfilled handles are returned.\n#\n#        Parameters\n#        ----------\n#        pattern: str\n#        fulfilled: bool\n#\n#        Returns\n#        -------\n#        list of str\n#          (paths)\n#        \"\"\"\n#        raise NotImplementedError(\"TODO\")\n\n    def recall_state(self, whereto):\n        \"\"\"Something that can be used to checkout a particular state\n        (tag, commit) to \"undo\" a change or switch to a otherwise desired\n        previous state.\n\n        Parameters\n        ----------\n        whereto: str\n        \"\"\"\n        if not self.is_installed():\n            raise RuntimeError(\n                \"cannot remember a state when a dataset is not yet installed\")\n        self.repo.checkout(whereto)\n\n    def is_installed(self):\n        \"\"\"Returns whether a dataset is installed.\n\n        A dataset is installed when a repository for it exists on the filesystem.\n\n        Returns\n        -------\n        bool\n        \"\"\"\n        return self.path is not None and self.repo is not None\n\n\n@optional_args\ndef datasetmethod(f, name=None, dataset_argname='dataset'):\n    \"\"\"Decorator to bind functions to Dataset class.\n\n    The decorated function is still directly callable and additionally serves\n    as method `name` of class Dataset.  To achieve this, the first positional\n    argument is redirected to original keyword argument 'dataset_argname'. All\n    other arguments stay in order (and keep their names, of course). That\n    means, that the signature of the bound function is name(self, a, b) if the\n    original signature is name(a, dataset, b) for example.\n\n    The decorator has no effect on the actual function decorated with it.\n    \"\"\"\n    if not name:\n        name = f.func_name if PY2 else f.__name__\n\n    @wraps(f)\n    def apply_func(*args, **kwargs):\n        \"\"\"Wrapper function to assign arguments of the bound function to\n        original function.\n\n        Note\n        ----\n        This wrapper is NOT returned by the decorator, but only used to bind\n        the function `f` to the Dataset class.\n        \"\"\"\n        kwargs = kwargs.copy()\n        from inspect import getargspec\n        orig_pos = getargspec(f).args\n\n        # If bound function is used with wrong signature (especially by\n        # explicitly passing a dataset, let's raise a proper exception instead\n        # of a 'list index out of range', that is not very telling to the user.\n        if len(args) > len(orig_pos) or dataset_argname in kwargs:\n            raise TypeError(\"{0}() takes at most {1} arguments ({2} given):\"\n                            \" {3}\".format(name, len(orig_pos), len(args),\n                                          ['self'] + [a for a in orig_pos\n                                                      if a != dataset_argname]))\n        kwargs[dataset_argname] = args[0]\n        ds_index = orig_pos.index(dataset_argname)\n        for i in range(1, len(args)):\n            if i <= ds_index:\n                kwargs[orig_pos[i-1]] = args[i]\n            elif i > ds_index:\n                kwargs[orig_pos[i]] = args[i]\n        return f(**kwargs)\n\n    setattr(Dataset, name, apply_func)\n    return f\n\n\n# Note: Cannot be defined with constraints.py, since then dataset.py needs to\n# be imported from constraints.py, which needs to be imported from dataset.py\n# for another constraint\nclass EnsureDataset(Constraint):\n\n    def __call__(self, value):\n        if isinstance(value, Dataset):\n            return value\n        elif isinstance(value, string_types):\n            return Dataset(path=value)\n        else:\n            raise ValueError(\"Can't create Dataset from %s.\" % type(value))\n\n    # TODO: Proper description? Mentioning Dataset class doesn't make sense for\n    # commandline doc!\n    def short_description(self):\n        return \"Dataset\"\n\n    def long_description(self):\n        return \"\"\"Value must be a Dataset or a valid identifier of a Dataset\n        (e.g. a path)\"\"\"\n",
            "header": {
                "file": {
                    "path": "datalad/distribution/dataset.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "061006b8a",
                "new_commit_hash": "644be3d7c",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/datalad/distribution/dataset.py"
            },
            "plus_file": {
                "path": "b/datalad/distribution/dataset.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 27,
                            "length": 7
                        },
                        "new_range": {
                            "start": 27,
                            "length": 7
                        },
                        "section": "lgr = logging.getLogger('datalad.dataset')"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "def resolve_path(path, ds=None):",
                                "type": "context"
                            },
                            {
                                "content": "    \"\"\"Resolve a path specification (against a Dataset location)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    Any explicit path (absolute or relative) is return as an absolute path.",
                                "type": "deleted"
                            },
                            {
                                "content": "    Any explicit path (absolute or relative) is returned as an absolute path.",
                                "type": "added"
                            },
                            {
                                "content": "    In case of an explicit relative path, the current working directory is",
                                "type": "context"
                            },
                            {
                                "content": "    used as a reference. Any non-explicit relative path is resolved against",
                                "type": "context"
                            },
                            {
                                "content": "    as dataset location, i.e. considered relative to the location of the",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "datalad/distribution/dataset.py",
                            "type": "function",
                            "name": "resolve_path",
                            "content": "def resolve_path(path, ds=None):\n    \"\"\"Resolve a path specification (against a Dataset location)\n\n    Any explicit path (absolute or relative) is return as an absolute path.\n    In case of an explicit relative path, the current working directory is\n    used as a reference. Any non-explicit relative path is resolved against\n    as dataset location, i.e. considered relative to the location of the\n    dataset. If no dataset is provided, the current working directory is\n    used.\n\n    Returns\n    -------\n    Absolute path\n    \"\"\"\n    path = expandpath(path, force_absolute=False)\n    if is_explicit_path(path):\n        return abspath(path)\n    if ds is None:\n        # no dataset given, use CWD as reference\n        # TODO: Check whether we should use PWD instead of CWD here. Is it done\n        # by abspath?\n        return abspath(path)\n    else:\n        return normpath(opj(ds.path, path))",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 27,
                            "end_lineno": 50,
                            "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\nimport calendar\nimport email.utils\nimport gzip\nimport os\nimport re\nimport shutil\nimport time\n\nfrom collections import OrderedDict\nfrom os.path import abspath, isabs\n\nfrom six import string_types\nfrom six import iteritems\nfrom six.moves.urllib.request import urlopen, Request\nfrom six.moves.urllib.parse import quote as urlquote, unquote as urlunquote\nfrom six.moves.urllib.parse import urljoin, urlparse, urlsplit, urlunsplit, urlunparse, ParseResult\nfrom six.moves.urllib.parse import parse_qsl\nfrom six.moves.urllib.parse import urlencode\nfrom six.moves.urllib.error import URLError\n\nfrom datalad.utils import on_windows\n\nfrom datalad.utils import auto_repr\n# TODO not sure what needs to use `six` here yet\nimport requests\n\nimport logging\nlgr = logging.getLogger('datalad.network')\n\n\ndef get_response_disposition_filename(s):\n    \"\"\"Given a string s as from HTTP Content-Disposition field in the response\n    return possibly present filename if any\n    \"\"\"\n    if not s:\n        return None\n    # If the response has Content-Disposition, try to get filename from it\n    cd = dict(map(\n        lambda x: x.strip().split('=') if '=' in x else (x.strip(),''),\n        s.split(';')))\n    if 'filename' in cd:\n        filename = cd['filename'].strip(\"\\\"'\")\n        return filename\n    return None\n\n\ndef get_url_disposition_filename(url, headers=None):\n    \"\"\"Get filename as possibly provided by the server in Content-Disposition\n    \"\"\"\n    if headers is None:\n        request = Request(url)\n        r = retry_urlopen(request)\n        # things are different in requests\n        if 'requests.' in str(r.__class__):\n            headers = r.headers\n        else:\n            headers = r.info()\n    else:\n        r = None\n    try:\n        return get_response_disposition_filename(headers.get('Content-Disposition', ''))\n    finally:\n        if r:\n            r.close()\n\n\ndef get_url_straight_filename(url, strip=[], allowdir=False):\n    \"\"\"Get file/dir name of the last path component of the URL\n\n    Parameters\n    ----------\n    strip: list, optional\n      If provided, listed names will not be considered and their\n      parent directory will be selected\n    allowdir: bool, optional\n      If url points to a \"directory\" (ends with /), empty string\n      would be returned unless allowdir is True, in which case the\n      name of the directory would be returned\n    \"\"\"\n    path = urlunquote(urlsplit(url).path)\n    path_parts = path.split('/')\n\n    if allowdir:\n        # strip empty ones\n        while len(path_parts) > 1 and not path_parts[-1]:\n            path_parts = path_parts[:-1]\n\n    if strip:\n        while path_parts and path_parts[-1] in strip:\n            path_parts = path_parts[:-1]\n\n    if path_parts:\n        return path_parts[-1]\n    else:\n        return None\n\n\ndef get_url_filename(url, headers=None, strip=[]):\n    \"\"\"Get filename from the url, first consulting server about Content-Disposition\n    \"\"\"\n    filename = get_url_disposition_filename(url, headers)\n    if filename:\n        return filename\n    return get_url_straight_filename(url, strip=[])\n\n\ndef get_url_response_stamp(url, response_info):\n    size, mtime = None, None\n    if 'Content-length' in response_info:\n        size = int(response_info['Content-length'])\n    if 'Last-modified' in response_info:\n        mtime = calendar.timegm(email.utils.parsedate(\n            response_info['Last-modified']))\n    return dict(size=size, mtime=mtime, url=url)\n\n\ndef get_tld(url):\n    \"\"\"Return top level domain from a url\n\n    Parameters\n    ----------\n    url : str\n    \"\"\"\n    # maybe use this instead to be safe:  https://pypi.python.org/pypi/tld\n    if not url.strip():\n        raise ValueError(\"Empty URL has no TLD\")\n    rec = urlsplit(url)\n    if not rec.netloc:\n        if not rec.scheme:\n            # There were no scheme provided thus netloc was empty -- must have been a simple 'path like'\n            return url.split('/', 1)[0]\n        else:\n            raise ValueError(\"It seems that only the scheme was provided without the net location/TLD\")\n    return rec.netloc\n\n\nfrom email.utils import parsedate_tz, mktime_tz\ndef rfc2822_to_epoch(datestr):\n    \"\"\"Given rfc2822 date/time format, return seconds since epoch\"\"\"\n    return mktime_tz(parsedate_tz(datestr))\n\n\nimport calendar\nfrom datetime import datetime\ndef iso8601_to_epoch(datestr):\n    return calendar.timegm(datetime.strptime(datestr, \"%Y-%m-%dT%H:%M:%S.%fZ\").timetuple())\n\n\ndef __urlopen_requests(url, header_vals=None):\n    # XXX Workaround for now for ... broken code\n    if isinstance(url, Request):\n        url = url.get_full_url()\n    return requests.Session().get(url)\n\n\ndef retry_urlopen(url, retries=3):\n    for t in range(retries):\n        try:\n            return __urlopen_requests(url)\n        except URLError as e:\n            lgr.warn(\"Received exception while reading %s: %s\" % (url, e))\n            if t == retries - 1:\n                # if we have reached allowed number of retries -- reraise\n                raise\n\n\ndef is_url_quoted(url):\n    \"\"\"Return either URL looks being already quoted\n    \"\"\"\n    try:\n        url_ = urlunquote(url)\n        return url != url_\n    except:  # problem with unquoting -- then it must be wasn't quoted (correctly)\n        return False\n\n\ndef same_website(url_rec, u_rec):\n    \"\"\"Decide either a link leads to external site\n\n    Parameters\n    ----------\n    url_rec: ParseResult\n      record for original url\n    u_rec: ParseResult\n      record for new url\n    \"\"\"\n    if isinstance(url_rec, string_types):\n        url_rec = urlparse(url_rec)\n    if isinstance(u_rec, string_types):\n        u_rec = urlparse(u_rec)\n    return (url_rec.netloc == u_rec.netloc)\n    # todo: collect more of sample cases.\n    # disabled below check while working on ratholeradio, since links\n    # could go to the parent and that is ok.  Figure out when it was\n    # desired not to go to the parent -- we might need explicit option\n    # and u_rec.path.startswith(url_rec.path)):\n\n\ndef dlurljoin(u_path, url):\n    url_rec = urlparse(url)  # probably duplicating parsing :-/ TODO\n    if url_rec.scheme:\n        # independent full url, so just return it\n        return url\n    if u_path.endswith('/'):  # should here be also a scheme use?\n        if url.startswith('/'):  # jump to the root\n            u_path_rec = urlparse(u_path)\n            return urljoin(urlunparse(\n                (u_path_rec.scheme, u_path_rec.netloc, '', '', '', '')), url)\n        else:\n            return os.path.join(u_path, url)\n    # TODO: recall where all this dirname came from and bring into the test\n    return urljoin(os.path.dirname(u_path) + '/', url)\n\n\n# TODO should it be a node maybe?\nclass SimpleURLStamper(object):\n    \"\"\"Gets a simple stamp about the URL: {url, time, size} of whatever was provided in the header\n    \"\"\"\n    def __init__(self, mode='full'):\n        self.mode = mode\n\n    def __call__(self, url):\n        # Extracted from above madness\n        # TODO: add mode alike to 'relaxed' where we would not\n        # care about content-disposition filename\n        # http://stackoverflow.com/questions/862173/how-to-download-a-file-using-python-in-a-smarter-way\n        request = Request(url)\n\n        # No traffic compression since we do not know how to identify\n        # exactly either it has to be decompressed\n        # request.add_header('Accept-encoding', 'gzip,deflate')\n        #\n        # TODO: think about stamping etc -- we seems to be redoing\n        # what git-annex does for us already... not really\n        r = retry_urlopen(request)\n        try:\n            r_info = r.info()\n            r_stamp = get_url_response_stamp(url, r_info)\n\n            return dict(mtime=r_stamp['mtime'], size=r_stamp['size'], url=url)\n        finally:\n            r.close()\n\n\n# TODO:  make it consistent/clear at what stage % encoding/decoding happens!\n# now it is a mix!\n\n#\n# Useful functionality in requests.models\n#  utils.requote_uri -- quote/unquote cycle to guarantee consistent appearance\n#  RequestEncodingMixin._encode_params -- Will successfully encode parameters when passed as a dict or a list of ...\n#  PreparedRequest().prepare_url(url, params) -- nicely cares about url encodings etc\n#\n\ndef _guess_ri_cls(ri):\n    \"\"\"Factory function which would determine which type of a ri a provided string is\"\"\"\n    # We assume that it is a URL and parse it. Depending on the result\n    # we might decide that it was something else ;)\n    fields = URL._pr_to_fields(urlparse(ri))\n    lgr.log(5, \"Parsed ri %s into fields %s\" % (ri, fields))\n\n    type_ = 'url'\n    # Special treatments\n    # file:///path should stay file:\n    if fields['scheme'] and fields['scheme'] not in {'file'} \\\n            and not fields['hostname']:\n        # dl+archive:... or just for ssh   hostname:path/p1\n        if '+' not in fields['scheme']:\n            type_ = 'ssh'\n            lgr.log(5, \"Assuming ssh style ri, adjusted: %s\" % (fields,))\n\n    if not fields['scheme'] and not fields['hostname']:\n        parts = _split_colon(ri)\n        if fields['path'] and '@' in fields['path'] or len(parts) > 1:\n            # user@host:path/sp1\n            # or host_name: (hence parts check)\n            # TODO: we need a regex to catch those really, parts check is not suff\n            type_ = 'ssh'\n        elif ri.startswith('//'):\n            # e.g. // or ///path\n            type_ = 'datalad'\n        else:\n            type_ = 'file'\n\n    if not fields['scheme'] and fields['hostname']:\n        # e.g. //a/path\n        type_ = 'datalad'\n\n    TYPES = {\n        'url': URL,\n        'ssh':  SSHRI,\n        'file': PathRI,\n        'datalad': DataLadRI\n    }\n    cls = TYPES[type_]\n    # just parse the ri according to regex matchint ssh \"ri\" specs\n    lgr.log(5, \"Detected %s ri\" % type_)\n    return cls\n\n\nclass RI(object):\n    \"\"\"Resource Identifier - base class and a factory for URL, SSHRI, etc\n\n    Intended to be a R/O object (i.e. no fields should be changed in-place).\n    Subclasses define specific collections of fields they care about in _FIELDS\n    class variable.\n    The idea is that this class should help to break apart a URL, while being\n    able to rebuild itself into a string representation for reuse\n\n    `RI` could be used as factory, whenever type of the resource is unknown and\n    must be guessed from the string representation.  One of the subclasses will be\n    provided as output, e.g.\n\n    >>> RI('http://example.com')\n    URL(hostname='example.com', scheme='http')\n    >>> RI('example.com:path')\n    SSHRI(hostname='example.com', path='path')\n    \"\"\"\n\n    # All of the subclasses will provide path\n    _FIELDS = (\n        'path',\n    )\n\n    __slots__ = _FIELDS + ('_fields', '_str')\n\n    def __new__(cls, ri=None, **kwargs):\n        \"\"\"Used as a possible factory for known RI types\n\n        Returns\n        -------\n        RI\n           uninitialized RI object of appropriate class with _str\n           set to string representation if was provided\n\n        \"\"\"\n        if cls is RI and ri is not None:\n            # RI class was used as a factory\n            cls = _guess_ri_cls(ri)\n\n        ri_obj = super(RI, cls).__new__(cls)\n        # Store internally original str\n        ri_obj._str = ri\n        return ri_obj\n\n    def __init__(self, ri=None, **fields):\n        \"\"\"\n        Parameters\n        ----------\n        ri: str, optional\n          String version of a resource specific for this class.  If you would like\n          a type of the resource be deduced, use RI(ri)\n        **fields: dict, optional\n          The values for the fields defined in _FIELDS class variable.\n        \"\"\"\n        if ri and (bool(ri) == bool(fields)):\n            raise ValueError(\n                \"Specify either ri or breakdown from the fields, not both. \"\n                \"Got ri=%r, fields=%r\" % (ri, fields))\n\n        self._fields = self._get_blank_fields()\n        if ri is not None:\n            fields = self._str_to_fields(ri)\n        self._set_from_fields(**fields)\n\n        # If was initialized from a string representation\n        if self._str is not None:\n            # well -- some ris might not unparse identically back\n            # strictly speaking, but let's assume they do\n            ri_ = self.as_str()\n            if ri != ri_:\n                lgr.warning(\"Parsed version of %s %r differs from original %r\",\n                            self.__class__.__name__, ri_, ri)\n\n    @classmethod\n    def _get_blank_fields(cls, **fields):\n        return OrderedDict(((f, fields.get(f, '')) for f in cls._FIELDS))\n\n    @property\n    def fields(self):\n        \"\"\"Returns shallow copy of fields to ease manipulations\"\"\"\n        return self._fields.copy()\n\n    def __repr__(self):\n        # since auto_repr doesn't support \"non-0\" values atm\n        return \"%s(%s)\" % (\n            self.__class__.__name__,\n            \", \".join([\"%s=%r\" % (k, v)\n                       for k, v in sorted(self._fields.items())\n                       if v]))\n\n    # Lazily evaluated if _str was not set\n    def __str__(self):\n        if self._str is None:\n            self._str = self.as_str()\n        return self._str\n\n    @classmethod\n    def from_str(cls, ri_str):\n        obj = cls(**cls._str_to_fields(ri_str))\n        obj._str = ri_str\n        return obj\n\n    # Apparently doesn't quite play nicely with multiple inheritence for MixIn'\n    # of regexp based URLs\n    #@abstractmethod\n    #@classmethod\n    #def _str_to_fields(cls, ri_str):\n    #    raise NotImplementedError\n\n    #\n    # If any field is specified, URL is not considered 'False', i.e.\n    # non-existing, although may be we could/shout omit having only\n    # scheme or port specified since it doesn't point to any useful\n    # location\n    #\n\n    def __nonzero__(self):\n        fields = self._fields\n        return any(fields.values())\n\n    # for PY3\n    __bool__ = __nonzero__\n\n    #\n    # Helpers to deal with internal structures and conversions\n    #\n\n    def _set_from_fields(self, **fields):\n        unknown_fields = set(fields).difference(self._FIELDS)\n        if unknown_fields:\n            raise ValueError(\"Do not know about %s. Known fields for %s are: %s\"\n                             % (unknown_fields, self.__class__, self._FIELDS))\n\n        # encode dicts for query or fragment into\n        for f in {'query', 'fragment'}:\n            v = fields.get(f)\n            if isinstance(v, dict):\n\n                ev = urlencode(v)\n                # / is reserved char within query\n                if f == 'fragment' and '%2F' not in str(v):\n                    # but seems to be ok'ish within the fragment which is\n                    # the last element of URI and anyways used only by the\n                    # client (i.e. by us here if used to compose the URL)\n                    # so let's return / back for clarity if there were no\n                    # awkward %2F to startswith\n                    ev = ev.replace('%2F', '/')\n                fields[f] = ev\n\n        self._fields.update(fields)\n\n    #\n    # Quick comparators\n    #\n\n    def __eq__(self, other):\n        if not isinstance(other, RI):\n            other = RI(other)\n        return isinstance(other, self.__class__) and dict(other._fields) == dict(self._fields)\n\n    def __ne__(self, other):\n        return not (self == other)\n\n    def __getattribute__(self, item):\n        if item.startswith('_') or item not in self._FIELDS:\n            return super(RI, self).__getattribute__(item)\n        else:\n            return self._fields[item]\n\n\nclass URL(RI):\n    \"\"\"Universal resource locator\n\n    Although largely decorating urlparse.ParseResult, it\n    - doesn't mandate providing all parts of the URL\n    - doesn't require netloc but rather asks for separate username, password, and hostname\n    \"\"\"\n\n    _FIELDS = RI._FIELDS + (\n        'scheme',\n        'username',\n        'password',\n        'hostname', 'port',\n        'query',\n        'fragment',\n    )\n\n    def as_str(self):\n        \"\"\"Render URL as a string\"\"\"\n        return urlunparse(self.to_pr())\n\n    @classmethod\n    def _str_to_fields(cls, url_str):\n        fields = URL._pr_to_fields(urlparse(url_str))\n        fields['path'] = urlunquote(fields['path'])\n        return fields\n\n    def to_pr(self):\n        \"\"\"Convert URL to urlparse.ParseResults namedtuple\"\"\"\n        return self._fields_to_pr(self._fields)\n\n    @classmethod\n    def _fields_to_pr(cls, fields):\n        \"\"\"Recompose back fields dict to ParseResult\"\"\"\n        netloc = fields['username'] or ''\n        if fields['password']:\n            netloc += ':' + fields['password']\n        if netloc:\n            netloc += '@'\n        netloc += fields['hostname']\n        if fields['port']:\n            netloc += ':%s' % fields['port']\n\n        pr_fields = {\n            f: fields[f]\n            for f in cls._FIELDS\n            if f not in ('hostname', 'password', 'username', 'port')\n        }\n        pr_fields['netloc'] = netloc\n        pr_fields['params'] = ''\n        # We need to quote the path\n        pr_fields['path'] = urlquote(pr_fields['path'])\n        # TODO: figure out what to do with query/fragment... one step at a time\n        return ParseResult(**pr_fields)\n\n    @classmethod\n    def _pr_to_fields(cls, pr):\n        \"\"\"ParseResult is a tuple so immutable, which complicates adjusting it\n\n        This function converts ParseResult into dict\"\"\"\n\n        if pr.params:\n            lgr.warning(\"ParseResults contains params %r, which will be ignored\"\n                        % (pr.params,))\n\n        # can't use just pr._asdict since we care to ask those properties\n        # such as .port , .hostname etc\n        # Forcing '' instead of None since those properties (.hostname), .password,\n        # .username return None if not available and we decided to uniformize\n        return {f: (getattr(pr, f) or '') for f in cls._FIELDS}\n\n    #\n    # Access helpers\n    #\n\n    def _parse_qs(self, s, auto_delist=True):\n        \"\"\"Helper around parse_qs to strip unneeded 'list'ing etc and return a dict of key=values\"\"\"\n        if not s:\n            return {}\n        out = OrderedDict(parse_qsl(s, 1))\n        if not auto_delist:\n            return out\n        for k in out:\n            v = out[k]\n            if isinstance(v, list) and len(v) == 1:\n                v = v[0]\n                out[k] = None if v == '' else v\n        return out\n\n    @property\n    def query_dict(self):\n        return self._parse_qs(self.query)\n\n    @property\n    def fragment_dict(self):\n        return self._parse_qs(self.fragment)\n\n\nclass PathRI(RI):\n    \"\"\"RI pointing to a (local) file/directory\"\"\"\n    def as_str(self):\n        return self.path\n\n    @classmethod\n    def _str_to_fields(cls, url_str):\n        return dict(path=url_str)\n\n\nclass RegexBasedURLMixin(object):\n    \"\"\"Base class for URLs which we could simple parse using regular expressions\"\"\"\n\n    _REGEX = None\n\n    # not used ATM but possible ;)\n    # @classmethod\n    # def is_str_matches(cls, url_str):\n    #     return bool(cls._REGEX.match(url_str))\n\n    @classmethod\n    def _str_to_fields(cls, url_str):\n        re_match = cls._REGEX.match(url_str)\n        if not re_match:\n            # TODO: custom error?\n            raise ValueError(\n                \"Possibly incorrectly determined string %r correspond to %s address\"\n                \" -- it failed matching regex. Dunno how to handle. Contact developers\"\n                % (cls, url_str,)\n            )\n        fields = cls._get_blank_fields()\n        fields.update({k: v for k, v in iteritems(re_match.groupdict()) if v})\n        cls._normalize_fields(fields)\n        return fields\n\n    @classmethod\n    def _normalize_fields(self, fields):\n        \"\"\"Helper to be ran if any of the fields need to be normalized after parsing\"\"\"\n        pass\n\n\nclass SSHRI(RI, RegexBasedURLMixin):\n    \"\"\"RI pointing to a remote location reachable via SSH\"\"\"\n\n    _FIELDS = RI._FIELDS + (\n        'username',\n        'hostname',\n        'port',\n    )\n\n    _REGEX = re.compile(r'((?P<username>\\S*)@)?(?P<hostname>[^:]+)(\\:(?P<path>.*))?$')\n\n    @classmethod\n    def _normalize_fields(cls, fields):\n        if fields['path'] and fields['path'].startswith('//'):\n            # Let's normalize for now to avoid multiple leading slashes\n            fields['path'] = '/' + fields['path'].lstrip('/')\n        # escape path so we have direct representation of the path to work with\n        fields['path'] = unescape_ssh_path(fields['path'])\n\n    def as_str(self):\n        fields = self.fields  # copy so we could escape symbols\n        url_fmt = '{hostname}'\n        if fields['username']:\n            url_fmt = \"{username}@\" + url_fmt\n        if fields['path']:\n            url_fmt += ':{path}'\n        fields['path'] = escape_ssh_path(fields['path'])\n        return url_fmt.format(**fields)\n\n\nclass DataLadRI(RI, RegexBasedURLMixin):\n    \"\"\"RI pointing to datasets within central DataLad super-dataset\"\"\"\n\n    _FIELDS = RI._FIELDS + (\n        'remote',\n    )\n\n    # For now or forever we don't deal with any fragments or other special stuff\n    _REGEX = re.compile(r'//(?P<remote>[^\\s/]*)/(?P<path>.*)$')\n\n    # do they need to be normalized??? loosing track ...\n\n    def as_str(self):\n        return \"//{remote}/{path}\".format(**self._fields)\n\n\ndef _split_colon(s, maxsplit=1):\n    \"\"\"Split on unescaped colon\"\"\"\n    return re.compile(r'(?<!\\\\):').split(s, maxsplit=maxsplit)\n\n# \\ should be first to deal with\n_SSH_ESCAPED_CHARACTERS = '\\\\#&;`|*?~<>^()[]{}$\\'\" '\n\n\n# TODO: RF using re.sub\ndef escape_ssh_path(path):\n    \"\"\"Escape all special characters present in the path\"\"\"\n    for c in _SSH_ESCAPED_CHARACTERS:\n        if c in path:\n            path = path.replace(c, '\\\\' + c)\n    return path\n\n\ndef unescape_ssh_path(path):\n    \"\"\"Un-escape all special characters present in the path\"\"\"\n    for c in _SSH_ESCAPED_CHARACTERS[::-1]:\n        if c in path:\n            path = path.replace('\\\\' + c, c)\n    return path\n\n\ndef parse_url_opts(url):\n    \"\"\"Given a string with url-style query, split into content before # and options as dict\"\"\"\n    url = URL(url)\n    # we need to filter out query and fragment to get the base url\n    fields = url.fields\n    fields.pop('query')\n    fields.pop('fragment')\n    opts = url.query_dict\n    return str(URL(**fields)), opts\n\n\n# TODO: should we just define URL.good_for_git or smth like that? ;)\n# although git also understands regular paths\ndef is_url(s):\n    \"\"\"Returns whether a string looks like something what datalad should treat as a URL\n\n    This includes ssh \"urls\" which git understands.\n    \"\"\"\n    try:\n        ri = RI(s)\n    except:\n        return False\n    return isinstance(ri, (URL, SSHRI))\n\n\n# TODO: better name? additionally may be move to SSHRI.is_valid() or sth.\ndef is_ssh(ri):\n    \"\"\"helper to determine, whether `ri` requires an SSH connection\n\n    Parameters\n    ----------\n    ri: str or RI\n\n    Returns\n    -------\n    bool\n    \"\"\"\n\n    # not exactly fitting the doc, but we actually can deal not necessarily with\n    # string or RI only, but with everything RI itself can deal with:\n    _ri = RI(ri) if not isinstance(ri, RI) else ri\n\n    return isinstance(_ri, SSHRI) or \\\n           (isinstance(_ri, URL) and _ri.scheme == 'ssh')\n\n\n#### windows workaround ###\n# TODO: There should be a better way\ndef get_local_file_url(fname):\n    \"\"\"Return OS specific URL pointing to a local file\n\n    Parameters\n    ----------\n    fname : string\n        Filename.  If not absolute, abspath is used\n    \"\"\"\n    fname = fname if isabs(fname) else abspath(fname)\n    if on_windows:\n        fname_rep = fname.replace('\\\\', '/')\n        furl = \"file:///%s\" % urlquote(fname_rep)\n        lgr.debug(\"Replaced '\\\\' in file\\'s url: %s\" % furl)\n    else:\n        # TODO:  need to fix for all the encoding etc\n        furl = str(URL(scheme='file', path=fname))\n    return furl\n\n\ndef get_local_path_from_url(url):\n    \"\"\"If given a file:// URL, returns a local path, if possible.\n\n    Raises `ValueError` if not possible, for example, if the URL\n    scheme is different, or if the `host` isn't empty or 'localhost'\n\n    The returned path is always absolute.\n    \"\"\"\n    urlparts = urlsplit(url)\n    if not urlparts.scheme == 'file':\n        raise ValueError(\n            \"Non 'file://' URL cannot be resolved to a local path\")\n    if not (urlparts.netloc in ('', 'localhost', '::1') \\\n            or urlparts.netloc.startswith('127.')):\n        raise ValueError(\"file:// URL does not point to 'localhost'\")\n    return urlunquote(urlparts.path)\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\nimport calendar\nimport email.utils\nimport gzip\nimport os\nimport re\nimport shutil\nimport time\n\nfrom collections import OrderedDict\nfrom os.path import abspath, isabs\n\nfrom six import string_types\nfrom six import iteritems\nfrom six.moves.urllib.request import urlopen, Request\nfrom six.moves.urllib.parse import quote as urlquote, unquote as urlunquote\nfrom six.moves.urllib.parse import urljoin, urlparse, urlsplit, urlunsplit, urlunparse, ParseResult\nfrom six.moves.urllib.parse import parse_qsl\nfrom six.moves.urllib.parse import urlencode\nfrom six.moves.urllib.error import URLError\n\nfrom datalad.utils import on_windows\n\nfrom datalad.utils import auto_repr\n# TODO not sure what needs to use `six` here yet\nimport requests\n\nimport logging\nlgr = logging.getLogger('datalad.network')\n\n\ndef get_response_disposition_filename(s):\n    \"\"\"Given a string s as from HTTP Content-Disposition field in the response\n    return possibly present filename if any\n    \"\"\"\n    if not s:\n        return None\n    # If the response has Content-Disposition, try to get filename from it\n    cd = dict(map(\n        lambda x: x.strip().split('=') if '=' in x else (x.strip(),''),\n        s.split(';')))\n    if 'filename' in cd:\n        filename = cd['filename'].strip(\"\\\"'\")\n        return filename\n    return None\n\n\ndef get_url_disposition_filename(url, headers=None):\n    \"\"\"Get filename as possibly provided by the server in Content-Disposition\n    \"\"\"\n    if headers is None:\n        request = Request(url)\n        r = retry_urlopen(request)\n        # things are different in requests\n        if 'requests.' in str(r.__class__):\n            headers = r.headers\n        else:\n            headers = r.info()\n    else:\n        r = None\n    try:\n        return get_response_disposition_filename(headers.get('Content-Disposition', ''))\n    finally:\n        if r:\n            r.close()\n\n\ndef get_url_straight_filename(url, strip=[], allowdir=False):\n    \"\"\"Get file/dir name of the last path component of the URL\n\n    Parameters\n    ----------\n    strip: list, optional\n      If provided, listed names will not be considered and their\n      parent directory will be selected\n    allowdir: bool, optional\n      If url points to a \"directory\" (ends with /), empty string\n      would be returned unless allowdir is True, in which case the\n      name of the directory would be returned\n    \"\"\"\n    path = urlunquote(urlsplit(url).path)\n    path_parts = path.split('/')\n\n    if allowdir:\n        # strip empty ones\n        while len(path_parts) > 1 and not path_parts[-1]:\n            path_parts = path_parts[:-1]\n\n    if strip:\n        while path_parts and path_parts[-1] in strip:\n            path_parts = path_parts[:-1]\n\n    if path_parts:\n        return path_parts[-1]\n    else:\n        return None\n\n\ndef get_url_filename(url, headers=None, strip=[]):\n    \"\"\"Get filename from the url, first consulting server about Content-Disposition\n    \"\"\"\n    filename = get_url_disposition_filename(url, headers)\n    if filename:\n        return filename\n    return get_url_straight_filename(url, strip=[])\n\n\ndef get_url_response_stamp(url, response_info):\n    size, mtime = None, None\n    if 'Content-length' in response_info:\n        size = int(response_info['Content-length'])\n    if 'Last-modified' in response_info:\n        mtime = calendar.timegm(email.utils.parsedate(\n            response_info['Last-modified']))\n    return dict(size=size, mtime=mtime, url=url)\n\n\ndef get_tld(url):\n    \"\"\"Return top level domain from a url\n\n    Parameters\n    ----------\n    url : str\n    \"\"\"\n    # maybe use this instead to be safe:  https://pypi.python.org/pypi/tld\n    if not url.strip():\n        raise ValueError(\"Empty URL has no TLD\")\n    rec = urlsplit(url)\n    if not rec.netloc:\n        if not rec.scheme:\n            # There were no scheme provided thus netloc was empty -- must have been a simple 'path like'\n            return url.split('/', 1)[0]\n        else:\n            raise ValueError(\"It seems that only the scheme was provided without the net location/TLD\")\n    return rec.netloc\n\n\nfrom email.utils import parsedate_tz, mktime_tz\ndef rfc2822_to_epoch(datestr):\n    \"\"\"Given rfc2822 date/time format, return seconds since epoch\"\"\"\n    return mktime_tz(parsedate_tz(datestr))\n\n\nimport calendar\nfrom datetime import datetime\ndef iso8601_to_epoch(datestr):\n    return calendar.timegm(datetime.strptime(datestr, \"%Y-%m-%dT%H:%M:%S.%fZ\").timetuple())\n\n\ndef __urlopen_requests(url, header_vals=None):\n    # XXX Workaround for now for ... broken code\n    if isinstance(url, Request):\n        url = url.get_full_url()\n    return requests.Session().get(url)\n\n\ndef retry_urlopen(url, retries=3):\n    for t in range(retries):\n        try:\n            return __urlopen_requests(url)\n        except URLError as e:\n            lgr.warn(\"Received exception while reading %s: %s\" % (url, e))\n            if t == retries - 1:\n                # if we have reached allowed number of retries -- reraise\n                raise\n\n\ndef is_url_quoted(url):\n    \"\"\"Return either URL looks being already quoted\n    \"\"\"\n    try:\n        url_ = urlunquote(url)\n        return url != url_\n    except:  # problem with unquoting -- then it must be wasn't quoted (correctly)\n        return False\n\n\ndef same_website(url_rec, u_rec):\n    \"\"\"Decide either a link leads to external site\n\n    Parameters\n    ----------\n    url_rec: ParseResult\n      record for original url\n    u_rec: ParseResult\n      record for new url\n    \"\"\"\n    if isinstance(url_rec, string_types):\n        url_rec = urlparse(url_rec)\n    if isinstance(u_rec, string_types):\n        u_rec = urlparse(u_rec)\n    return (url_rec.netloc == u_rec.netloc)\n    # todo: collect more of sample cases.\n    # disabled below check while working on ratholeradio, since links\n    # could go to the parent and that is ok.  Figure out when it was\n    # desired not to go to the parent -- we might need explicit option\n    # and u_rec.path.startswith(url_rec.path)):\n\n\ndef dlurljoin(u_path, url):\n    url_rec = urlparse(url)  # probably duplicating parsing :-/ TODO\n    if url_rec.scheme:\n        # independent full url, so just return it\n        return url\n    if u_path.endswith('/'):  # should here be also a scheme use?\n        if url.startswith('/'):  # jump to the root\n            u_path_rec = urlparse(u_path)\n            return urljoin(urlunparse(\n                (u_path_rec.scheme, u_path_rec.netloc, '', '', '', '')), url)\n        else:\n            return os.path.join(u_path, url)\n    # TODO: recall where all this dirname came from and bring into the test\n    return urljoin(os.path.dirname(u_path) + '/', url)\n\n\n# TODO should it be a node maybe?\nclass SimpleURLStamper(object):\n    \"\"\"Gets a simple stamp about the URL: {url, time, size} of whatever was provided in the header\n    \"\"\"\n    def __init__(self, mode='full'):\n        self.mode = mode\n\n    def __call__(self, url):\n        # Extracted from above madness\n        # TODO: add mode alike to 'relaxed' where we would not\n        # care about content-disposition filename\n        # http://stackoverflow.com/questions/862173/how-to-download-a-file-using-python-in-a-smarter-way\n        request = Request(url)\n\n        # No traffic compression since we do not know how to identify\n        # exactly either it has to be decompressed\n        # request.add_header('Accept-encoding', 'gzip,deflate')\n        #\n        # TODO: think about stamping etc -- we seems to be redoing\n        # what git-annex does for us already... not really\n        r = retry_urlopen(request)\n        try:\n            r_info = r.info()\n            r_stamp = get_url_response_stamp(url, r_info)\n\n            return dict(mtime=r_stamp['mtime'], size=r_stamp['size'], url=url)\n        finally:\n            r.close()\n\n\n# TODO:  make it consistent/clear at what stage % encoding/decoding happens!\n# now it is a mix!\n\n#\n# Useful functionality in requests.models\n#  utils.requote_uri -- quote/unquote cycle to guarantee consistent appearance\n#  RequestEncodingMixin._encode_params -- Will successfully encode parameters when passed as a dict or a list of ...\n#  PreparedRequest().prepare_url(url, params) -- nicely cares about url encodings etc\n#\n\ndef _guess_ri_cls(ri):\n    \"\"\"Factory function which would determine which type of a ri a provided string is\"\"\"\n    # We assume that it is a URL and parse it. Depending on the result\n    # we might decide that it was something else ;)\n    fields = URL._pr_to_fields(urlparse(ri))\n    lgr.log(5, \"Parsed ri %s into fields %s\" % (ri, fields))\n\n    type_ = 'url'\n    # Special treatments\n    # file:///path should stay file:\n    if fields['scheme'] and fields['scheme'] not in {'file'} \\\n            and not fields['hostname']:\n        # dl+archive:... or just for ssh   hostname:path/p1\n        if '+' not in fields['scheme']:\n            type_ = 'ssh'\n            lgr.log(5, \"Assuming ssh style ri, adjusted: %s\" % (fields,))\n\n    if not fields['scheme'] and not fields['hostname']:\n        parts = _split_colon(ri)\n        if fields['path'] and '@' in fields['path'] or len(parts) > 1:\n            # user@host:path/sp1\n            # or host_name: (hence parts check)\n            # TODO: we need a regex to catch those really, parts check is not suff\n            type_ = 'ssh'\n        elif ri.startswith('//'):\n            # e.g. // or ///path\n            type_ = 'datalad'\n        else:\n            type_ = 'file'\n\n    if not fields['scheme'] and fields['hostname']:\n        # e.g. //a/path\n        type_ = 'datalad'\n\n    TYPES = {\n        'url': URL,\n        'ssh':  SSHRI,\n        'file': PathRI,\n        'datalad': DataLadRI\n    }\n    cls = TYPES[type_]\n    # just parse the ri according to regex matchint ssh \"ri\" specs\n    lgr.log(5, \"Detected %s ri\" % type_)\n    return cls\n\n\nclass RI(object):\n    \"\"\"Resource Identifier - base class and a factory for URL, SSHRI, etc\n\n    Intended to be a R/O object (i.e. no fields should be changed in-place).\n    Subclasses define specific collections of fields they care about in _FIELDS\n    class variable.\n    The idea is that this class should help to break apart a URL, while being\n    able to rebuild itself into a string representation for reuse\n\n    `RI` could be used as factory, whenever type of the resource is unknown and\n    must be guessed from the string representation.  One of the subclasses will be\n    provided as output, e.g.\n\n    >>> RI('http://example.com')\n    URL(hostname='example.com', scheme='http')\n    >>> RI('example.com:path')\n    SSHRI(hostname='example.com', path='path')\n    \"\"\"\n\n    # All of the subclasses will provide path\n    _FIELDS = (\n        'path',\n    )\n\n    __slots__ = _FIELDS + ('_fields', '_str')\n\n    def __new__(cls, ri=None, **kwargs):\n        \"\"\"Used as a possible factory for known RI types\n\n        Returns\n        -------\n        RI\n           uninitialized RI object of appropriate class with _str\n           set to string representation if was provided\n\n        \"\"\"\n        if cls is RI and ri is not None:\n            # RI class was used as a factory\n            cls = _guess_ri_cls(ri)\n\n        ri_obj = super(RI, cls).__new__(cls)\n        # Store internally original str\n        ri_obj._str = ri\n        return ri_obj\n\n    def __init__(self, ri=None, **fields):\n        \"\"\"\n        Parameters\n        ----------\n        ri: str, optional\n          String version of a resource specific for this class.  If you would like\n          a type of the resource be deduced, use RI(ri)\n        **fields: dict, optional\n          The values for the fields defined in _FIELDS class variable.\n        \"\"\"\n        if ri and (bool(ri) == bool(fields)):\n            raise ValueError(\n                \"Specify either ri or breakdown from the fields, not both. \"\n                \"Got ri=%r, fields=%r\" % (ri, fields))\n\n        self._fields = self._get_blank_fields()\n        if ri is not None:\n            fields = self._str_to_fields(ri)\n        self._set_from_fields(**fields)\n\n        # If was initialized from a string representation\n        if self._str is not None:\n            # well -- some ris might not unparse identically back\n            # strictly speaking, but let's assume they do\n            ri_ = self.as_str()\n            if ri != ri_:\n                lgr.warning(\"Parsed version of %s %r differs from original %r\",\n                            self.__class__.__name__, ri_, ri)\n\n    @classmethod\n    def _get_blank_fields(cls, **fields):\n        return OrderedDict(((f, fields.get(f, '')) for f in cls._FIELDS))\n\n    @property\n    def fields(self):\n        \"\"\"Returns shallow copy of fields to ease manipulations\"\"\"\n        return self._fields.copy()\n\n    def __repr__(self):\n        # since auto_repr doesn't support \"non-0\" values atm\n        return \"%s(%s)\" % (\n            self.__class__.__name__,\n            \", \".join([\"%s=%r\" % (k, v)\n                       for k, v in sorted(self._fields.items())\n                       if v]))\n\n    # Lazily evaluated if _str was not set\n    def __str__(self):\n        if self._str is None:\n            self._str = self.as_str()\n        return self._str\n\n    @classmethod\n    def from_str(cls, ri_str):\n        obj = cls(**cls._str_to_fields(ri_str))\n        obj._str = ri_str\n        return obj\n\n    # Apparently doesn't quite play nicely with multiple inheritence for MixIn'\n    # of regexp based URLs\n    #@abstractmethod\n    #@classmethod\n    #def _str_to_fields(cls, ri_str):\n    #    raise NotImplementedError\n\n    #\n    # If any field is specified, URL is not considered 'False', i.e.\n    # non-existing, although may be we could/shout omit having only\n    # scheme or port specified since it doesn't point to any useful\n    # location\n    #\n\n    def __nonzero__(self):\n        fields = self._fields\n        return any(fields.values())\n\n    # for PY3\n    __bool__ = __nonzero__\n\n    #\n    # Helpers to deal with internal structures and conversions\n    #\n\n    def _set_from_fields(self, **fields):\n        unknown_fields = set(fields).difference(self._FIELDS)\n        if unknown_fields:\n            raise ValueError(\"Do not know about %s. Known fields for %s are: %s\"\n                             % (unknown_fields, self.__class__, self._FIELDS))\n\n        # encode dicts for query or fragment into\n        for f in {'query', 'fragment'}:\n            v = fields.get(f)\n            if isinstance(v, dict):\n\n                ev = urlencode(v)\n                # / is reserved char within query\n                if f == 'fragment' and '%2F' not in str(v):\n                    # but seems to be ok'ish within the fragment which is\n                    # the last element of URI and anyways used only by the\n                    # client (i.e. by us here if used to compose the URL)\n                    # so let's return / back for clarity if there were no\n                    # awkward %2F to startswith\n                    ev = ev.replace('%2F', '/')\n                fields[f] = ev\n\n        self._fields.update(fields)\n\n    #\n    # Quick comparators\n    #\n\n    def __eq__(self, other):\n        if not isinstance(other, RI):\n            other = RI(other)\n        return isinstance(other, self.__class__) and dict(other._fields) == dict(self._fields)\n\n    def __ne__(self, other):\n        return not (self == other)\n\n    def __getattribute__(self, item):\n        if item.startswith('_') or item not in self._FIELDS:\n            return super(RI, self).__getattribute__(item)\n        else:\n            return self._fields[item]\n\n\nclass URL(RI):\n    \"\"\"Universal resource locator\n\n    Although largely decorating urlparse.ParseResult, it\n    - doesn't mandate providing all parts of the URL\n    - doesn't require netloc but rather asks for separate username, password, and hostname\n    \"\"\"\n\n    _FIELDS = RI._FIELDS + (\n        'scheme',\n        'username',\n        'password',\n        'hostname', 'port',\n        'query',\n        'fragment',\n    )\n\n    def as_str(self):\n        \"\"\"Render URL as a string\"\"\"\n        return urlunparse(self.to_pr())\n\n    @classmethod\n    def _str_to_fields(cls, url_str):\n        fields = URL._pr_to_fields(urlparse(url_str))\n        fields['path'] = urlunquote(fields['path'])\n        return fields\n\n    def to_pr(self):\n        \"\"\"Convert URL to urlparse.ParseResults namedtuple\"\"\"\n        return self._fields_to_pr(self._fields)\n\n    @classmethod\n    def _fields_to_pr(cls, fields):\n        \"\"\"Recompose back fields dict to ParseResult\"\"\"\n        netloc = fields['username'] or ''\n        if fields['password']:\n            netloc += ':' + fields['password']\n        if netloc:\n            netloc += '@'\n        netloc += fields['hostname']\n        if fields['port']:\n            netloc += ':%s' % fields['port']\n\n        pr_fields = {\n            f: fields[f]\n            for f in cls._FIELDS\n            if f not in ('hostname', 'password', 'username', 'port')\n        }\n        pr_fields['netloc'] = netloc\n        pr_fields['params'] = ''\n        # We need to quote the path\n        pr_fields['path'] = urlquote(pr_fields['path'])\n        # TODO: figure out what to do with query/fragment... one step at a time\n        return ParseResult(**pr_fields)\n\n    @classmethod\n    def _pr_to_fields(cls, pr):\n        \"\"\"ParseResult is a tuple so immutable, which complicates adjusting it\n\n        This function converts ParseResult into dict\"\"\"\n\n        if pr.params:\n            lgr.warning(\"ParseResults contains params %r, which will be ignored\"\n                        % (pr.params,))\n\n        # can't use just pr._asdict since we care to ask those properties\n        # such as .port , .hostname etc\n        # Forcing '' instead of None since those properties (.hostname), .password,\n        # .username return None if not available and we decided to uniformize\n        return {f: (getattr(pr, f) or '') for f in cls._FIELDS}\n\n    #\n    # Access helpers\n    #\n\n    def _parse_qs(self, s, auto_delist=True):\n        \"\"\"Helper around parse_qs to strip unneeded 'list'ing etc and return a dict of key=values\"\"\"\n        if not s:\n            return {}\n        out = OrderedDict(parse_qsl(s, 1))\n        if not auto_delist:\n            return out\n        for k in out:\n            v = out[k]\n            if isinstance(v, list) and len(v) == 1:\n                v = v[0]\n                out[k] = None if v == '' else v\n        return out\n\n    @property\n    def query_dict(self):\n        return self._parse_qs(self.query)\n\n    @property\n    def fragment_dict(self):\n        return self._parse_qs(self.fragment)\n\n\nclass PathRI(RI):\n    \"\"\"RI pointing to a (local) file/directory\"\"\"\n    def as_str(self):\n        return self.path\n\n    @classmethod\n    def _str_to_fields(cls, url_str):\n        return dict(path=url_str)\n\n\nclass RegexBasedURLMixin(object):\n    \"\"\"Base class for URLs which we could simple parse using regular expressions\"\"\"\n\n    _REGEX = None\n\n    # not used ATM but possible ;)\n    # @classmethod\n    # def is_str_matches(cls, url_str):\n    #     return bool(cls._REGEX.match(url_str))\n\n    @classmethod\n    def _str_to_fields(cls, url_str):\n        re_match = cls._REGEX.match(url_str)\n        if not re_match:\n            # TODO: custom error?\n            raise ValueError(\n                \"Possibly incorrectly determined string %r correspond to %s address\"\n                \" -- it failed matching regex. Dunno how to handle. Contact developers\"\n                % (cls, url_str,)\n            )\n        fields = cls._get_blank_fields()\n        fields.update({k: v for k, v in iteritems(re_match.groupdict()) if v})\n        cls._normalize_fields(fields)\n        return fields\n\n    @classmethod\n    def _normalize_fields(self, fields):\n        \"\"\"Helper to be ran if any of the fields need to be normalized after parsing\"\"\"\n        pass\n\n\nclass SSHRI(RI, RegexBasedURLMixin):\n    \"\"\"RI pointing to a remote location reachable via SSH\"\"\"\n\n    _FIELDS = RI._FIELDS + (\n        'username',\n        'hostname',\n        'port',\n    )\n\n    _REGEX = re.compile(r'((?P<username>\\S*)@)?(?P<hostname>[^:]+)(\\:(?P<path>.*))?$')\n\n    @classmethod\n    def _normalize_fields(cls, fields):\n        if fields['path'] and fields['path'].startswith('//'):\n            # Let's normalize for now to avoid multiple leading slashes\n            fields['path'] = '/' + fields['path'].lstrip('/')\n        # escape path so we have direct representation of the path to work with\n        fields['path'] = unescape_ssh_path(fields['path'])\n\n    def as_str(self):\n        fields = self.fields  # copy so we could escape symbols\n        url_fmt = '{hostname}'\n        if fields['username']:\n            url_fmt = \"{username}@\" + url_fmt\n        if fields['path']:\n            url_fmt += ':{path}'\n        fields['path'] = escape_ssh_path(fields['path'])\n        return url_fmt.format(**fields)\n\n\nclass DataLadRI(RI, RegexBasedURLMixin):\n    \"\"\"RI pointing to datasets within central DataLad super-dataset\"\"\"\n\n    _FIELDS = RI._FIELDS + (\n        'remote',\n    )\n\n    # For now or forever we don't deal with any fragments or other special stuff\n    _REGEX = re.compile(r'//(?P<remote>[^\\s/]*)/(?P<path>.*)$')\n\n    # do they need to be normalized??? loosing track ...\n\n    def as_str(self):\n        return \"//{remote}/{path}\".format(**self._fields)\n\n\ndef _split_colon(s, maxsplit=1):\n    \"\"\"Split on unescaped colon\"\"\"\n    return re.compile(r'(?<!\\\\):').split(s, maxsplit=maxsplit)\n\n# \\ should be first to deal with\n_SSH_ESCAPED_CHARACTERS = '\\\\#&;`|*?~<>^()[]{}$\\'\" '\n\n\n# TODO: RF using re.sub\ndef escape_ssh_path(path):\n    \"\"\"Escape all special characters present in the path\"\"\"\n    for c in _SSH_ESCAPED_CHARACTERS:\n        if c in path:\n            path = path.replace(c, '\\\\' + c)\n    return path\n\n\ndef unescape_ssh_path(path):\n    \"\"\"Un-escape all special characters present in the path\"\"\"\n    for c in _SSH_ESCAPED_CHARACTERS[::-1]:\n        if c in path:\n            path = path.replace('\\\\' + c, c)\n    return path\n\n\ndef parse_url_opts(url):\n    \"\"\"Given a string with url-style query, split into content before # and options as dict\"\"\"\n    url = URL(url)\n    # we need to filter out query and fragment to get the base url\n    fields = url.fields\n    fields.pop('query')\n    fields.pop('fragment')\n    opts = url.query_dict\n    return str(URL(**fields)), opts\n\n\n# TODO: should we just define URL.good_for_git or smth like that? ;)\n# although git also understands regular paths\ndef is_url(ri):\n    \"\"\"Returns whether argument looks like something what datalad should treat as a URL\n\n    This includes ssh \"urls\" which git understands.\n\n    Parameters\n    ----------\n    ri : str or RI\n      The resource identifier (as a string or RI) to \"analyze\"\n    \"\"\"\n    if not isinstance(ri, RI):\n        try:\n            ri = RI(ri)\n        except:\n            return False\n    return isinstance(ri, (URL, SSHRI))\n\n\n# TODO: better name? additionally may be move to SSHRI.is_valid() or sth.\ndef is_ssh(ri):\n    \"\"\"helper to determine, whether `ri` requires an SSH connection\n\n    Parameters\n    ----------\n    ri: str or RI\n\n    Returns\n    -------\n    bool\n    \"\"\"\n\n    # not exactly fitting the doc, but we actually can deal not necessarily with\n    # string or RI only, but with everything RI itself can deal with:\n    _ri = RI(ri) if not isinstance(ri, RI) else ri\n\n    return isinstance(_ri, SSHRI) or \\\n           (isinstance(_ri, URL) and _ri.scheme == 'ssh')\n\n\n#### windows workaround ###\n# TODO: There should be a better way\ndef get_local_file_url(fname):\n    \"\"\"Return OS specific URL pointing to a local file\n\n    Parameters\n    ----------\n    fname : string\n        Filename.  If not absolute, abspath is used\n    \"\"\"\n    fname = fname if isabs(fname) else abspath(fname)\n    if on_windows:\n        fname_rep = fname.replace('\\\\', '/')\n        furl = \"file:///%s\" % urlquote(fname_rep)\n        lgr.debug(\"Replaced '\\\\' in file\\'s url: %s\" % furl)\n    else:\n        # TODO:  need to fix for all the encoding etc\n        furl = str(URL(scheme='file', path=fname))\n    return furl\n\n\ndef get_local_path_from_url(url):\n    \"\"\"If given a file:// URL, returns a local path, if possible.\n\n    Raises `ValueError` if not possible, for example, if the URL\n    scheme is different, or if the `host` isn't empty or 'localhost'\n\n    The returned path is always absolute.\n    \"\"\"\n    urlparts = urlsplit(url)\n    if not urlparts.scheme == 'file':\n        raise ValueError(\n            \"Non 'file://' URL cannot be resolved to a local path\")\n    if not (urlparts.netloc in ('', 'localhost', '::1') \\\n            or urlparts.netloc.startswith('127.')):\n        raise ValueError(\"file:// URL does not point to 'localhost'\")\n    return urlunquote(urlparts.path)\n",
            "header": {
                "file": {
                    "path": "datalad/support/network.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "af42a6f1c",
                "new_commit_hash": "178445296",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/datalad/support/network.py"
            },
            "plus_file": {
                "path": "b/datalad/support/network.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 701,
                            "length": 15
                        },
                        "new_range": {
                            "start": 701,
                            "length": 21
                        },
                        "section": "def parse_url_opts(url):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "# TODO: should we just define URL.good_for_git or smth like that? ;)",
                                "type": "context"
                            },
                            {
                                "content": "# although git also understands regular paths",
                                "type": "context"
                            },
                            {
                                "content": "def is_url(s):",
                                "type": "deleted"
                            },
                            {
                                "content": "    \"\"\"Returns whether a string looks like something what datalad should treat as a URL",
                                "type": "deleted"
                            },
                            {
                                "content": "def is_url(ri):",
                                "type": "added"
                            },
                            {
                                "content": "    \"\"\"Returns whether argument looks like something what datalad should treat as a URL",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    This includes ssh \"urls\" which git understands.",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    Parameters",
                                "type": "added"
                            },
                            {
                                "content": "    ----------",
                                "type": "added"
                            },
                            {
                                "content": "    ri : str or RI",
                                "type": "added"
                            },
                            {
                                "content": "      The resource identifier (as a string or RI) to \"analyze\"",
                                "type": "added"
                            },
                            {
                                "content": "    \"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "    try:",
                                "type": "deleted"
                            },
                            {
                                "content": "        ri = RI(s)",
                                "type": "deleted"
                            },
                            {
                                "content": "    except:",
                                "type": "deleted"
                            },
                            {
                                "content": "        return False",
                                "type": "deleted"
                            },
                            {
                                "content": "    if not isinstance(ri, RI):",
                                "type": "added"
                            },
                            {
                                "content": "        try:",
                                "type": "added"
                            },
                            {
                                "content": "            ri = RI(ri)",
                                "type": "added"
                            },
                            {
                                "content": "        except:",
                                "type": "added"
                            },
                            {
                                "content": "            return False",
                                "type": "added"
                            },
                            {
                                "content": "    return isinstance(ri, (URL, SSHRI))",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "datalad/support/network.py",
                            "type": "function",
                            "name": "is_url",
                            "content": "def is_url(s):\n    \"\"\"Returns whether a string looks like something what datalad should treat as a URL\n\n    This includes ssh \"urls\" which git understands.\n    \"\"\"\n    try:\n        ri = RI(s)\n    except:\n        return False\n    return isinstance(ri, (URL, SSHRI))",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 704,
                            "end_lineno": 713,
                            "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\nimport logging\n\nfrom collections import OrderedDict\n\nfrom .utils import eq_, neq_, ok_, nok_, assert_raises\nfrom .utils import skip_if_on_windows\nfrom .utils import swallow_logs\nfrom .utils import assert_re_in\nfrom .utils import assert_in\nfrom .utils import get_most_obscure_supported_name\n\nfrom ..support.network import same_website, dlurljoin\nfrom ..support.network import get_tld\nfrom ..support.network import get_url_straight_filename\nfrom ..support.network import get_response_disposition_filename\nfrom ..support.network import parse_url_opts\nfrom ..support.network import RI\nfrom ..support.network import SSHRI\nfrom ..support.network import PathRI\nfrom ..support.network import DataLadRI\nfrom ..support.network import URL\nfrom ..support.network import _split_colon\nfrom ..support.network import is_url\nfrom ..support.network import get_local_file_url\nfrom ..support.network import get_local_path_from_url\nfrom ..support.network import is_ssh\n\ndef test_same_website():\n    ok_(same_website(\"http://a.b\", \"http://a.b/2014/01/xxx/\"))\n    ok_(same_website(\"http://a.b/page/2/\", \"http://a.b/2014/01/xxx/\"))\n    ok_(same_website(\"https://a.b/page/2/\", \"http://a.b/2014/01/xxx/\"))\n    ok_(same_website(\"http://a.b/page/2/\", \"https://a.b/2014/01/xxx/\"))\n\n\ndef test_get_tld():\n    eq_(get_tld('http://example.com'), 'example.com')\n    eq_(get_tld('http://example.com/1'), 'example.com')\n    eq_(get_tld('http://example.com/1/2'), 'example.com')\n    eq_(get_tld('example.com/1/2'), 'example.com')\n    eq_(get_tld('s3://example.com/1/2'), 'example.com')\n    assert_raises(ValueError, get_tld, \"\")\n    assert_raises(ValueError, get_tld, \"s3://\")\n    assert_raises(ValueError, get_tld, \"http://\")\n\ndef test_dlurljoin():\n    eq_(dlurljoin('http://a.b/', 'f'), 'http://a.b/f')\n    eq_(dlurljoin('http://a.b/page', 'f'), 'http://a.b/f')\n    eq_(dlurljoin('http://a.b/dir/', 'f'), 'http://a.b/dir/f')\n    eq_(dlurljoin('http://a.b/dir/', 'http://url'), 'http://url')\n    eq_(dlurljoin('http://a.b/dir/', '/'), 'http://a.b/')\n    eq_(dlurljoin('http://a.b/dir/', '/x/y'), 'http://a.b/x/y')\n\ndef _test_get_url_straight_filename(suf):\n    eq_(get_url_straight_filename('http://a.b/' + suf), '')\n    eq_(get_url_straight_filename('http://a.b/p1' + suf), 'p1')\n    eq_(get_url_straight_filename('http://a.b/p1/' + suf), '')\n    eq_(get_url_straight_filename('http://a.b/p1/' + suf, allowdir=True), 'p1')\n    eq_(get_url_straight_filename('http://a.b/p1/p2' + suf), 'p2')\n    eq_(get_url_straight_filename('http://a.b/p1/p2/' + suf), '')\n    eq_(get_url_straight_filename('http://a.b/p1/p2/' + suf, allowdir=True), 'p2')\n    eq_(get_url_straight_filename('http://a.b/p1/p2/' + suf, allowdir=True, strip=('p2', 'xxx')), 'p1')\n    eq_(get_url_straight_filename('http://a.b/p1/p2/' + suf, strip=('p2', 'xxx')), '')\n\ndef test_get_url_straight_filename():\n    yield _test_get_url_straight_filename, ''\n    yield _test_get_url_straight_filename, '#'\n    yield _test_get_url_straight_filename, '#tag'\n    yield _test_get_url_straight_filename, '#tag/obscure'\n    yield _test_get_url_straight_filename, '?param=1'\n    yield _test_get_url_straight_filename, '?param=1&another=/'\n\nfrom ..support.network import rfc2822_to_epoch\ndef test_rfc2822_to_epoch():\n    eq_(rfc2822_to_epoch(\"Thu, 16 Oct 2014 01:16:17 EDT\"), 1413436577)\n\n\ndef test_get_response_disposition_filename():\n    eq_(get_response_disposition_filename('attachment;filename=\"Part1-Subjects1-99.tar\"'), \"Part1-Subjects1-99.tar\")\n    eq_(get_response_disposition_filename('attachment'), None)\n\n\ndef test_parse_url_opts():\n    url = 'http://map.org/api/download/?id=157'\n    output = parse_url_opts(url)\n    eq_(output, ('http://map.org/api/download/', {'id': '157'}))\n\n    url = 's3://bucket/save/?key=891'\n    output = parse_url_opts(url)\n    eq_(output, ('s3://bucket/save/', {'key': '891'}))\n\n    url = 'http://map.org/api/download/?id=98&code=13'\n    output = parse_url_opts(url)\n    eq_(output, ('http://map.org/api/download/', {'id': '98', 'code': '13'}))\n\n\ndef test_split_colon():\n    eq_(_split_colon('a:b'), ['a', 'b'])\n    eq_(_split_colon('a:b:c'), ['a', 'b:c'])\n    eq_(_split_colon('a:b:c', 2), ['a', 'b', 'c'])\n    eq_(_split_colon('ab'), ['ab'])\n    eq_(_split_colon(r'a\\:b'), [r'a\\:b'])\n\n\ndef test_url_eq():\n    eq_(URL(), URL())\n    # doesn't make sense to ask what kind of a url it is an empty URL\n    #eq_(RI(), RI())\n    neq_(URL(), URL(hostname='x'))\n    # Different types aren't equal even if have the same fields values\n    neq_(URL(path='x'), PathRI(path='x'))\n    neq_(URL(hostname='x'), SSHRI(hostname='x'))\n    neq_(str(URL(hostname='x')), str(SSHRI(hostname='x')))\n\n\ndef _check_ri(ri, cls, exact_str=True, **fields):\n    \"\"\"just a helper to carry out few checks on urls\"\"\"\n    with swallow_logs(new_level=logging.WARNING) as cml:\n        ri_ = cls(**fields)\n        murl = RI(ri)\n        eq_(murl.__class__, cls)  # not just a subclass\n        eq_(murl, ri_)\n        eq_(str(RI(ri)), ri)\n        eq_(eval(repr(ri_)), ri)  # repr leads back to identical ri_\n        eq_(ri, ri_)  # just in case ;)  above should fail first if smth is wrong\n        if not exact_str:\n            assert_in('Parsed version of', cml.out)\n    (eq_ if exact_str else neq_)(ri, str(ri_))  # that we can reconstruct it EXACTLY on our examples\n    # and that we have access to all those fields\n    nok_(set(fields).difference(set(cls._FIELDS)))\n    for f, v in fields.items():\n        eq_(getattr(ri_, f), v)\n\n\ndef test_url_base():\n    # Basic checks\n    assert_raises(ValueError, URL, \"http://example.com\", hostname='example.com')\n    url = URL(\"http://example.com\")\n    eq_(url.hostname, 'example.com')\n    eq_(url.scheme, 'http')\n    eq_(url.port, '')  # not specified -- empty strings\n    eq_(url.username, '')  # not specified -- empty strings\n    eq_(repr(url), \"URL(hostname='example.com', scheme='http')\")\n    eq_(url, \"http://example.com\")  # automagic coercion in __eq__\n\n    neq_(URL(), URL(hostname='x'))\n\n    smth = URL('smth')\n    eq_(smth.hostname, '')\n    ok_(bool(smth))\n    nok_(bool(URL()))\n\n    assert_raises(ValueError, url._set_from_fields, unknown='1')\n\n    with swallow_logs(new_level=logging.WARNING) as cml:\n        # we don't \"care\" about params ATM so there is a warning if there are any\n        purl = URL(\"http://example.com/;param\")\n        eq_(str(purl), 'http://example.com/;param')  # but we do maintain original string\n        assert_in('ParseResults contains params', cml.out)\n        eq_(purl.as_str(), 'http://example.com/')\n\n\ndef test_url_samples():\n    _check_ri(\"http://example.com\", URL, scheme='http', hostname=\"example.com\")\n    # \"complete\" one for classical http\n    _check_ri(\"http://user:pw@example.com:8080/p/sp?p1=v1&p2=v2#frag\", URL,\n              scheme='http', hostname=\"example.com\", port=8080,\n              username='user', password='pw', path='/p/sp',\n              query='p1=v1&p2=v2', fragment='frag')\n\n    # sample one for ssh with specifying the scheme\n    # XXX? might be useful?  https://github.com/FriendCode/giturlparse.py\n    _check_ri(\"ssh://host/path/sp1\", URL, scheme='ssh', hostname='host', path='/path/sp1')\n    _check_ri(\"user@host:path/sp1\", SSHRI,\n              hostname='host', path='path/sp1', username='user')\n    _check_ri(\"host:path/sp1\", SSHRI, hostname='host', path='path/sp1')\n    _check_ri(\"host:path\", SSHRI, hostname='host', path='path')\n    _check_ri(\"host:/path\", SSHRI, hostname='host', path='/path')\n    _check_ri(\"user@host\", SSHRI, hostname='host', username='user')\n    # TODO!!!  should this be a legit URL like this?\n    # _check_ri(\"host\", SSHRI, hostname='host'))\n    eq_(repr(RI(\"host:path\")), \"SSHRI(hostname='host', path='path')\")\n\n    # And now perspective 'datalad', implicit=True urls pointing to the canonical center location\n    _check_ri(\"///\", DataLadRI)\n    _check_ri(\"///p/s1\", DataLadRI, path='p/s1')\n    # could be considered by someone as \"URI reference\" relative to scheme\n    _check_ri(\"//a/\", DataLadRI, remote='a')\n    _check_ri(\"//a/data\", DataLadRI, path='data', remote='a')\n\n    # here we will do custom magic allowing only schemes with + in them, such as dl+archive\n    # or not so custom as\n    _check_ri(\"hg+https://host/user/proj\", URL,\n              scheme=\"hg+https\", hostname='host', path='/user/proj')\n    # \"old\" style\n    _check_ri(\"dl+archive:KEY/path/sp1#size=123\", URL,\n              scheme='dl+archive', path='KEY/path/sp1', fragment='size=123')\n    # \"new\" style\n    _check_ri(\"dl+archive:KEY#path=path/sp1&size=123\", URL,\n              scheme='dl+archive', path='KEY', fragment='path=path/sp1&size=123')\n    # actually above one is probably wrong since we need to encode the path\n    _check_ri(\"dl+archive:KEY#path=path%2Fbsp1&size=123\", URL,\n              scheme='dl+archive', path='KEY', fragment='path=path%2Fbsp1&size=123')\n\n    #https://en.wikipedia.org/wiki/File_URI_scheme\n    _check_ri(\"file://host\", URL, scheme='file', hostname='host')\n    _check_ri(\"file://host/path/sp1\", URL, scheme='file', hostname='host', path='/path/sp1')\n    _check_ri(\"file:///path/sp1\", URL, scheme='file', path='/path/sp1')\n    _check_ri(\"file:///~/path/sp1\", URL, scheme='file', path='/~/path/sp1', exact_str=False)\n    _check_ri(\"file:///%7E/path/sp1\", URL, scheme='file', path='/~/path/sp1')\n    # not sure but let's check\n    _check_ri(\"file:///c:/path/sp1\", URL, scheme='file', path='/c:/path/sp1', exact_str=False)\n\n    # and now implicit paths or actually they are also \"URI references\"\n    _check_ri(\"f\", PathRI, path='f')\n    _check_ri(\"f/s1\", PathRI, path='f/s1')\n    _check_ri(\"/f\", PathRI, path='/f')\n    _check_ri(\"/f/s1\", PathRI, path='/f/s1')\n\n    # some github ones, just to make sure\n    _check_ri(\"git://host/user/proj\", URL, scheme=\"git\", hostname=\"host\", path=\"/user/proj\")\n    _check_ri(\"git@host:user/proj\", SSHRI, hostname=\"host\", path=\"user/proj\", username='git')\n\n    _check_ri('weired:/', SSHRI, hostname='weired', path='/')\n    # since schema is not allowing some symbols so we need to add additional check\n    _check_ri('weired_url:/', SSHRI, hostname='weired_url', path='/')\n    _check_ri('example.com:/', SSHRI, hostname='example.com', path='/')\n    _check_ri('example.com:path/sp1', SSHRI, hostname='example.com', path='path/sp1')\n    _check_ri('example.com/path/sp1\\:fname', PathRI, path='example.com/path/sp1\\:fname')\n    # ssh is as stupid as us, so we will stay \"Consistently\" dumb\n    \"\"\"\n    $> ssh example.com/path/sp1:fname\n    ssh: Could not resolve hostname example.com/path/sp1:fname: Name or service not known\n    \"\"\"\n    _check_ri('example.com/path/sp1:fname', SSHRI, hostname='example.com/path/sp1', path='fname')\n\n    # SSHRIs have .port, but it is empty\n    eq_(SSHRI(hostname='example.com').port, '')\n\n    # check that we are getting a warning logged when url can't be reconstructed\n    # precisely\n    # actually failed to come up with one -- becomes late here\n    #_check_ri(\"http://host///..//p\", scheme='http', path='/..//p')\n\n    # actually this one is good enough to trigger a warning and I still don't know\n    # what it should exactly be!?\n    with swallow_logs(new_level=logging.WARNING) as cml:\n        weired_str = 'weired://'\n        weired_url = RI(weired_str)\n        repr(weired_url)\n        assert_re_in('Parsed version of SSHRI .weired:/. differs from original .weired://.',\n                     cml.out)\n        # but we store original str\n        eq_(str(weired_url), weired_str)\n        neq_(weired_url.as_str(), weired_str)\n\n\ndef _test_url_quote_path(cls, clskwargs, target_url):\n    path = '/ \"\\';a&b&cd `| '\n    if not (cls is PathRI):\n        clskwargs['hostname'] = hostname = 'example.com'\n    url = cls(path=path, **clskwargs)\n    eq_(url.path, path)\n    if 'hostname' in clskwargs:\n        eq_(url.hostname, hostname)\n    # all nasty symbols should be quoted\n    url_str = str(url)\n    eq_(url_str, target_url)\n    # no side-effects:\n    eq_(url.path, path)\n    if 'hostname' in clskwargs:\n        eq_(url.hostname, hostname)\n\n    # and figured out and unquoted\n    url_ = RI(url_str)\n    ok_(isinstance(url_, cls))\n    eq_(url_.path, path)\n    if 'hostname' in clskwargs:\n        eq_(url.hostname, hostname)\n\n\ndef test_url_quote_path():\n    yield _test_url_quote_path, SSHRI, {}, r'example.com:/\\ \\\"' + r\"\\'\\;a\\&b\\&cd\\ \\`\\|\\ \"\n    yield _test_url_quote_path, URL, {'scheme': \"http\"}, 'http://example.com/%20%22%27%3Ba%26b%26cd%20%60%7C%20'\n    yield _test_url_quote_path, PathRI, {}, r'/ \"' + r\"';a&b&cd `| \"  # nothing is done to file:implicit\n\n\ndef test_url_compose_archive_one():\n    url = URL(scheme='dl+archive', path='KEY',\n              fragment=OrderedDict((('path', 'f/p/ s+'), ('size', 30))))\n    # funny - space is encoded as + but + is %2B\n    eq_(str(url), 'dl+archive:KEY#path=f/p/+s%2B&size=30')\n    eq_(url.fragment_dict, {'path': 'f/p/ s+', 'size': '30'})\n\n\ndef test_url_fragments_and_query():\n    url = URL(hostname=\"host\", query=OrderedDict((('a', 'x/b'), ('b', 'y'))))\n    eq_(str(url), '//host?a=x%2Fb&b=y')\n    eq_(url.query, 'a=x%2Fb&b=y')\n    eq_(url.query_dict, {'a': 'x/b', 'b': 'y'})\n\n    url = URL(hostname=\"host\", fragment=OrderedDict((('b', 'x/b'), ('a', 'y'))))\n    eq_(str(url), '//host#b=x/b&a=y')\n    eq_(url.fragment, 'b=x/b&a=y')\n    eq_(url.fragment_dict, {'a': 'y', 'b': 'x/b'})\n\n    fname = get_most_obscure_supported_name()\n    url = URL(hostname=\"host\", fragment={'a': fname})\n    eq_(url.fragment_dict, {'a': fname})\n\n\ndef test_url_dicts():\n    eq_(URL(\"http://host\").query_dict, {})\n\n\n@skip_if_on_windows\ndef test_get_url_path_on_fileurls():\n    eq_(URL('file:///a').path, '/a')\n    eq_(URL('file:///a/b').path, '/a/b')\n    eq_(URL('file:///a/b#id').path, '/a/b')\n    eq_(URL('file:///a/b?whatever').path, '/a/b')\n\n\ndef test_is_url():\n    ok_(is_url('file://localhost/some'))\n    ok_(is_url('http://localhost'))\n    ok_(is_url('ssh://me@localhost'))\n    # in current understanding it is indeed a url but an 'ssh', implicit=True, not just\n    # a useless scheme=weired with a hope to point to a netloc\n    with swallow_logs():\n        ok_(is_url('weired://'))\n    nok_(is_url('relative'))\n    nok_(is_url('/absolute'))\n    ok_(is_url('like@sshlogin'))  # actually we do allow ssh:implicit urls ATM\n    nok_(is_url(''))\n    nok_(is_url(' '))\n\n\ndef test_get_local_file_url_linux():\n    eq_(get_local_file_url('/a'), 'file:///a')\n    eq_(get_local_file_url('/a/b/c'), 'file:///a/b/c')\n    eq_(get_local_file_url('/a~'), 'file:///a%7E')\n    eq_(get_local_file_url('/a b/'), 'file:///a%20b/')\n\n\ndef test_get_local_path_from_url():\n    assert_raises(ValueError, get_local_path_from_url, 'http://some')\n    assert_raises(ValueError, get_local_path_from_url, 'file://elsewhere/some')\n    # invalid URL -- is it?  just that 'hostname' is some and no path\n    assert_raises(ValueError, get_local_path_from_url, 'file://some')\n    eq_(get_local_path_from_url('file:///some'), '/some')\n    eq_(get_local_path_from_url('file://localhost/some'), '/some')\n    eq_(get_local_path_from_url('file://::1/some'), '/some')\n    eq_(get_local_path_from_url('file://127.3.4.155/some'), '/some')\n\n\ndef test_is_ssh():\n\n    ssh_locators = [\"ssh://host\",\n                    \"ssh://host/some/where\",\n                    \"user@host:path/sp1\",\n                    \"user@host:/absloute/path/sp1\",\n                    \"host:path/sp1\",\n                    \"host:/absloute/path/sp1\",\n                    \"user@host\"]\n    for ri in ssh_locators:\n        ok_(is_ssh(ri), \"not considered ssh (string): %s\" % ri)\n        ok_(is_ssh(RI(ri)), \"not considered ssh (RI): %s\" % ri)\n\n    non_ssh_locators = [\"file://path/to\",\n                        \"/abs/path\",\n                        \"../rel/path\",\n                        \"http://example.com\",\n                        \"git://host/user/proj\",\n                        \"s3://bucket/save/?key=891\"]\n    for ri in non_ssh_locators:\n        ok_(not is_ssh(ri), \"considered ssh (string): %s\" % ri)\n        ok_(not is_ssh(RI(ri)), \"considered ssh (RI): %s\" % ri)\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\nimport logging\n\nfrom collections import OrderedDict\n\nfrom .utils import eq_, neq_, ok_, nok_, assert_raises\nfrom .utils import skip_if_on_windows\nfrom .utils import swallow_logs\nfrom .utils import assert_re_in\nfrom .utils import assert_in\nfrom .utils import get_most_obscure_supported_name\n\nfrom ..support.network import same_website, dlurljoin\nfrom ..support.network import get_tld\nfrom ..support.network import get_url_straight_filename\nfrom ..support.network import get_response_disposition_filename\nfrom ..support.network import parse_url_opts\nfrom ..support.network import RI\nfrom ..support.network import SSHRI\nfrom ..support.network import PathRI\nfrom ..support.network import DataLadRI\nfrom ..support.network import URL\nfrom ..support.network import _split_colon\nfrom ..support.network import is_url\nfrom ..support.network import get_local_file_url\nfrom ..support.network import get_local_path_from_url\nfrom ..support.network import is_ssh\n\ndef test_same_website():\n    ok_(same_website(\"http://a.b\", \"http://a.b/2014/01/xxx/\"))\n    ok_(same_website(\"http://a.b/page/2/\", \"http://a.b/2014/01/xxx/\"))\n    ok_(same_website(\"https://a.b/page/2/\", \"http://a.b/2014/01/xxx/\"))\n    ok_(same_website(\"http://a.b/page/2/\", \"https://a.b/2014/01/xxx/\"))\n\n\ndef test_get_tld():\n    eq_(get_tld('http://example.com'), 'example.com')\n    eq_(get_tld('http://example.com/1'), 'example.com')\n    eq_(get_tld('http://example.com/1/2'), 'example.com')\n    eq_(get_tld('example.com/1/2'), 'example.com')\n    eq_(get_tld('s3://example.com/1/2'), 'example.com')\n    assert_raises(ValueError, get_tld, \"\")\n    assert_raises(ValueError, get_tld, \"s3://\")\n    assert_raises(ValueError, get_tld, \"http://\")\n\ndef test_dlurljoin():\n    eq_(dlurljoin('http://a.b/', 'f'), 'http://a.b/f')\n    eq_(dlurljoin('http://a.b/page', 'f'), 'http://a.b/f')\n    eq_(dlurljoin('http://a.b/dir/', 'f'), 'http://a.b/dir/f')\n    eq_(dlurljoin('http://a.b/dir/', 'http://url'), 'http://url')\n    eq_(dlurljoin('http://a.b/dir/', '/'), 'http://a.b/')\n    eq_(dlurljoin('http://a.b/dir/', '/x/y'), 'http://a.b/x/y')\n\ndef _test_get_url_straight_filename(suf):\n    eq_(get_url_straight_filename('http://a.b/' + suf), '')\n    eq_(get_url_straight_filename('http://a.b/p1' + suf), 'p1')\n    eq_(get_url_straight_filename('http://a.b/p1/' + suf), '')\n    eq_(get_url_straight_filename('http://a.b/p1/' + suf, allowdir=True), 'p1')\n    eq_(get_url_straight_filename('http://a.b/p1/p2' + suf), 'p2')\n    eq_(get_url_straight_filename('http://a.b/p1/p2/' + suf), '')\n    eq_(get_url_straight_filename('http://a.b/p1/p2/' + suf, allowdir=True), 'p2')\n    eq_(get_url_straight_filename('http://a.b/p1/p2/' + suf, allowdir=True, strip=('p2', 'xxx')), 'p1')\n    eq_(get_url_straight_filename('http://a.b/p1/p2/' + suf, strip=('p2', 'xxx')), '')\n\ndef test_get_url_straight_filename():\n    yield _test_get_url_straight_filename, ''\n    yield _test_get_url_straight_filename, '#'\n    yield _test_get_url_straight_filename, '#tag'\n    yield _test_get_url_straight_filename, '#tag/obscure'\n    yield _test_get_url_straight_filename, '?param=1'\n    yield _test_get_url_straight_filename, '?param=1&another=/'\n\nfrom ..support.network import rfc2822_to_epoch\ndef test_rfc2822_to_epoch():\n    eq_(rfc2822_to_epoch(\"Thu, 16 Oct 2014 01:16:17 EDT\"), 1413436577)\n\n\ndef test_get_response_disposition_filename():\n    eq_(get_response_disposition_filename('attachment;filename=\"Part1-Subjects1-99.tar\"'), \"Part1-Subjects1-99.tar\")\n    eq_(get_response_disposition_filename('attachment'), None)\n\n\ndef test_parse_url_opts():\n    url = 'http://map.org/api/download/?id=157'\n    output = parse_url_opts(url)\n    eq_(output, ('http://map.org/api/download/', {'id': '157'}))\n\n    url = 's3://bucket/save/?key=891'\n    output = parse_url_opts(url)\n    eq_(output, ('s3://bucket/save/', {'key': '891'}))\n\n    url = 'http://map.org/api/download/?id=98&code=13'\n    output = parse_url_opts(url)\n    eq_(output, ('http://map.org/api/download/', {'id': '98', 'code': '13'}))\n\n\ndef test_split_colon():\n    eq_(_split_colon('a:b'), ['a', 'b'])\n    eq_(_split_colon('a:b:c'), ['a', 'b:c'])\n    eq_(_split_colon('a:b:c', 2), ['a', 'b', 'c'])\n    eq_(_split_colon('ab'), ['ab'])\n    eq_(_split_colon(r'a\\:b'), [r'a\\:b'])\n\n\ndef test_url_eq():\n    eq_(URL(), URL())\n    # doesn't make sense to ask what kind of a url it is an empty URL\n    #eq_(RI(), RI())\n    neq_(URL(), URL(hostname='x'))\n    # Different types aren't equal even if have the same fields values\n    neq_(URL(path='x'), PathRI(path='x'))\n    neq_(URL(hostname='x'), SSHRI(hostname='x'))\n    neq_(str(URL(hostname='x')), str(SSHRI(hostname='x')))\n\n\ndef _check_ri(ri, cls, exact_str=True, **fields):\n    \"\"\"just a helper to carry out few checks on urls\"\"\"\n    with swallow_logs(new_level=logging.WARNING) as cml:\n        ri_ = cls(**fields)\n        murl = RI(ri)\n        eq_(murl.__class__, cls)  # not just a subclass\n        eq_(murl, ri_)\n        eq_(str(RI(ri)), ri)\n        eq_(eval(repr(ri_)), ri)  # repr leads back to identical ri_\n        eq_(ri, ri_)  # just in case ;)  above should fail first if smth is wrong\n        if not exact_str:\n            assert_in('Parsed version of', cml.out)\n    (eq_ if exact_str else neq_)(ri, str(ri_))  # that we can reconstruct it EXACTLY on our examples\n    # and that we have access to all those fields\n    nok_(set(fields).difference(set(cls._FIELDS)))\n    for f, v in fields.items():\n        eq_(getattr(ri_, f), v)\n\n\ndef test_url_base():\n    # Basic checks\n    assert_raises(ValueError, URL, \"http://example.com\", hostname='example.com')\n    url = URL(\"http://example.com\")\n    eq_(url.hostname, 'example.com')\n    eq_(url.scheme, 'http')\n    eq_(url.port, '')  # not specified -- empty strings\n    eq_(url.username, '')  # not specified -- empty strings\n    eq_(repr(url), \"URL(hostname='example.com', scheme='http')\")\n    eq_(url, \"http://example.com\")  # automagic coercion in __eq__\n\n    neq_(URL(), URL(hostname='x'))\n\n    smth = URL('smth')\n    eq_(smth.hostname, '')\n    ok_(bool(smth))\n    nok_(bool(URL()))\n\n    assert_raises(ValueError, url._set_from_fields, unknown='1')\n\n    with swallow_logs(new_level=logging.WARNING) as cml:\n        # we don't \"care\" about params ATM so there is a warning if there are any\n        purl = URL(\"http://example.com/;param\")\n        eq_(str(purl), 'http://example.com/;param')  # but we do maintain original string\n        assert_in('ParseResults contains params', cml.out)\n        eq_(purl.as_str(), 'http://example.com/')\n\n\ndef test_url_samples():\n    _check_ri(\"http://example.com\", URL, scheme='http', hostname=\"example.com\")\n    # \"complete\" one for classical http\n    _check_ri(\"http://user:pw@example.com:8080/p/sp?p1=v1&p2=v2#frag\", URL,\n              scheme='http', hostname=\"example.com\", port=8080,\n              username='user', password='pw', path='/p/sp',\n              query='p1=v1&p2=v2', fragment='frag')\n\n    # sample one for ssh with specifying the scheme\n    # XXX? might be useful?  https://github.com/FriendCode/giturlparse.py\n    _check_ri(\"ssh://host/path/sp1\", URL, scheme='ssh', hostname='host', path='/path/sp1')\n    _check_ri(\"user@host:path/sp1\", SSHRI,\n              hostname='host', path='path/sp1', username='user')\n    _check_ri(\"host:path/sp1\", SSHRI, hostname='host', path='path/sp1')\n    _check_ri(\"host:path\", SSHRI, hostname='host', path='path')\n    _check_ri(\"host:/path\", SSHRI, hostname='host', path='/path')\n    _check_ri(\"user@host\", SSHRI, hostname='host', username='user')\n    # TODO!!!  should this be a legit URL like this?\n    # _check_ri(\"host\", SSHRI, hostname='host'))\n    eq_(repr(RI(\"host:path\")), \"SSHRI(hostname='host', path='path')\")\n\n    # And now perspective 'datalad', implicit=True urls pointing to the canonical center location\n    _check_ri(\"///\", DataLadRI)\n    _check_ri(\"///p/s1\", DataLadRI, path='p/s1')\n    # could be considered by someone as \"URI reference\" relative to scheme\n    _check_ri(\"//a/\", DataLadRI, remote='a')\n    _check_ri(\"//a/data\", DataLadRI, path='data', remote='a')\n\n    # here we will do custom magic allowing only schemes with + in them, such as dl+archive\n    # or not so custom as\n    _check_ri(\"hg+https://host/user/proj\", URL,\n              scheme=\"hg+https\", hostname='host', path='/user/proj')\n    # \"old\" style\n    _check_ri(\"dl+archive:KEY/path/sp1#size=123\", URL,\n              scheme='dl+archive', path='KEY/path/sp1', fragment='size=123')\n    # \"new\" style\n    _check_ri(\"dl+archive:KEY#path=path/sp1&size=123\", URL,\n              scheme='dl+archive', path='KEY', fragment='path=path/sp1&size=123')\n    # actually above one is probably wrong since we need to encode the path\n    _check_ri(\"dl+archive:KEY#path=path%2Fbsp1&size=123\", URL,\n              scheme='dl+archive', path='KEY', fragment='path=path%2Fbsp1&size=123')\n\n    #https://en.wikipedia.org/wiki/File_URI_scheme\n    _check_ri(\"file://host\", URL, scheme='file', hostname='host')\n    _check_ri(\"file://host/path/sp1\", URL, scheme='file', hostname='host', path='/path/sp1')\n    _check_ri(\"file:///path/sp1\", URL, scheme='file', path='/path/sp1')\n    _check_ri(\"file:///~/path/sp1\", URL, scheme='file', path='/~/path/sp1', exact_str=False)\n    _check_ri(\"file:///%7E/path/sp1\", URL, scheme='file', path='/~/path/sp1')\n    # not sure but let's check\n    _check_ri(\"file:///c:/path/sp1\", URL, scheme='file', path='/c:/path/sp1', exact_str=False)\n\n    # and now implicit paths or actually they are also \"URI references\"\n    _check_ri(\"f\", PathRI, path='f')\n    _check_ri(\"f/s1\", PathRI, path='f/s1')\n    _check_ri(\"/f\", PathRI, path='/f')\n    _check_ri(\"/f/s1\", PathRI, path='/f/s1')\n\n    # some github ones, just to make sure\n    _check_ri(\"git://host/user/proj\", URL, scheme=\"git\", hostname=\"host\", path=\"/user/proj\")\n    _check_ri(\"git@host:user/proj\", SSHRI, hostname=\"host\", path=\"user/proj\", username='git')\n\n    _check_ri('weired:/', SSHRI, hostname='weired', path='/')\n    # since schema is not allowing some symbols so we need to add additional check\n    _check_ri('weired_url:/', SSHRI, hostname='weired_url', path='/')\n    _check_ri('example.com:/', SSHRI, hostname='example.com', path='/')\n    _check_ri('example.com:path/sp1', SSHRI, hostname='example.com', path='path/sp1')\n    _check_ri('example.com/path/sp1\\:fname', PathRI, path='example.com/path/sp1\\:fname')\n    # ssh is as stupid as us, so we will stay \"Consistently\" dumb\n    \"\"\"\n    $> ssh example.com/path/sp1:fname\n    ssh: Could not resolve hostname example.com/path/sp1:fname: Name or service not known\n    \"\"\"\n    _check_ri('example.com/path/sp1:fname', SSHRI, hostname='example.com/path/sp1', path='fname')\n\n    # SSHRIs have .port, but it is empty\n    eq_(SSHRI(hostname='example.com').port, '')\n\n    # check that we are getting a warning logged when url can't be reconstructed\n    # precisely\n    # actually failed to come up with one -- becomes late here\n    #_check_ri(\"http://host///..//p\", scheme='http', path='/..//p')\n\n    # actually this one is good enough to trigger a warning and I still don't know\n    # what it should exactly be!?\n    with swallow_logs(new_level=logging.WARNING) as cml:\n        weired_str = 'weired://'\n        weired_url = RI(weired_str)\n        repr(weired_url)\n        assert_re_in('Parsed version of SSHRI .weired:/. differs from original .weired://.',\n                     cml.out)\n        # but we store original str\n        eq_(str(weired_url), weired_str)\n        neq_(weired_url.as_str(), weired_str)\n\n\ndef _test_url_quote_path(cls, clskwargs, target_url):\n    path = '/ \"\\';a&b&cd `| '\n    if not (cls is PathRI):\n        clskwargs['hostname'] = hostname = 'example.com'\n    url = cls(path=path, **clskwargs)\n    eq_(url.path, path)\n    if 'hostname' in clskwargs:\n        eq_(url.hostname, hostname)\n    # all nasty symbols should be quoted\n    url_str = str(url)\n    eq_(url_str, target_url)\n    # no side-effects:\n    eq_(url.path, path)\n    if 'hostname' in clskwargs:\n        eq_(url.hostname, hostname)\n\n    # and figured out and unquoted\n    url_ = RI(url_str)\n    ok_(isinstance(url_, cls))\n    eq_(url_.path, path)\n    if 'hostname' in clskwargs:\n        eq_(url.hostname, hostname)\n\n\ndef test_url_quote_path():\n    yield _test_url_quote_path, SSHRI, {}, r'example.com:/\\ \\\"' + r\"\\'\\;a\\&b\\&cd\\ \\`\\|\\ \"\n    yield _test_url_quote_path, URL, {'scheme': \"http\"}, 'http://example.com/%20%22%27%3Ba%26b%26cd%20%60%7C%20'\n    yield _test_url_quote_path, PathRI, {}, r'/ \"' + r\"';a&b&cd `| \"  # nothing is done to file:implicit\n\n\ndef test_url_compose_archive_one():\n    url = URL(scheme='dl+archive', path='KEY',\n              fragment=OrderedDict((('path', 'f/p/ s+'), ('size', 30))))\n    # funny - space is encoded as + but + is %2B\n    eq_(str(url), 'dl+archive:KEY#path=f/p/+s%2B&size=30')\n    eq_(url.fragment_dict, {'path': 'f/p/ s+', 'size': '30'})\n\n\ndef test_url_fragments_and_query():\n    url = URL(hostname=\"host\", query=OrderedDict((('a', 'x/b'), ('b', 'y'))))\n    eq_(str(url), '//host?a=x%2Fb&b=y')\n    eq_(url.query, 'a=x%2Fb&b=y')\n    eq_(url.query_dict, {'a': 'x/b', 'b': 'y'})\n\n    url = URL(hostname=\"host\", fragment=OrderedDict((('b', 'x/b'), ('a', 'y'))))\n    eq_(str(url), '//host#b=x/b&a=y')\n    eq_(url.fragment, 'b=x/b&a=y')\n    eq_(url.fragment_dict, {'a': 'y', 'b': 'x/b'})\n\n    fname = get_most_obscure_supported_name()\n    url = URL(hostname=\"host\", fragment={'a': fname})\n    eq_(url.fragment_dict, {'a': fname})\n\n\ndef test_url_dicts():\n    eq_(URL(\"http://host\").query_dict, {})\n\n\n@skip_if_on_windows\ndef test_get_url_path_on_fileurls():\n    eq_(URL('file:///a').path, '/a')\n    eq_(URL('file:///a/b').path, '/a/b')\n    eq_(URL('file:///a/b#id').path, '/a/b')\n    eq_(URL('file:///a/b?whatever').path, '/a/b')\n\n\ndef test_is_url():\n    ok_(is_url('file://localhost/some'))\n    ok_(is_url('http://localhost'))\n    ok_(is_url('ssh://me@localhost'))\n    # in current understanding it is indeed a url but an 'ssh', implicit=True, not just\n    # a useless scheme=weired with a hope to point to a netloc\n    with swallow_logs():\n        ok_(is_url('weired://'))\n    nok_(is_url('relative'))\n    nok_(is_url('/absolute'))\n    ok_(is_url('like@sshlogin'))  # actually we do allow ssh:implicit urls ATM\n    nok_(is_url(''))\n    nok_(is_url(' '))\n\n    # we can pass RI instance directly\n    ok_(is_url(RI('file://localhost/some')))\n    nok_(is_url(RI('relative')))\n\n\ndef test_get_local_file_url_linux():\n    eq_(get_local_file_url('/a'), 'file:///a')\n    eq_(get_local_file_url('/a/b/c'), 'file:///a/b/c')\n    eq_(get_local_file_url('/a~'), 'file:///a%7E')\n    eq_(get_local_file_url('/a b/'), 'file:///a%20b/')\n\n\ndef test_get_local_path_from_url():\n    assert_raises(ValueError, get_local_path_from_url, 'http://some')\n    assert_raises(ValueError, get_local_path_from_url, 'file://elsewhere/some')\n    # invalid URL -- is it?  just that 'hostname' is some and no path\n    assert_raises(ValueError, get_local_path_from_url, 'file://some')\n    eq_(get_local_path_from_url('file:///some'), '/some')\n    eq_(get_local_path_from_url('file://localhost/some'), '/some')\n    eq_(get_local_path_from_url('file://::1/some'), '/some')\n    eq_(get_local_path_from_url('file://127.3.4.155/some'), '/some')\n\n\ndef test_is_ssh():\n\n    ssh_locators = [\"ssh://host\",\n                    \"ssh://host/some/where\",\n                    \"user@host:path/sp1\",\n                    \"user@host:/absloute/path/sp1\",\n                    \"host:path/sp1\",\n                    \"host:/absloute/path/sp1\",\n                    \"user@host\"]\n    for ri in ssh_locators:\n        ok_(is_ssh(ri), \"not considered ssh (string): %s\" % ri)\n        ok_(is_ssh(RI(ri)), \"not considered ssh (RI): %s\" % ri)\n\n    non_ssh_locators = [\"file://path/to\",\n                        \"/abs/path\",\n                        \"../rel/path\",\n                        \"http://example.com\",\n                        \"git://host/user/proj\",\n                        \"s3://bucket/save/?key=891\"]\n    for ri in non_ssh_locators:\n        ok_(not is_ssh(ri), \"considered ssh (string): %s\" % ri)\n        ok_(not is_ssh(RI(ri)), \"considered ssh (RI): %s\" % ri)\n",
            "header": {
                "file": {
                    "path": "datalad/tests/test_network.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "d9a4a48d9",
                "new_commit_hash": "6d52a6f74",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/datalad/tests/test_network.py"
            },
            "plus_file": {
                "path": "b/datalad/tests/test_network.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 343,
                            "length": 6
                        },
                        "new_range": {
                            "start": 343,
                            "length": 10
                        },
                        "section": "def test_is_url():"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    nok_(is_url(''))",
                                "type": "context"
                            },
                            {
                                "content": "    nok_(is_url(' '))",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    # we can pass RI instance directly",
                                "type": "added"
                            },
                            {
                                "content": "    ok_(is_url(RI('file://localhost/some')))",
                                "type": "added"
                            },
                            {
                                "content": "    nok_(is_url(RI('relative')))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "def test_get_local_file_url_linux():",
                                "type": "context"
                            },
                            {
                                "content": "    eq_(get_local_file_url('/a'), 'file:///a')",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "datalad/tests/test_network.py",
                            "type": "function",
                            "name": "test_is_url",
                            "content": "def test_is_url():\n    ok_(is_url('file://localhost/some'))\n    ok_(is_url('http://localhost'))\n    ok_(is_url('ssh://me@localhost'))\n    # in current understanding it is indeed a url but an 'ssh', implicit=True, not just\n    # a useless scheme=weired with a hope to point to a netloc\n    with swallow_logs():\n        ok_(is_url('weired://'))\n    nok_(is_url('relative'))\n    nok_(is_url('/absolute'))\n    ok_(is_url('like@sshlogin'))  # actually we do allow ssh:implicit urls ATM\n    nok_(is_url(''))\n    nok_(is_url(' '))\n\n    # we can pass RI instance directly\n    ok_(is_url(RI('file://localhost/some')))\n    nok_(is_url(RI('relative')))",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 332,
                            "end_lineno": 348,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "3deb4d632f5f9eb628d20a42319a4d51bc253c03^",
    "new_commit_hash": "3deb4d632f5f9eb628d20a42319a4d51bc253c03",
    "commit_message": "RF: make is_url consume RI instances as well (+typo fix)",
    "commit_date": "2016-06-24T13:55:34+02:00",
    "metadata": {}
}
{
    "repo_name": "datalad",
    "new_commit_hash": "3deb4d632f5f9eb628d20a42319a4d51bc253c03",
    "test_file_codes": [
        "# 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\nimport logging\n\nfrom collections import OrderedDict\n\nfrom datalad.tests.utils import eq_, neq_, ok_, nok_, assert_raises\nfrom datalad.tests.utils import skip_if_on_windows\nfrom datalad.tests.utils import swallow_logs\nfrom datalad.tests.utils import assert_re_in\nfrom datalad.tests.utils import assert_in\nfrom datalad.tests.utils import get_most_obscure_supported_name\n\nfrom datalad.support.network import same_website, dlurljoin\nfrom datalad.support.network import get_tld\nfrom datalad.support.network import get_url_straight_filename\nfrom datalad.support.network import get_response_disposition_filename\nfrom datalad.support.network import parse_url_opts\nfrom datalad.support.network import RI\nfrom datalad.support.network import SSHRI\nfrom datalad.support.network import PathRI\nfrom datalad.support.network import DataLadRI\nfrom datalad.support.network import URL\nfrom datalad.support.network import _split_colon\nfrom datalad.support.network import is_url\nfrom datalad.support.network import get_local_file_url\nfrom datalad.support.network import get_local_path_from_url\nfrom datalad.support.network import is_ssh\n\ndef test_same_website():\n    ok_(same_website(\"http://a.b\", \"http://a.b/2014/01/xxx/\"))\n    ok_(same_website(\"http://a.b/page/2/\", \"http://a.b/2014/01/xxx/\"))\n    ok_(same_website(\"https://a.b/page/2/\", \"http://a.b/2014/01/xxx/\"))\n    ok_(same_website(\"http://a.b/page/2/\", \"https://a.b/2014/01/xxx/\"))\n\n\ndef test_get_tld():\n    eq_(get_tld('http://example.com'), 'example.com')\n    eq_(get_tld('http://example.com/1'), 'example.com')\n    eq_(get_tld('http://example.com/1/2'), 'example.com')\n    eq_(get_tld('example.com/1/2'), 'example.com')\n    eq_(get_tld('s3://example.com/1/2'), 'example.com')\n    assert_raises(ValueError, get_tld, \"\")\n    assert_raises(ValueError, get_tld, \"s3://\")\n    assert_raises(ValueError, get_tld, \"http://\")\n\ndef test_dlurljoin():\n    eq_(dlurljoin('http://a.b/', 'f'), 'http://a.b/f')\n    eq_(dlurljoin('http://a.b/page', 'f'), 'http://a.b/f')\n    eq_(dlurljoin('http://a.b/dir/', 'f'), 'http://a.b/dir/f')\n    eq_(dlurljoin('http://a.b/dir/', 'http://url'), 'http://url')\n    eq_(dlurljoin('http://a.b/dir/', '/'), 'http://a.b/')\n    eq_(dlurljoin('http://a.b/dir/', '/x/y'), 'http://a.b/x/y')\n\ndef _test_get_url_straight_filename(suf):\n    eq_(get_url_straight_filename('http://a.b/' + suf), '')\n    eq_(get_url_straight_filename('http://a.b/p1' + suf), 'p1')\n    eq_(get_url_straight_filename('http://a.b/p1/' + suf), '')\n    eq_(get_url_straight_filename('http://a.b/p1/' + suf, allowdir=True), 'p1')\n    eq_(get_url_straight_filename('http://a.b/p1/p2' + suf), 'p2')\n    eq_(get_url_straight_filename('http://a.b/p1/p2/' + suf), '')\n    eq_(get_url_straight_filename('http://a.b/p1/p2/' + suf, allowdir=True), 'p2')\n    eq_(get_url_straight_filename('http://a.b/p1/p2/' + suf, allowdir=True, strip=('p2', 'xxx')), 'p1')\n    eq_(get_url_straight_filename('http://a.b/p1/p2/' + suf, strip=('p2', 'xxx')), '')\n\ndef test_get_url_straight_filename():\n    yield _test_get_url_straight_filename, ''\n    yield _test_get_url_straight_filename, '#'\n    yield _test_get_url_straight_filename, '#tag'\n    yield _test_get_url_straight_filename, '#tag/obscure'\n    yield _test_get_url_straight_filename, '?param=1'\n    yield _test_get_url_straight_filename, '?param=1&another=/'\n\nfrom datalad.support.network import rfc2822_to_epoch\ndef test_rfc2822_to_epoch():\n    eq_(rfc2822_to_epoch(\"Thu, 16 Oct 2014 01:16:17 EDT\"), 1413436577)\n\n\ndef test_get_response_disposition_filename():\n    eq_(get_response_disposition_filename('attachment;filename=\"Part1-Subjects1-99.tar\"'), \"Part1-Subjects1-99.tar\")\n    eq_(get_response_disposition_filename('attachment'), None)\n\n\ndef test_parse_url_opts():\n    url = 'http://map.org/api/download/?id=157'\n    output = parse_url_opts(url)\n    eq_(output, ('http://map.org/api/download/', {'id': '157'}))\n\n    url = 's3://bucket/save/?key=891'\n    output = parse_url_opts(url)\n    eq_(output, ('s3://bucket/save/', {'key': '891'}))\n\n    url = 'http://map.org/api/download/?id=98&code=13'\n    output = parse_url_opts(url)\n    eq_(output, ('http://map.org/api/download/', {'id': '98', 'code': '13'}))\n\n\ndef test_split_colon():\n    eq_(_split_colon('a:b'), ['a', 'b'])\n    eq_(_split_colon('a:b:c'), ['a', 'b:c'])\n    eq_(_split_colon('a:b:c', 2), ['a', 'b', 'c'])\n    eq_(_split_colon('ab'), ['ab'])\n    eq_(_split_colon(r'a\\:b'), [r'a\\:b'])\n\n\ndef test_url_eq():\n    eq_(URL(), URL())\n    # doesn't make sense to ask what kind of a url it is an empty URL\n    #eq_(RI(), RI())\n    neq_(URL(), URL(hostname='x'))\n    # Different types aren't equal even if have the same fields values\n    neq_(URL(path='x'), PathRI(path='x'))\n    neq_(URL(hostname='x'), SSHRI(hostname='x'))\n    neq_(str(URL(hostname='x')), str(SSHRI(hostname='x')))\n\n\ndef _check_ri(ri, cls, exact_str=True, **fields):\n    \"\"\"just a helper to carry out few checks on urls\"\"\"\n    with swallow_logs(new_level=logging.WARNING) as cml:\n        ri_ = cls(**fields)\n        murl = RI(ri)\n        eq_(murl.__class__, cls)  # not just a subclass\n        eq_(murl, ri_)\n        eq_(str(RI(ri)), ri)\n        eq_(eval(repr(ri_)), ri)  # repr leads back to identical ri_\n        eq_(ri, ri_)  # just in case ;)  above should fail first if smth is wrong\n        if not exact_str:\n            assert_in('Parsed version of', cml.out)\n    (eq_ if exact_str else neq_)(ri, str(ri_))  # that we can reconstruct it EXACTLY on our examples\n    # and that we have access to all those fields\n    nok_(set(fields).difference(set(cls._FIELDS)))\n    for f, v in fields.items():\n        eq_(getattr(ri_, f), v)\n\n\ndef test_url_base():\n    # Basic checks\n    assert_raises(ValueError, URL, \"http://example.com\", hostname='example.com')\n    url = URL(\"http://example.com\")\n    eq_(url.hostname, 'example.com')\n    eq_(url.scheme, 'http')\n    eq_(url.port, '')  # not specified -- empty strings\n    eq_(url.username, '')  # not specified -- empty strings\n    eq_(repr(url), \"URL(hostname='example.com', scheme='http')\")\n    eq_(url, \"http://example.com\")  # automagic coercion in __eq__\n\n    neq_(URL(), URL(hostname='x'))\n\n    smth = URL('smth')\n    eq_(smth.hostname, '')\n    ok_(bool(smth))\n    nok_(bool(URL()))\n\n    assert_raises(ValueError, url._set_from_fields, unknown='1')\n\n    with swallow_logs(new_level=logging.WARNING) as cml:\n        # we don't \"care\" about params ATM so there is a warning if there are any\n        purl = URL(\"http://example.com/;param\")\n        eq_(str(purl), 'http://example.com/;param')  # but we do maintain original string\n        assert_in('ParseResults contains params', cml.out)\n        eq_(purl.as_str(), 'http://example.com/')\n\n\ndef test_url_samples():\n    _check_ri(\"http://example.com\", URL, scheme='http', hostname=\"example.com\")\n    # \"complete\" one for classical http\n    _check_ri(\"http://user:pw@example.com:8080/p/sp?p1=v1&p2=v2#frag\", URL,\n              scheme='http', hostname=\"example.com\", port=8080,\n              username='user', password='pw', path='/p/sp',\n              query='p1=v1&p2=v2', fragment='frag')\n\n    # sample one for ssh with specifying the scheme\n    # XXX? might be useful?  https://github.com/FriendCode/giturlparse.py\n    _check_ri(\"ssh://host/path/sp1\", URL, scheme='ssh', hostname='host', path='/path/sp1')\n    _check_ri(\"user@host:path/sp1\", SSHRI,\n              hostname='host', path='path/sp1', username='user')\n    _check_ri(\"host:path/sp1\", SSHRI, hostname='host', path='path/sp1')\n    _check_ri(\"host:path\", SSHRI, hostname='host', path='path')\n    _check_ri(\"host:/path\", SSHRI, hostname='host', path='/path')\n    _check_ri(\"user@host\", SSHRI, hostname='host', username='user')\n    # TODO!!!  should this be a legit URL like this?\n    # _check_ri(\"host\", SSHRI, hostname='host'))\n    eq_(repr(RI(\"host:path\")), \"SSHRI(hostname='host', path='path')\")\n\n    # And now perspective 'datalad', implicit=True urls pointing to the canonical center location\n    _check_ri(\"///\", DataLadRI)\n    _check_ri(\"///p/s1\", DataLadRI, path='p/s1')\n    # could be considered by someone as \"URI reference\" relative to scheme\n    _check_ri(\"//a/\", DataLadRI, remote='a')\n    _check_ri(\"//a/data\", DataLadRI, path='data', remote='a')\n\n    # here we will do custom magic allowing only schemes with + in them, such as dl+archive\n    # or not so custom as\n    _check_ri(\"hg+https://host/user/proj\", URL,\n              scheme=\"hg+https\", hostname='host', path='/user/proj')\n    # \"old\" style\n    _check_ri(\"dl+archive:KEY/path/sp1#size=123\", URL,\n              scheme='dl+archive', path='KEY/path/sp1', fragment='size=123')\n    # \"new\" style\n    _check_ri(\"dl+archive:KEY#path=path/sp1&size=123\", URL,\n              scheme='dl+archive', path='KEY', fragment='path=path/sp1&size=123')\n    # actually above one is probably wrong since we need to encode the path\n    _check_ri(\"dl+archive:KEY#path=path%2Fbsp1&size=123\", URL,\n              scheme='dl+archive', path='KEY', fragment='path=path%2Fbsp1&size=123')\n\n    #https://en.wikipedia.org/wiki/File_URI_scheme\n    _check_ri(\"file://host\", URL, scheme='file', hostname='host')\n    _check_ri(\"file://host/path/sp1\", URL, scheme='file', hostname='host', path='/path/sp1')\n    _check_ri(\"file:///path/sp1\", URL, scheme='file', path='/path/sp1')\n    _check_ri(\"file:///~/path/sp1\", URL, scheme='file', path='/~/path/sp1', exact_str=False)\n    _check_ri(\"file:///%7E/path/sp1\", URL, scheme='file', path='/~/path/sp1')\n    # not sure but let's check\n    _check_ri(\"file:///c:/path/sp1\", URL, scheme='file', path='/c:/path/sp1', exact_str=False)\n\n    # and now implicit paths or actually they are also \"URI references\"\n    _check_ri(\"f\", PathRI, path='f')\n    _check_ri(\"f/s1\", PathRI, path='f/s1')\n    _check_ri(\"/f\", PathRI, path='/f')\n    _check_ri(\"/f/s1\", PathRI, path='/f/s1')\n\n    # some github ones, just to make sure\n    _check_ri(\"git://host/user/proj\", URL, scheme=\"git\", hostname=\"host\", path=\"/user/proj\")\n    _check_ri(\"git@host:user/proj\", SSHRI, hostname=\"host\", path=\"user/proj\", username='git')\n\n    _check_ri('weired:/', SSHRI, hostname='weired', path='/')\n    # since schema is not allowing some symbols so we need to add additional check\n    _check_ri('weired_url:/', SSHRI, hostname='weired_url', path='/')\n    _check_ri('example.com:/', SSHRI, hostname='example.com', path='/')\n    _check_ri('example.com:path/sp1', SSHRI, hostname='example.com', path='path/sp1')\n    _check_ri('example.com/path/sp1\\:fname', PathRI, path='example.com/path/sp1\\:fname')\n    # ssh is as stupid as us, so we will stay \"Consistently\" dumb\n    \"\"\"\n    $> ssh example.com/path/sp1:fname\n    ssh: Could not resolve hostname example.com/path/sp1:fname: Name or service not known\n    \"\"\"\n    _check_ri('example.com/path/sp1:fname', SSHRI, hostname='example.com/path/sp1', path='fname')\n\n    # SSHRIs have .port, but it is empty\n    eq_(SSHRI(hostname='example.com').port, '')\n\n    # check that we are getting a warning logged when url can't be reconstructed\n    # precisely\n    # actually failed to come up with one -- becomes late here\n    #_check_ri(\"http://host///..//p\", scheme='http', path='/..//p')\n\n    # actually this one is good enough to trigger a warning and I still don't know\n    # what it should exactly be!?\n    with swallow_logs(new_level=logging.WARNING) as cml:\n        weired_str = 'weired://'\n        weired_url = RI(weired_str)\n        repr(weired_url)\n        assert_re_in('Parsed version of SSHRI .weired:/. differs from original .weired://.',\n                     cml.out)\n        # but we store original str\n        eq_(str(weired_url), weired_str)\n        neq_(weired_url.as_str(), weired_str)\n\n\ndef _test_url_quote_path(cls, clskwargs, target_url):\n    path = '/ \"\\';a&b&cd `| '\n    if not (cls is PathRI):\n        clskwargs['hostname'] = hostname = 'example.com'\n    url = cls(path=path, **clskwargs)\n    eq_(url.path, path)\n    if 'hostname' in clskwargs:\n        eq_(url.hostname, hostname)\n    # all nasty symbols should be quoted\n    url_str = str(url)\n    eq_(url_str, target_url)\n    # no side-effects:\n    eq_(url.path, path)\n    if 'hostname' in clskwargs:\n        eq_(url.hostname, hostname)\n\n    # and figured out and unquoted\n    url_ = RI(url_str)\n    ok_(isinstance(url_, cls))\n    eq_(url_.path, path)\n    if 'hostname' in clskwargs:\n        eq_(url.hostname, hostname)\n\n\ndef test_url_quote_path():\n    yield _test_url_quote_path, SSHRI, {}, r'example.com:/\\ \\\"' + r\"\\'\\;a\\&b\\&cd\\ \\`\\|\\ \"\n    yield _test_url_quote_path, URL, {'scheme': \"http\"}, 'http://example.com/%20%22%27%3Ba%26b%26cd%20%60%7C%20'\n    yield _test_url_quote_path, PathRI, {}, r'/ \"' + r\"';a&b&cd `| \"  # nothing is done to file:implicit\n\n\ndef test_url_compose_archive_one():\n    url = URL(scheme='dl+archive', path='KEY',\n              fragment=OrderedDict((('path', 'f/p/ s+'), ('size', 30))))\n    # funny - space is encoded as + but + is %2B\n    eq_(str(url), 'dl+archive:KEY#path=f/p/+s%2B&size=30')\n    eq_(url.fragment_dict, {'path': 'f/p/ s+', 'size': '30'})\n\n\ndef test_url_fragments_and_query():\n    url = URL(hostname=\"host\", query=OrderedDict((('a', 'x/b'), ('b', 'y'))))\n    eq_(str(url), '//host?a=x%2Fb&b=y')\n    eq_(url.query, 'a=x%2Fb&b=y')\n    eq_(url.query_dict, {'a': 'x/b', 'b': 'y'})\n\n    url = URL(hostname=\"host\", fragment=OrderedDict((('b', 'x/b'), ('a', 'y'))))\n    eq_(str(url), '//host#b=x/b&a=y')\n    eq_(url.fragment, 'b=x/b&a=y')\n    eq_(url.fragment_dict, {'a': 'y', 'b': 'x/b'})\n\n    fname = get_most_obscure_supported_name()\n    url = URL(hostname=\"host\", fragment={'a': fname})\n    eq_(url.fragment_dict, {'a': fname})\n\n\ndef test_url_dicts():\n    eq_(URL(\"http://host\").query_dict, {})\n\n\n@skip_if_on_windows\ndef test_get_url_path_on_fileurls():\n    eq_(URL('file:///a').path, '/a')\n    eq_(URL('file:///a/b').path, '/a/b')\n    eq_(URL('file:///a/b#id').path, '/a/b')\n    eq_(URL('file:///a/b?whatever').path, '/a/b')\n\n\ndef test_is_url():\n    ok_(is_url('file://localhost/some'))\n    ok_(is_url('http://localhost'))\n    ok_(is_url('ssh://me@localhost'))\n    # in current understanding it is indeed a url but an 'ssh', implicit=True, not just\n    # a useless scheme=weired with a hope to point to a netloc\n    with swallow_logs():\n        ok_(is_url('weired://'))\n    nok_(is_url('relative'))\n    nok_(is_url('/absolute'))\n    ok_(is_url('like@sshlogin'))  # actually we do allow ssh:implicit urls ATM\n    nok_(is_url(''))\n    nok_(is_url(' '))\n\n    # we can pass RI instance directly\n    ok_(is_url(RI('file://localhost/some')))\n    nok_(is_url(RI('relative')))\n\n\ndef test_get_local_file_url_linux():\n    eq_(get_local_file_url('/a'), 'file:///a')\n    eq_(get_local_file_url('/a/b/c'), 'file:///a/b/c')\n    eq_(get_local_file_url('/a~'), 'file:///a%7E')\n    eq_(get_local_file_url('/a b/'), 'file:///a%20b/')\n\n\ndef test_get_local_path_from_url():\n    assert_raises(ValueError, get_local_path_from_url, 'http://some')\n    assert_raises(ValueError, get_local_path_from_url, 'file://elsewhere/some')\n    # invalid URL -- is it?  just that 'hostname' is some and no path\n    assert_raises(ValueError, get_local_path_from_url, 'file://some')\n    eq_(get_local_path_from_url('file:///some'), '/some')\n    eq_(get_local_path_from_url('file://localhost/some'), '/some')\n    eq_(get_local_path_from_url('file://::1/some'), '/some')\n    eq_(get_local_path_from_url('file://127.3.4.155/some'), '/some')\n\n\ndef test_is_ssh():\n\n    ssh_locators = [\"ssh://host\",\n                    \"ssh://host/some/where\",\n                    \"user@host:path/sp1\",\n                    \"user@host:/absloute/path/sp1\",\n                    \"host:path/sp1\",\n                    \"host:/absloute/path/sp1\",\n                    \"user@host\"]\n    for ri in ssh_locators:\n        ok_(is_ssh(ri), \"not considered ssh (string): %s\" % ri)\n        ok_(is_ssh(RI(ri)), \"not considered ssh (RI): %s\" % ri)\n\n    non_ssh_locators = [\"file://path/to\",\n                        \"/abs/path\",\n                        \"../rel/path\",\n                        \"http://example.com\",\n                        \"git://host/user/proj\",\n                        \"s3://bucket/save/?key=891\"]\n    for ri in non_ssh_locators:\n        ok_(not is_ssh(ri), \"considered ssh (string): %s\" % ri)\n        ok_(not is_ssh(RI(ri)), \"considered ssh (RI): %s\" % ri)\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...\n❌ Verification failed\nPython 3.9 installation failed, trying Python 3.7...\nVerifying installation...\nDatalad version: 0.2.2.dev29\n✅ Installation successful!\nSuccessfully installed Datalad using Python 3.7\n",
    "setup_res_stderr": "Using CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 25 packages in 77ms\nInstalled 25 packages in 6.02s\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\nerror: The build backend returned an error\n  Caused by: Call to `setuptools.build_meta:__legacy__.build_editable` failed (exit status: 1)\n\n[stderr]\nTraceback (most recent call last):\n  File \"<string>\", line 14, in <module>\n  File \"/home/gcpuser/.cache/uv/builds-v0/.tmpJz4f8f/lib/python3.9/site-packages/setuptools/build_meta.py\", line 483, in get_requires_for_build_editable\n    return self.get_requires_for_build_wheel(config_settings)\n  File \"/home/gcpuser/.cache/uv/builds-v0/.tmpJz4f8f/lib/python3.9/site-packages/setuptools/build_meta.py\", line 334, in get_requires_for_build_wheel\n    return self._get_build_requires(config_settings, requirements=[])\n  File \"/home/gcpuser/.cache/uv/builds-v0/.tmpJz4f8f/lib/python3.9/site-packages/setuptools/build_meta.py\", line 304, in _get_build_requires\n    self.run_setup()\n  File \"/home/gcpuser/.cache/uv/builds-v0/.tmpJz4f8f/lib/python3.9/site-packages/setuptools/build_meta.py\", line 522, in run_setup\n    super().run_setup(setup_script=setup_script)\n  File \"/home/gcpuser/.cache/uv/builds-v0/.tmpJz4f8f/lib/python3.9/site-packages/setuptools/build_meta.py\", line 320, in run_setup\n    exec(code, locals())\n  File \"<string>\", line 39, in <module>\nAttributeError: module 'platform' has no attribute 'dist'\n\nhint: This usually indicates a problem with the package or the build environment.\nerror: The build backend returned an error\n  Caused by: Call to `setuptools.build_meta:__legacy__.build_editable` failed (exit status: 1)\n\n[stderr]\nTraceback (most recent call last):\n  File \"<string>\", line 14, in <module>\n  File \"/home/gcpuser/.cache/uv/builds-v0/.tmpsxfgj9/lib/python3.9/site-packages/setuptools/build_meta.py\", line 483, in get_requires_for_build_editable\n    return self.get_requires_for_build_wheel(config_settings)\n  File \"/home/gcpuser/.cache/uv/builds-v0/.tmpsxfgj9/lib/python3.9/site-packages/setuptools/build_meta.py\", line 334, in get_requires_for_build_wheel\n    return self._get_build_requires(config_settings, requirements=[])\n  File \"/home/gcpuser/.cache/uv/builds-v0/.tmpsxfgj9/lib/python3.9/site-packages/setuptools/build_meta.py\", line 304, in _get_build_requires\n    self.run_setup()\n  File \"/home/gcpuser/.cache/uv/builds-v0/.tmpsxfgj9/lib/python3.9/site-packages/setuptools/build_meta.py\", line 522, in run_setup\n    super().run_setup(setup_script=setup_script)\n  File \"/home/gcpuser/.cache/uv/builds-v0/.tmpsxfgj9/lib/python3.9/site-packages/setuptools/build_meta.py\", line 320, in run_setup\n    exec(code, locals())\n  File \"<string>\", line 39, in <module>\nAttributeError: module 'platform' has no attribute 'dist'\n\nhint: This usually indicates a problem with the package or the build environment.\nTraceback (most recent call last):\n  File \"<string>\", line 1, in <module>\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_3deb4d632f5f9eb628d20a42319a4d51bc253c03/datalad/__init__.py\", line 20, in <module>\n    from .config import ConfigManager\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_3deb4d632f5f9eb628d20a42319a4d51bc253c03/datalad/config.py\", line 17, in <module>\n    from appdirs import AppDirs\nModuleNotFoundError: No module named 'appdirs'\nUsing CPython 3.7.9\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 26 packages in 211ms\nInstalled 26 packages in 7.04s\n + bids==0.0\n + coverage==7.2.7\n + docopt==0.6.2\n + exceptiongroup==1.2.2\n + fasteners==0.19\n + grabbit==0.2.6\n + importlib-metadata==6.7.0\n + iniconfig==2.0.0\n + nibabel==4.0.2\n + num2words==0.5.14\n + numpy==1.21.6\n + packaging==24.0\n + pandas==1.3.5\n + patsy==1.0.1\n + pluggy==1.2.0\n + pybids==0.6.5\n + pytest==7.4.4\n + pytest-cov==4.1.0\n + python-dateutil==2.9.0.post0\n + pytz==2024.2\n + scipy==1.7.3\n + setuptools==68.0.0\n + six==1.17.0\n + tomli==2.0.1\n + typing-extensions==4.7.1\n + zipp==3.15.0\nResolved 67 packages in 2.85s\nPrepared 1 package in 1.20s\nInstalled 61 packages in 100ms\n + appdirs==1.4.4\n + attrs==24.2.0\n + automat==22.10.0\n + beautifulsoup4==4.12.3\n + boto==2.49.0\n + certifi==2024.12.14\n + cffi==1.15.1\n + charset-normalizer==3.4.1\n + constantly==15.1.0\n + cryptography==44.0.0\n + cssselect==1.2.0\n + datalad==0.2.2.dev1 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_3deb4d632f5f9eb628d20a42319a4d51bc253c03)\n + filelock==3.12.2\n + gitdb==4.0.11\n + gitpython==3.1.43\n + httpretty==1.1.4\n + humanize==4.6.0\n + hyperlink==21.0.0\n + idna==3.10\n + importlib-resources==5.12.0\n + incremental==22.10.0\n + itemadapter==0.8.0\n + itemloaders==1.1.0\n + jaraco-classes==3.2.3\n + jeepney==0.8.0\n + jmespath==1.0.1\n + keyring==24.1.1\n + keyrings-alt==4.2.0\n + lxml==5.3.0\n + mock==5.1.0\n + more-itertools==9.1.0\n + msgpack-python==0.5.6\n + multidict==6.0.5\n + nose==1.3.7\n + parsel==1.8.1\n + patool==1.12\n + protego==0.3.0\n + pyasn1==0.5.1\n + pyasn1-modules==0.3.0\n + pycparser==2.21\n + pydispatcher==2.0.7\n + pyopenssl==24.3.0\n + pyyaml==6.0.1\n + queuelib==1.6.2\n + requests==2.31.0\n + requests-file==2.1.0\n + scrapy==2.9.0\n + secretstorage==3.3.3\n + service-identity==21.1.0\n + smmap==5.0.1\n + soupsieve==2.4.1\n + testtools==2.7.1\n + tldextract==4.0.0\n + tqdm==4.67.1\n + twisted==23.8.0\n + urllib3==2.0.7\n + vcrpy==4.3.0\n + w3lib==2.1.2\n + wrapt==1.16.0\n + yarl==1.9.4\n + zope-interface==6.4.post2\nAudited 1 package in 3ms\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_3deb4d632f5f9eb628d20a42319a4d51bc253c03/.venv/lib/python3.7/site-packages/urllib3/__init__.py:38: NotOpenSSLWarning: urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 3.1.4'. See: https://github.com/urllib3/urllib3/issues/3020\n  exceptions.NotOpenSSLWarning,\n",
    "new_commit_res_code": 1,
    "new_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.7.9, pytest-7.4.4, pluggy-1.2.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_3deb4d632f5f9eb628d20a42319a4d51bc253c03\nplugins: cov-4.1.0\ncollected 20 items\n\nr2e_tests/test_1.py ...x......Fx.....F..                                 [100%]\n\n=================================== FAILURES ===================================\n_______________________________ test_url_samples _______________________________\n\n    def test_url_samples():\n        _check_ri(\"http://example.com\", URL, scheme='http', hostname=\"example.com\")\n        # \"complete\" one for classical http\n        _check_ri(\"http://user:pw@example.com:8080/p/sp?p1=v1&p2=v2#frag\", URL,\n                  scheme='http', hostname=\"example.com\", port=8080,\n                  username='user', password='pw', path='/p/sp',\n                  query='p1=v1&p2=v2', fragment='frag')\n    \n        # sample one for ssh with specifying the scheme\n        # XXX? might be useful?  https://github.com/FriendCode/giturlparse.py\n        _check_ri(\"ssh://host/path/sp1\", URL, scheme='ssh', hostname='host', path='/path/sp1')\n        _check_ri(\"user@host:path/sp1\", SSHRI,\n                  hostname='host', path='path/sp1', username='user')\n        _check_ri(\"host:path/sp1\", SSHRI, hostname='host', path='path/sp1')\n        _check_ri(\"host:path\", SSHRI, hostname='host', path='path')\n        _check_ri(\"host:/path\", SSHRI, hostname='host', path='/path')\n        _check_ri(\"user@host\", SSHRI, hostname='host', username='user')\n        # TODO!!!  should this be a legit URL like this?\n        # _check_ri(\"host\", SSHRI, hostname='host'))\n        eq_(repr(RI(\"host:path\")), \"SSHRI(hostname='host', path='path')\")\n    \n        # And now perspective 'datalad', implicit=True urls pointing to the canonical center location\n        _check_ri(\"///\", DataLadRI)\n        _check_ri(\"///p/s1\", DataLadRI, path='p/s1')\n        # could be considered by someone as \"URI reference\" relative to scheme\n        _check_ri(\"//a/\", DataLadRI, remote='a')\n        _check_ri(\"//a/data\", DataLadRI, path='data', remote='a')\n    \n        # here we will do custom magic allowing only schemes with + in them, such as dl+archive\n        # or not so custom as\n        _check_ri(\"hg+https://host/user/proj\", URL,\n                  scheme=\"hg+https\", hostname='host', path='/user/proj')\n        # \"old\" style\n        _check_ri(\"dl+archive:KEY/path/sp1#size=123\", URL,\n                  scheme='dl+archive', path='KEY/path/sp1', fragment='size=123')\n        # \"new\" style\n        _check_ri(\"dl+archive:KEY#path=path/sp1&size=123\", URL,\n                  scheme='dl+archive', path='KEY', fragment='path=path/sp1&size=123')\n        # actually above one is probably wrong since we need to encode the path\n        _check_ri(\"dl+archive:KEY#path=path%2Fbsp1&size=123\", URL,\n                  scheme='dl+archive', path='KEY', fragment='path=path%2Fbsp1&size=123')\n    \n        #https://en.wikipedia.org/wiki/File_URI_scheme\n        _check_ri(\"file://host\", URL, scheme='file', hostname='host')\n        _check_ri(\"file://host/path/sp1\", URL, scheme='file', hostname='host', path='/path/sp1')\n        _check_ri(\"file:///path/sp1\", URL, scheme='file', path='/path/sp1')\n>       _check_ri(\"file:///~/path/sp1\", URL, scheme='file', path='/~/path/sp1', exact_str=False)\n\nr2e_tests/test_1.py:217: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nr2e_tests/test_1.py:135: in _check_ri\n    assert_in('Parsed version of', cml.out)\n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/unittest/case.py:1119: in assertIn\n    self.fail(self._formatMessage(msg, standardMsg))\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <nose.tools.trivial.Dummy testMethod=nop>\nmsg = \"'Parsed version of' not found in ''\"\n\n    def fail(self, msg=None):\n        \"\"\"Fail immediately, with the given message.\"\"\"\n>       raise self.failureException(msg)\nE       AssertionError: 'Parsed version of' not found in ''\n\n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/unittest/case.py:693: AssertionError\n________________________ test_get_local_file_url_linux _________________________\n\n    def test_get_local_file_url_linux():\n        eq_(get_local_file_url('/a'), 'file:///a')\n        eq_(get_local_file_url('/a/b/c'), 'file:///a/b/c')\n>       eq_(get_local_file_url('/a~'), 'file:///a%7E')\n\nr2e_tests/test_1.py:354: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\na = 'file:///a~', b = 'file:///a%7E', msg = None\n\n    def eq_(a, b, msg=None):\n        \"\"\"Shorthand for 'assert a == b, \"%r != %r\" % (a, b)\n        \"\"\"\n        if not a == b:\n>           raise AssertionError(msg or \"%r != %r\" % (a, b))\nE           AssertionError: 'file:///a~' != 'file:///a%7E'\n\n.venv/lib/python3.7/site-packages/nose/tools/trivial.py:29: AssertionError\n==================================== PASSES ====================================\n________________________________ test_url_base _________________________________\n------------------------------ Captured log call -------------------------------\nWARNING  datalad.network:network.py:544 ParseResults contains params 'param', which will be ignored\nWARNING  datalad.network:network.py:382 Parsed version of URL 'http://example.com/' differs from original 'http://example.com/;param'\n_________________________________ test_is_url __________________________________\n------------------------------ Captured log call -------------------------------\nWARNING  datalad.network:network.py:382 Parsed version of SSHRI 'weired:/' differs from original 'weired://'\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::test_same_website\nPASSED r2e_tests/test_1.py::test_get_tld\nPASSED r2e_tests/test_1.py::test_dlurljoin\nPASSED r2e_tests/test_1.py::test_rfc2822_to_epoch\nPASSED r2e_tests/test_1.py::test_get_response_disposition_filename\nPASSED r2e_tests/test_1.py::test_parse_url_opts\nPASSED r2e_tests/test_1.py::test_split_colon\nPASSED r2e_tests/test_1.py::test_url_eq\nPASSED r2e_tests/test_1.py::test_url_base\nPASSED r2e_tests/test_1.py::test_url_compose_archive_one\nPASSED r2e_tests/test_1.py::test_url_fragments_and_query\nPASSED r2e_tests/test_1.py::test_url_dicts\nPASSED r2e_tests/test_1.py::test_get_url_path_on_fileurls\nPASSED r2e_tests/test_1.py::test_is_url\nPASSED r2e_tests/test_1.py::test_get_local_path_from_url\nPASSED r2e_tests/test_1.py::test_is_ssh\nXFAIL r2e_tests/test_1.py::test_get_url_straight_filename - reason: [NOTRUN] yield tests were removed in pytest 4.0 - test_get_url_straight_filename will be ignored\nXFAIL r2e_tests/test_1.py::test_url_quote_path - reason: [NOTRUN] yield tests were removed in pytest 4.0 - test_url_quote_path will be ignored\nFAILED r2e_tests/test_1.py::test_url_samples - AssertionError: 'Parsed versio...\nFAILED r2e_tests/test_1.py::test_get_local_file_url_linux - AssertionError: '...\n=================== 2 failed, 16 passed, 2 xfailed in 2.04s ====================\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.7.9, pytest-7.4.4, pluggy-1.2.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_3deb4d632f5f9eb628d20a42319a4d51bc253c03\nplugins: cov-4.1.0\ncollected 20 items\n\nr2e_tests/test_1.py ...x......Fx....FF..                                 [100%]\n\n=================================== FAILURES ===================================\n_______________________________ test_url_samples _______________________________\n\n    def test_url_samples():\n        _check_ri(\"http://example.com\", URL, scheme='http', hostname=\"example.com\")\n        # \"complete\" one for classical http\n        _check_ri(\"http://user:pw@example.com:8080/p/sp?p1=v1&p2=v2#frag\", URL,\n                  scheme='http', hostname=\"example.com\", port=8080,\n                  username='user', password='pw', path='/p/sp',\n                  query='p1=v1&p2=v2', fragment='frag')\n    \n        # sample one for ssh with specifying the scheme\n        # XXX? might be useful?  https://github.com/FriendCode/giturlparse.py\n        _check_ri(\"ssh://host/path/sp1\", URL, scheme='ssh', hostname='host', path='/path/sp1')\n        _check_ri(\"user@host:path/sp1\", SSHRI,\n                  hostname='host', path='path/sp1', username='user')\n        _check_ri(\"host:path/sp1\", SSHRI, hostname='host', path='path/sp1')\n        _check_ri(\"host:path\", SSHRI, hostname='host', path='path')\n        _check_ri(\"host:/path\", SSHRI, hostname='host', path='/path')\n        _check_ri(\"user@host\", SSHRI, hostname='host', username='user')\n        # TODO!!!  should this be a legit URL like this?\n        # _check_ri(\"host\", SSHRI, hostname='host'))\n        eq_(repr(RI(\"host:path\")), \"SSHRI(hostname='host', path='path')\")\n    \n        # And now perspective 'datalad', implicit=True urls pointing to the canonical center location\n        _check_ri(\"///\", DataLadRI)\n        _check_ri(\"///p/s1\", DataLadRI, path='p/s1')\n        # could be considered by someone as \"URI reference\" relative to scheme\n        _check_ri(\"//a/\", DataLadRI, remote='a')\n        _check_ri(\"//a/data\", DataLadRI, path='data', remote='a')\n    \n        # here we will do custom magic allowing only schemes with + in them, such as dl+archive\n        # or not so custom as\n        _check_ri(\"hg+https://host/user/proj\", URL,\n                  scheme=\"hg+https\", hostname='host', path='/user/proj')\n        # \"old\" style\n        _check_ri(\"dl+archive:KEY/path/sp1#size=123\", URL,\n                  scheme='dl+archive', path='KEY/path/sp1', fragment='size=123')\n        # \"new\" style\n        _check_ri(\"dl+archive:KEY#path=path/sp1&size=123\", URL,\n                  scheme='dl+archive', path='KEY', fragment='path=path/sp1&size=123')\n        # actually above one is probably wrong since we need to encode the path\n        _check_ri(\"dl+archive:KEY#path=path%2Fbsp1&size=123\", URL,\n                  scheme='dl+archive', path='KEY', fragment='path=path%2Fbsp1&size=123')\n    \n        #https://en.wikipedia.org/wiki/File_URI_scheme\n        _check_ri(\"file://host\", URL, scheme='file', hostname='host')\n        _check_ri(\"file://host/path/sp1\", URL, scheme='file', hostname='host', path='/path/sp1')\n        _check_ri(\"file:///path/sp1\", URL, scheme='file', path='/path/sp1')\n>       _check_ri(\"file:///~/path/sp1\", URL, scheme='file', path='/~/path/sp1', exact_str=False)\n\nr2e_tests/test_1.py:217: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nr2e_tests/test_1.py:135: in _check_ri\n    assert_in('Parsed version of', cml.out)\n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/unittest/case.py:1119: in assertIn\n    self.fail(self._formatMessage(msg, standardMsg))\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <nose.tools.trivial.Dummy testMethod=nop>\nmsg = \"'Parsed version of' not found in ''\"\n\n    def fail(self, msg=None):\n        \"\"\"Fail immediately, with the given message.\"\"\"\n>       raise self.failureException(msg)\nE       AssertionError: 'Parsed version of' not found in ''\n\n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/unittest/case.py:693: AssertionError\n_________________________________ test_is_url __________________________________\n\n    def test_is_url():\n        ok_(is_url('file://localhost/some'))\n        ok_(is_url('http://localhost'))\n        ok_(is_url('ssh://me@localhost'))\n        # in current understanding it is indeed a url but an 'ssh', implicit=True, not just\n        # a useless scheme=weired with a hope to point to a netloc\n        with swallow_logs():\n            ok_(is_url('weired://'))\n        nok_(is_url('relative'))\n        nok_(is_url('/absolute'))\n        ok_(is_url('like@sshlogin'))  # actually we do allow ssh:implicit urls ATM\n        nok_(is_url(''))\n        nok_(is_url(' '))\n    \n        # we can pass RI instance directly\n>       ok_(is_url(RI('file://localhost/some')))\n\nr2e_tests/test_1.py:347: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nexpr = False, msg = None\n\n    def ok_(expr, msg=None):\n        \"\"\"Shorthand for assert. Saves 3 whole characters!\n        \"\"\"\n        if not expr:\n>           raise AssertionError(msg)\nE           AssertionError: None\n\n.venv/lib/python3.7/site-packages/nose/tools/trivial.py:22: AssertionError\n------------------------------ Captured log call -------------------------------\nWARNING  datalad.network:network.py:382 Parsed version of SSHRI 'weired:/' differs from original 'weired://'\n________________________ test_get_local_file_url_linux _________________________\n\n    def test_get_local_file_url_linux():\n        eq_(get_local_file_url('/a'), 'file:///a')\n        eq_(get_local_file_url('/a/b/c'), 'file:///a/b/c')\n>       eq_(get_local_file_url('/a~'), 'file:///a%7E')\n\nr2e_tests/test_1.py:354: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\na = 'file:///a~', b = 'file:///a%7E', msg = None\n\n    def eq_(a, b, msg=None):\n        \"\"\"Shorthand for 'assert a == b, \"%r != %r\" % (a, b)\n        \"\"\"\n        if not a == b:\n>           raise AssertionError(msg or \"%r != %r\" % (a, b))\nE           AssertionError: 'file:///a~' != 'file:///a%7E'\n\n.venv/lib/python3.7/site-packages/nose/tools/trivial.py:29: AssertionError\n==================================== PASSES ====================================\n________________________________ test_url_base _________________________________\n------------------------------ Captured log call -------------------------------\nWARNING  datalad.network:network.py:544 ParseResults contains params 'param', which will be ignored\nWARNING  datalad.network:network.py:382 Parsed version of URL 'http://example.com/' differs from original 'http://example.com/;param'\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::test_same_website\nPASSED r2e_tests/test_1.py::test_get_tld\nPASSED r2e_tests/test_1.py::test_dlurljoin\nPASSED r2e_tests/test_1.py::test_rfc2822_to_epoch\nPASSED r2e_tests/test_1.py::test_get_response_disposition_filename\nPASSED r2e_tests/test_1.py::test_parse_url_opts\nPASSED r2e_tests/test_1.py::test_split_colon\nPASSED r2e_tests/test_1.py::test_url_eq\nPASSED r2e_tests/test_1.py::test_url_base\nPASSED r2e_tests/test_1.py::test_url_compose_archive_one\nPASSED r2e_tests/test_1.py::test_url_fragments_and_query\nPASSED r2e_tests/test_1.py::test_url_dicts\nPASSED r2e_tests/test_1.py::test_get_url_path_on_fileurls\nPASSED r2e_tests/test_1.py::test_get_local_path_from_url\nPASSED r2e_tests/test_1.py::test_is_ssh\nXFAIL r2e_tests/test_1.py::test_get_url_straight_filename - reason: [NOTRUN] yield tests were removed in pytest 4.0 - test_get_url_straight_filename will be ignored\nXFAIL r2e_tests/test_1.py::test_url_quote_path - reason: [NOTRUN] yield tests were removed in pytest 4.0 - test_url_quote_path will be ignored\nFAILED r2e_tests/test_1.py::test_url_samples - AssertionError: 'Parsed versio...\nFAILED r2e_tests/test_1.py::test_is_url - AssertionError: None\nFAILED r2e_tests/test_1.py::test_get_local_file_url_linux - AssertionError: '...\n=================== 3 failed, 15 passed, 2 xfailed in 0.95s ====================\n",
    "old_commit_res_stderr": ""
}
datalad/distribution/dataset.py datalad/support/network.py datalad/tests/test_network.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `is_url` Fails to Recognize RI Instances as URLs

**Description:**
The `is_url` function currently does not handle `RI` (Resource Identifier) instances correctly. When an `RI` instance is passed to `is_url`, the function fails to identify it as a valid URL, leading to incorrect behavior.

**Example Buggy Code:**
```python
from datalad.support.network import is_url, RI

# Attempting to check if an RI instance is a URL
result = is_url(RI('file://localhost/some'))
print(result)  # Unexpectedly returns False
```

**Expected Behavior:**
The `is_url` function should return `True` when a valid `RI` instance representing a URL is passed. It should correctly identify and handle both string URLs and `RI` instances.

**Actual Behavior:**
Passing an `RI` instance to `is_url` results in `False`, even when the `RI` instance represents a valid URL. This prevents proper URL recognition and handling within the application.

[/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/support/network.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.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##

import calendar
import email.utils
import gzip
import os
import re
import shutil
import time

from collections import OrderedDict
from os.path import abspath, isabs

from six import string_types
from six import iteritems
from six.moves.urllib.request import urlopen, Request
from six.moves.urllib.parse import quote as urlquote, unquote as urlunquote
from six.moves.urllib.parse import urljoin, urlparse, urlsplit, urlunsplit, urlunparse, ParseResult
from six.moves.urllib.parse import parse_qsl
from six.moves.urllib.parse import urlencode
from six.moves.urllib.error import URLError

from datalad.utils import on_windows

from datalad.utils import auto_repr
# TODO not sure what needs to use `six` here yet
import requests

import logging
lgr = logging.getLogger('datalad.network')


def get_response_disposition_filename(s):
    """Given a string s as from HTTP Content-Disposition field in the response
    return possibly present filename if any
    """
    if not s:
        return None
    # If the response has Content-Disposition, try to get filename from it
    cd = dict(map(
        lambda x: x.strip().split('=') if '=' in x else (x.strip(),''),
        s.split(';')))
    if 'filename' in cd:
        filename = cd['filename'].strip("\"'")
        return filename
    return None


def get_url_disposition_filename(url, headers=None):
    """Get filename as possibly provided by the server in Content-Disposition
    """
    if headers is None:
        request = Request(url)
        r = retry_urlopen(request)
        # things are different in requests
        if 'requests.' in str(r.__class__):
            headers = r.headers
        else:
            headers = r.info()
    else:
        r = None
    try:
        return get_response_disposition_filename(headers.get('Content-Disposition', ''))
    finally:
        if r:
            r.close()


def get_url_straight_filename(url, strip=[], allowdir=False):
    """Get file/dir name of the last path component of the URL

    Parameters
    ----------
    strip: list, optional
      If provided, listed names will not be considered and their
      parent directory will be selected
    allowdir: bool, optional
      If url points to a "directory" (ends with /), empty string
      would be returned unless allowdir is True, in which case the
      name of the directory would be returned
    """
    path = urlunquote(urlsplit(url).path)
    path_parts = path.split('/')

    if allowdir:
        # strip empty ones
        while len(path_parts) > 1 and not path_parts[-1]:
            path_parts = path_parts[:-1]

    if strip:
        while path_parts and path_parts[-1] in strip:
            path_parts = path_parts[:-1]

    if path_parts:
        return path_parts[-1]
    else:
        return None


def get_url_filename(url, headers=None, strip=[]):
    """Get filename from the url, first consulting server about Content-Disposition
    """
    filename = get_url_disposition_filename(url, headers)
    if filename:
        return filename
    return get_url_straight_filename(url, strip=[])


def get_url_response_stamp(url, response_info):
    size, mtime = None, None
    if 'Content-length' in response_info:
        size = int(response_info['Content-length'])
    if 'Last-modified' in response_info:
        mtime = calendar.timegm(email.utils.parsedate(
            response_info['Last-modified']))
    return dict(size=size, mtime=mtime, url=url)


def get_tld(url):
    """Return top level domain from a url

    Parameters
    ----------
    url : str
    """
    # maybe use this instead to be safe:  https://pypi.python.org/pypi/tld
    if not url.strip():
        raise ValueError("Empty URL has no TLD")
    rec = urlsplit(url)
    if not rec.netloc:
        if not rec.scheme:
            # There were no scheme provided thus netloc was empty -- must have been a simple 'path like'
            return url.split('/', 1)[0]
        else:
            raise ValueError("It seems that only the scheme was provided without the net location/TLD")
    return rec.netloc


from email.utils import parsedate_tz, mktime_tz
def rfc2822_to_epoch(datestr):
    """Given rfc2822 date/time format, return seconds since epoch"""
    return mktime_tz(parsedate_tz(datestr))


import calendar
from datetime import datetime
def iso8601_to_epoch(datestr):
    return calendar.timegm(datetime.strptime(datestr, "%Y-%m-%dT%H:%M:%S.%fZ").timetuple())


def __urlopen_requests(url, header_vals=None):
    # XXX Workaround for now for ... broken code
    if isinstance(url, Request):
        url = url.get_full_url()
    return requests.Session().get(url)


def retry_urlopen(url, retries=3):
    for t in range(retries):
        try:
            return __urlopen_requests(url)
        except URLError as e:
            lgr.warn("Received exception while reading %s: %s" % (url, e))
            if t == retries - 1:
                # if we have reached allowed number of retries -- reraise
                raise


def is_url_quoted(url):
    """Return either URL looks being already quoted
    """
    try:
        url_ = urlunquote(url)
        return url != url_
    except:  # problem with unquoting -- then it must be wasn't quoted (correctly)
        return False


def same_website(url_rec, u_rec):
    """Decide either a link leads to external site

    Parameters
    ----------
    url_rec: ParseResult
      record for original url
    u_rec: ParseResult
      record for new url
    """
    if isinstance(url_rec, string_types):
        url_rec = urlparse(url_rec)
    if isinstance(u_rec, string_types):
        u_rec = urlparse(u_rec)
    return (url_rec.netloc == u_rec.netloc)
    # todo: collect more of sample cases.
    # disabled below check while working on ratholeradio, since links
    # could go to the parent and that is ok.  Figure out when it was
    # desired not to go to the parent -- we might need explicit option
    # and u_rec.path.startswith(url_rec.path)):


def dlurljoin(u_path, url):
    url_rec = urlparse(url)  # probably duplicating parsing :-/ TODO
    if url_rec.scheme:
        # independent full url, so just return it
        return url
    if u_path.endswith('/'):  # should here be also a scheme use?
        if url.startswith('/'):  # jump to the root
            u_path_rec = urlparse(u_path)
            return urljoin(urlunparse(
                (u_path_rec.scheme, u_path_rec.netloc, '', '', '', '')), url)
        else:
            return os.path.join(u_path, url)
    # TODO: recall where all this dirname came from and bring into the test
    return urljoin(os.path.dirname(u_path) + '/', url)


# TODO should it be a node maybe?
class SimpleURLStamper(object):
    """Gets a simple stamp about the URL: {url, time, size} of whatever was provided in the header
    """
    def __init__(self, mode='full'):
        self.mode = mode

    def __call__(self, url):
        # Extracted from above madness
        # TODO: add mode alike to 'relaxed' where we would not
        # care about content-disposition filename
        # http://stackoverflow.com/questions/862173/how-to-download-a-file-using-python-in-a-smarter-way
        request = Request(url)

        # No traffic compression since we do not know how to identify
        # exactly either it has to be decompressed
        # request.add_header('Accept-encoding', 'gzip,deflate')
        #
        # TODO: think about stamping etc -- we seems to be redoing
        # what git-annex does for us already... not really
        r = retry_urlopen(request)
        try:
            r_info = r.info()
            r_stamp = get_url_response_stamp(url, r_info)

            return dict(mtime=r_stamp['mtime'], size=r_stamp['size'], url=url)
        finally:
            r.close()


# TODO:  make it consistent/clear at what stage % encoding/decoding happens!
# now it is a mix!

#
# Useful functionality in requests.models
#  utils.requote_uri -- quote/unquote cycle to guarantee consistent appearance
#  RequestEncodingMixin._encode_params -- Will successfully encode parameters when passed as a dict or a list of ...
#  PreparedRequest().prepare_url(url, params) -- nicely cares about url encodings etc
#

def _guess_ri_cls(ri):
    """Factory function which would determine which type of a ri a provided string is"""
    # We assume that it is a URL and parse it. Depending on the result
    # we might decide that it was something else ;)
    fields = URL._pr_to_fields(urlparse(ri))
    lgr.log(5, "Parsed ri %s into fields %s" % (ri, fields))

    type_ = 'url'
    # Special treatments
    # file:///path should stay file:
    if fields['scheme'] and fields['scheme'] not in {'file'} \
            and not fields['hostname']:
        # dl+archive:... or just for ssh   hostname:path/p1
        if '+' not in fields['scheme']:
            type_ = 'ssh'
            lgr.log(5, "Assuming ssh style ri, adjusted: %s" % (fields,))

    if not fields['scheme'] and not fields['hostname']:
        parts = _split_colon(ri)
        if fields['path'] and '@' in fields['path'] or len(parts) > 1:
            # user@host:path/sp1
            # or host_name: (hence parts check)
            # TODO: we need a regex to catch those really, parts check is not suff
            type_ = 'ssh'
        elif ri.startswith('//'):
            # e.g. // or ///path
            type_ = 'datalad'
        else:
            type_ = 'file'

    if not fields['scheme'] and fields['hostname']:
        # e.g. //a/path
        type_ = 'datalad'

    TYPES = {
        'url': URL,
        'ssh':  SSHRI,
        'file': PathRI,
        'datalad': DataLadRI
    }
    cls = TYPES[type_]
    # just parse the ri according to regex matchint ssh "ri" specs
    lgr.log(5, "Detected %s ri" % type_)
    return cls


class RI(object):
    """Resource Identifier - base class and a factory for URL, SSHRI, etc

    Intended to be a R/O object (i.e. no fields should be changed in-place).
    Subclasses define specific collections of fields they care about in _FIELDS
    class variable.
    The idea is that this class should help to break apart a URL, while being
    able to rebuild itself into a string representation for reuse

    `RI` could be used as factory, whenever type of the resource is unknown and
    must be guessed from the string representation.  One of the subclasses will be
    provided as output, e.g.

    >>> RI('http://example.com')
    URL(hostname='example.com', scheme='http')
    >>> RI('example.com:path')
    SSHRI(hostname='example.com', path='path')
    """

    # All of the subclasses will provide path
    _FIELDS = (
        'path',
    )

    __slots__ = _FIELDS + ('_fields', '_str')

    def __new__(cls, ri=None, **kwargs):
        """Used as a possible factory for known RI types

        Returns
        -------
        RI
           uninitialized RI object of appropriate class with _str
           set to string representation if was provided

        """
        if cls is RI and ri is not None:
            # RI class was used as a factory
            cls = _guess_ri_cls(ri)

        ri_obj = super(RI, cls).__new__(cls)
        # Store internally original str
        ri_obj._str = ri
        return ri_obj

    def __init__(self, ri=None, **fields):
        """
        Parameters
        ----------
        ri: str, optional
          String version of a resource specific for this class.  If you would like
          a type of the resource be deduced, use RI(ri)
        **fields: dict, optional
          The values for the fields defined in _FIELDS class variable.
        """
        if ri and (bool(ri) == bool(fields)):
            raise ValueError(
                "Specify either ri or breakdown from the fields, not both. "
                "Got ri=%r, fields=%r" % (ri, fields))

        self._fields = self._get_blank_fields()
        if ri is not None:
            fields = self._str_to_fields(ri)
        self._set_from_fields(**fields)

        # If was initialized from a string representation
        if self._str is not None:
            # well -- some ris might not unparse identically back
            # strictly speaking, but let's assume they do
            ri_ = self.as_str()
            if ri != ri_:
                lgr.warning("Parsed version of %s %r differs from original %r",
                            self.__class__.__name__, ri_, ri)

    @classmethod
    def _get_blank_fields(cls, **fields):
        return OrderedDict(((f, fields.get(f, '')) for f in cls._FIELDS))

    @property
    def fields(self):
        """Returns shallow copy of fields to ease manipulations"""
        return self._fields.copy()

    def __repr__(self):
        # since auto_repr doesn't support "non-0" values atm
        return "%s(%s)" % (
            self.__class__.__name__,
            ", ".join(["%s=%r" % (k, v)
                       for k, v in sorted(self._fields.items())
                       if v]))

    # Lazily evaluated if _str was not set
    def __str__(self):
        if self._str is None:
            self._str = self.as_str()
        return self._str

    @classmethod
    def from_str(cls, ri_str):
        obj = cls(**cls._str_to_fields(ri_str))
        obj._str = ri_str
        return obj

    # Apparently doesn't quite play nicely with multiple inheritence for MixIn'
    # of regexp based URLs
    #@abstractmethod
    #@classmethod
    #def _str_to_fields(cls, ri_str):
    #    raise NotImplementedError

    #
    # If any field is specified, URL is not considered 'False', i.e.
    # non-existing, although may be we could/shout omit having only
    # scheme or port specified since it doesn't point to any useful
    # location
    #

    def __nonzero__(self):
        fields = self._fields
        return any(fields.values())

    # for PY3
    __bool__ = __nonzero__

    #
    # Helpers to deal with internal structures and conversions
    #

    def _set_from_fields(self, **fields):
        unknown_fields = set(fields).difference(self._FIELDS)
        if unknown_fields:
            raise ValueError("Do not know about %s. Known fields for %s are: %s"
                             % (unknown_fields, self.__class__, self._FIELDS))

        # encode dicts for query or fragment into
        for f in {'query', 'fragment'}:
            v = fields.get(f)
            if isinstance(v, dict):

                ev = urlencode(v)
                # / is reserved char within query
                if f == 'fragment' and '%2F' not in str(v):
                    # but seems to be ok'ish within the fragment which is
                    # the last element of URI and anyways used only by the
                    # client (i.e. by us here if used to compose the URL)
                    # so let's return / back for clarity if there were no
                    # awkward %2F to startswith
                    ev = ev.replace('%2F', '/')
                fields[f] = ev

        self._fields.update(fields)

    #
    # Quick comparators
    #

    def __eq__(self, other):
        if not isinstance(other, RI):
            other = RI(other)
        return isinstance(other, self.__class__) and dict(other._fields) == dict(self._fields)

    def __ne__(self, other):
        return not (self == other)

    def __getattribute__(self, item):
        if item.startswith('_') or item not in self._FIELDS:
            return super(RI, self).__getattribute__(item)
        else:
            return self._fields[item]


class URL(RI):
    """Universal resource locator

    Although largely decorating urlparse.ParseResult, it
    - doesn't mandate providing all parts of the URL
    - doesn't require netloc but rather asks for separate username, password, and hostname
    """

    _FIELDS = RI._FIELDS + (
        'scheme',
        'username',
        'password',
        'hostname', 'port',
        'query',
        'fragment',
    )

    def as_str(self):
        """Render URL as a string"""
        return urlunparse(self.to_pr())

    @classmethod
    def _str_to_fields(cls, url_str):
        fields = URL._pr_to_fields(urlparse(url_str))
        fields['path'] = urlunquote(fields['path'])
        return fields

    def to_pr(self):
        """Convert URL to urlparse.ParseResults namedtuple"""
        return self._fields_to_pr(self._fields)

    @classmethod
    def _fields_to_pr(cls, fields):
        """Recompose back fields dict to ParseResult"""
        netloc = fields['username'] or ''
        if fields['password']:
            netloc += ':' + fields['password']
        if netloc:
            netloc += '@'
        netloc += fields['hostname']
        if fields['port']:
            netloc += ':%s' % fields['port']

        pr_fields = {
            f: fields[f]
            for f in cls._FIELDS
            if f not in ('hostname', 'password', 'username', 'port')
        }
        pr_fields['netloc'] = netloc
        pr_fields['params'] = ''
        # We need to quote the path
        pr_fields['path'] = urlquote(pr_fields['path'])
        # TODO: figure out what to do with query/fragment... one step at a time
        return ParseResult(**pr_fields)

    @classmethod
    def _pr_to_fields(cls, pr):
        """ParseResult is a tuple so immutable, which complicates adjusting it

        This function converts ParseResult into dict"""

        if pr.params:
            lgr.warning("ParseResults contains params %r, which will be ignored"
                        % (pr.params,))

        # can't use just pr._asdict since we care to ask those properties
        # such as .port , .hostname etc
        # Forcing '' instead of None since those properties (.hostname), .password,
        # .username return None if not available and we decided to uniformize
        return {f: (getattr(pr, f) or '') for f in cls._FIELDS}

    #
    # Access helpers
    #

    def _parse_qs(self, s, auto_delist=True):
        """Helper around parse_qs to strip unneeded 'list'ing etc and return a dict of key=values"""
        if not s:
            return {}
        out = OrderedDict(parse_qsl(s, 1))
        if not auto_delist:
            return out
        for k in out:
            v = out[k]
            if isinstance(v, list) and len(v) == 1:
                v = v[0]
                out[k] = None if v == '' else v
        return out

    @property
    def query_dict(self):
        return self._parse_qs(self.query)

    @property
    def fragment_dict(self):
        return self._parse_qs(self.fragment)


class PathRI(RI):
    """RI pointing to a (local) file/directory"""
    def as_str(self):
        return self.path

    @classmethod
    def _str_to_fields(cls, url_str):
        return dict(path=url_str)


class RegexBasedURLMixin(object):
    """Base class for URLs which we could simple parse using regular expressions"""

    _REGEX = None

    # not used ATM but possible ;)
    # @classmethod
    # def is_str_matches(cls, url_str):
    #     return bool(cls._REGEX.match(url_str))

    @classmethod
    def _str_to_fields(cls, url_str):
        re_match = cls._REGEX.match(url_str)
        if not re_match:
            # TODO: custom error?
            raise ValueError(
                "Possibly incorrectly determined string %r correspond to %s address"
                " -- it failed matching regex. Dunno how to handle. Contact developers"
                % (cls, url_str,)
            )
        fields = cls._get_blank_fields()
        fields.update({k: v for k, v in iteritems(re_match.groupdict()) if v})
        cls._normalize_fields(fields)
        return fields

    @classmethod
    def _normalize_fields(self, fields):
        """Helper to be ran if any of the fields need to be normalized after parsing"""
        pass


class SSHRI(RI, RegexBasedURLMixin):
    """RI pointing to a remote location reachable via SSH"""

    _FIELDS = RI._FIELDS + (
        'username',
        'hostname',
        'port',
    )

    _REGEX = re.compile(r'((?P<username>\S*)@)?(?P<hostname>[^:]+)(\:(?P<path>.*))?$')

    @classmethod
    def _normalize_fields(cls, fields):
        if fields['path'] and fields['path'].startswith('//'):
            # Let's normalize for now to avoid multiple leading slashes
            fields['path'] = '/' + fields['path'].lstrip('/')
        # escape path so we have direct representation of the path to work with
        fields['path'] = unescape_ssh_path(fields['path'])

    def as_str(self):
        fields = self.fields  # copy so we could escape symbols
        url_fmt = '{hostname}'
        if fields['username']:
            url_fmt = "{username}@" + url_fmt
        if fields['path']:
            url_fmt += ':{path}'
        fields['path'] = escape_ssh_path(fields['path'])
        return url_fmt.format(**fields)


class DataLadRI(RI, RegexBasedURLMixin):
    """RI pointing to datasets within central DataLad super-dataset"""

    _FIELDS = RI._FIELDS + (
        'remote',
    )

    # For now or forever we don't deal with any fragments or other special stuff
    _REGEX = re.compile(r'//(?P<remote>[^\s/]*)/(?P<path>.*)$')

    # do they need to be normalized??? loosing track ...

    def as_str(self):
        return "//{remote}/{path}".format(**self._fields)


def _split_colon(s, maxsplit=1):
    """Split on unescaped colon"""
    return re.compile(r'(?<!\\):').split(s, maxsplit=maxsplit)

# \ should be first to deal with
_SSH_ESCAPED_CHARACTERS = '\\#&;`|*?~<>^()[]{}$\'" '


# TODO: RF using re.sub
def escape_ssh_path(path):
    """Escape all special characters present in the path"""
    for c in _SSH_ESCAPED_CHARACTERS:
        if c in path:
            path = path.replace(c, '\\' + c)
    return path


def unescape_ssh_path(path):
    """Un-escape all special characters present in the path"""
    for c in _SSH_ESCAPED_CHARACTERS[::-1]:
        if c in path:
            path = path.replace('\\' + c, c)
    return path


def parse_url_opts(url):
    """Given a string with url-style query, split into content before # and options as dict"""
    url = URL(url)
    # we need to filter out query and fragment to get the base url
    fields = url.fields
    fields.pop('query')
    fields.pop('fragment')
    opts = url.query_dict
    return str(URL(**fields)), opts


# TODO: should we just define URL.good_for_git or smth like that? ;)
# although git also understands regular paths
def is_url(s):
    """Returns whether a string looks like something what datalad should treat as a URL

    This includes ssh "urls" which git understands.
    """
    try:
        ri = RI(s)
    except:
        return False
    return isinstance(ri, (URL, SSHRI))


# TODO: better name? additionally may be move to SSHRI.is_valid() or sth.
def is_ssh(ri):
    """helper to determine, whether `ri` requires an SSH connection

    Parameters
    ----------
    ri: str or RI

    Returns
    -------
    bool
    """

    # not exactly fitting the doc, but we actually can deal not necessarily with
    # string or RI only, but with everything RI itself can deal with:
    _ri = RI(ri) if not isinstance(ri, RI) else ri

    return isinstance(_ri, SSHRI) or \
           (isinstance(_ri, URL) and _ri.scheme == 'ssh')


#### windows workaround ###
# TODO: There should be a better way
def get_local_file_url(fname):
    """Return OS specific URL pointing to a local file

    Parameters
    ----------
    fname : string
        Filename.  If not absolute, abspath is used
    """
    fname = fname if isabs(fname) else abspath(fname)
    if on_windows:
        fname_rep = fname.replace('\\', '/')
        furl = "file:///%s" % urlquote(fname_rep)
        lgr.debug("Replaced '\\' in file\'s url: %s" % furl)
    else:
        # TODO:  need to fix for all the encoding etc
        furl = str(URL(scheme='file', path=fname))
    return furl


def get_local_path_from_url(url):
    """If given a file:// URL, returns a local path, if possible.

    Raises `ValueError` if not possible, for example, if the URL
    scheme is different, or if the `host` isn't empty or 'localhost'

    The returned path is always absolute.
    """
    urlparts = urlsplit(url)
    if not urlparts.scheme == 'file':
        raise ValueError(
            "Non 'file://' URL cannot be resolved to a local path")
    if not (urlparts.netloc in ('', 'localhost', '::1') \
            or urlparts.netloc.startswith('127.')):
        raise ValueError("file:// URL does not point to 'localhost'")
    return urlunquote(urlparts.path)

```
--- 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:** `is_url` Fails to Recognize RI Instances as URLs

**Description:**
The `is_url` function currently does not handle `RI` (Resource Identifier) instances correctly. When an `RI` instance is passed to `is_url`, the function fails to identify it as a valid URL, leading to incorrect behavior.

**Example Buggy Code:**
```python
from datalad.support.network import is_url, RI

# Attempting to check if an RI instance is a URL
result = is_url(RI('file://localhost/some'))
print(result)  # Unexpectedly returns False
```

**Expected Behavior:**
The `is_url` function should return `True` when a valid `RI` instance representing a URL is passed. It should correctly identify and handle both string URLs and `RI` instances.

**Actual Behavior:**
Passing an `RI` instance to `is_url` results in `False`, even when the `RI` instance represents a valid URL. This prevents proper URL recognition and handling within the application.

[/ISSUE]
{
    "test_same_website": "PASSED",
    "test_get_tld": "PASSED",
    "test_dlurljoin": "PASSED",
    "test_rfc2822_to_epoch": "PASSED",
    "test_get_response_disposition_filename": "PASSED",
    "test_parse_url_opts": "PASSED",
    "test_split_colon": "PASSED",
    "test_url_eq": "PASSED",
    "test_url_base": "PASSED",
    "test_url_compose_archive_one": "PASSED",
    "test_url_fragments_and_query": "PASSED",
    "test_url_dicts": "PASSED",
    "test_get_url_path_on_fileurls": "PASSED",
    "test_is_url": "PASSED",
    "test_get_local_path_from_url": "PASSED",
    "test_is_ssh": "PASSED",
    "test_url_samples": "FAILED",
    "test_get_local_file_url_linux": "FAILED"
}
diff --git a/datalad/distribution/dataset.py b/datalad/distribution/dataset.py
index 061006b8a..644be3d7c 100644
--- a/datalad/distribution/dataset.py
+++ b/datalad/distribution/dataset.py
@@ -27,7 +27,7 @@ lgr = logging.getLogger('datalad.dataset')
 def resolve_path(path, ds=None):
     """Resolve a path specification (against a Dataset location)
 
-    Any explicit path (absolute or relative) is return as an absolute path.
+    Any explicit path (absolute or relative) is returned as an absolute path.
     In case of an explicit relative path, the current working directory is
     used as a reference. Any non-explicit relative path is resolved against
     as dataset location, i.e. considered relative to the location of the
diff --git a/datalad/support/network.py b/datalad/support/network.py
index af42a6f1c..178445296 100644
--- a/datalad/support/network.py
+++ b/datalad/support/network.py
@@ -701,15 +701,21 @@ def parse_url_opts(url):
 
 # TODO: should we just define URL.good_for_git or smth like that? ;)
 # although git also understands regular paths
-def is_url(s):
-    """Returns whether a string looks like something what datalad should treat as a URL
+def is_url(ri):
+    """Returns whether argument looks like something what datalad should treat as a URL
 
     This includes ssh "urls" which git understands.
+
+    Parameters
+    ----------
+    ri : str or RI
+      The resource identifier (as a string or RI) to "analyze"
     """
-    try:
-        ri = RI(s)
-    except:
-        return False
+    if not isinstance(ri, RI):
+        try:
+            ri = RI(ri)
+        except:
+            return False
     return isinstance(ri, (URL, SSHRI))
 
 

{"datalad/support/network.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\nimport calendar\nimport email.utils\nimport gzip\nimport os\nimport re\nimport shutil\nimport time\n\nfrom collections import OrderedDict\nfrom os.path import abspath, isabs\n\nfrom six import string_types\nfrom six import iteritems\nfrom six.moves.urllib.request import urlopen, Request\nfrom six.moves.urllib.parse import quote as urlquote, unquote as urlunquote\nfrom six.moves.urllib.parse import urljoin, urlparse, urlsplit, urlunsplit, urlunparse, ParseResult\nfrom six.moves.urllib.parse import parse_qsl\nfrom six.moves.urllib.parse import urlencode\nfrom six.moves.urllib.error import URLError\n\nfrom datalad.utils import on_windows\n\nfrom datalad.utils import auto_repr\n# TODO not sure what needs to use `six` here yet\nimport requests\n\nimport logging\nlgr = logging.getLogger('datalad.network')\n\n\ndef get_response_disposition_filename(s):\n    \"\"\"Given a string s as from HTTP Content-Disposition field in the response\n    return possibly present filename if any\n    \"\"\"\n    if not s:\n        return None\n    # If the response has Content-Disposition, try to get filename from it\n    cd = dict(map(\n        lambda x: x.strip().split('=') if '=' in x else (x.strip(),''),\n        s.split(';')))\n    if 'filename' in cd:\n        filename = cd['filename'].strip(\"\\\"'\")\n        return filename\n    return None\n\n\ndef get_url_disposition_filename(url, headers=None):\n    \"\"\"Get filename as possibly provided by the server in Content-Disposition\n    \"\"\"\n    if headers is None:\n        request = Request(url)\n        r = retry_urlopen(request)\n        # things are different in requests\n        if 'requests.' in str(r.__class__):\n            headers = r.headers\n        else:\n            headers = r.info()\n    else:\n        r = None\n    try:\n        return get_response_disposition_filename(headers.get('Content-Disposition', ''))\n    finally:\n        if r:\n            r.close()\n\n\ndef get_url_straight_filename(url, strip=[], allowdir=False):\n    \"\"\"Get file/dir name of the last path component of the URL\n\n    Parameters\n    ----------\n    strip: list, optional\n      If provided, listed names will not be considered and their\n      parent directory will be selected\n    allowdir: bool, optional\n      If url points to a \"directory\" (ends with /), empty string\n      would be returned unless allowdir is True, in which case the\n      name of the directory would be returned\n    \"\"\"\n    path = urlunquote(urlsplit(url).path)\n    path_parts = path.split('/')\n\n    if allowdir:\n        # strip empty ones\n        while len(path_parts) > 1 and not path_parts[-1]:\n            path_parts = path_parts[:-1]\n\n    if strip:\n        while path_parts and path_parts[-1] in strip:\n            path_parts = path_parts[:-1]\n\n    if path_parts:\n        return path_parts[-1]\n    else:\n        return None\n\n\ndef get_url_filename(url, headers=None, strip=[]):\n    \"\"\"Get filename from the url, first consulting server about Content-Disposition\n    \"\"\"\n    filename = get_url_disposition_filename(url, headers)\n    if filename:\n        return filename\n    return get_url_straight_filename(url, strip=[])\n\n\ndef get_url_response_stamp(url, response_info):\n    size, mtime = None, None\n    if 'Content-length' in response_info:\n        size = int(response_info['Content-length'])\n    if 'Last-modified' in response_info:\n        mtime = calendar.timegm(email.utils.parsedate(\n            response_info['Last-modified']))\n    return dict(size=size, mtime=mtime, url=url)\n\n\ndef get_tld(url):\n    \"\"\"Return top level domain from a url\n\n    Parameters\n    ----------\n    url : str\n    \"\"\"\n    # maybe use this instead to be safe:  https://pypi.python.org/pypi/tld\n    if not url.strip():\n        raise ValueError(\"Empty URL has no TLD\")\n    rec = urlsplit(url)\n    if not rec.netloc:\n        if not rec.scheme:\n            # There were no scheme provided thus netloc was empty -- must have been a simple 'path like'\n            return url.split('/', 1)[0]\n        else:\n            raise ValueError(\"It seems that only the scheme was provided without the net location/TLD\")\n    return rec.netloc\n\n\nfrom email.utils import parsedate_tz, mktime_tz\ndef rfc2822_to_epoch(datestr):\n    \"\"\"Given rfc2822 date/time format, return seconds since epoch\"\"\"\n    return mktime_tz(parsedate_tz(datestr))\n\n\nimport calendar\nfrom datetime import datetime\ndef iso8601_to_epoch(datestr):\n    return calendar.timegm(datetime.strptime(datestr, \"%Y-%m-%dT%H:%M:%S.%fZ\").timetuple())\n\n\ndef __urlopen_requests(url, header_vals=None):\n    # XXX Workaround for now for ... broken code\n    if isinstance(url, Request):\n        url = url.get_full_url()\n    return requests.Session().get(url)\n\n\ndef retry_urlopen(url, retries=3):\n    for t in range(retries):\n        try:\n            return __urlopen_requests(url)\n        except URLError as e:\n            lgr.warn(\"Received exception while reading %s: %s\" % (url, e))\n            if t == retries - 1:\n                # if we have reached allowed number of retries -- reraise\n                raise\n\n\ndef is_url_quoted(url):\n    \"\"\"Return either URL looks being already quoted\n    \"\"\"\n    try:\n        url_ = urlunquote(url)\n        return url != url_\n    except:  # problem with unquoting -- then it must be wasn't quoted (correctly)\n        return False\n\n\ndef same_website(url_rec, u_rec):\n    \"\"\"Decide either a link leads to external site\n\n    Parameters\n    ----------\n    url_rec: ParseResult\n      record for original url\n    u_rec: ParseResult\n      record for new url\n    \"\"\"\n    if isinstance(url_rec, string_types):\n        url_rec = urlparse(url_rec)\n    if isinstance(u_rec, string_types):\n        u_rec = urlparse(u_rec)\n    return (url_rec.netloc == u_rec.netloc)\n    # todo: collect more of sample cases.\n    # disabled below check while working on ratholeradio, since links\n    # could go to the parent and that is ok.  Figure out when it was\n    # desired not to go to the parent -- we might need explicit option\n    # and u_rec.path.startswith(url_rec.path)):\n\n\ndef dlurljoin(u_path, url):\n    url_rec = urlparse(url)  # probably duplicating parsing :-/ TODO\n    if url_rec.scheme:\n        # independent full url, so just return it\n        return url\n    if u_path.endswith('/'):  # should here be also a scheme use?\n        if url.startswith('/'):  # jump to the root\n            u_path_rec = urlparse(u_path)\n            return urljoin(urlunparse(\n                (u_path_rec.scheme, u_path_rec.netloc, '', '', '', '')), url)\n        else:\n            return os.path.join(u_path, url)\n    # TODO: recall where all this dirname came from and bring into the test\n    return urljoin(os.path.dirname(u_path) + '/', url)\n\n\n# TODO should it be a node maybe?\nclass SimpleURLStamper(object):\n    \"\"\"Gets a simple stamp about the URL: {url, time, size} of whatever was provided in the header\n    \"\"\"\n    def __init__(self, mode='full'):\n        self.mode = mode\n\n    def __call__(self, url):\n        # Extracted from above madness\n        # TODO: add mode alike to 'relaxed' where we would not\n        # care about content-disposition filename\n        # http://stackoverflow.com/questions/862173/how-to-download-a-file-using-python-in-a-smarter-way\n        request = Request(url)\n\n        # No traffic compression since we do not know how to identify\n        # exactly either it has to be decompressed\n        # request.add_header('Accept-encoding', 'gzip,deflate')\n        #\n        # TODO: think about stamping etc -- we seems to be redoing\n        # what git-annex does for us already... not really\n        r = retry_urlopen(request)\n        try:\n            r_info = r.info()\n            r_stamp = get_url_response_stamp(url, r_info)\n\n            return dict(mtime=r_stamp['mtime'], size=r_stamp['size'], url=url)\n        finally:\n            r.close()\n\n\n# TODO:  make it consistent/clear at what stage % encoding/decoding happens!\n# now it is a mix!\n\n#\n# Useful functionality in requests.models\n#  utils.requote_uri -- quote/unquote cycle to guarantee consistent appearance\n#  RequestEncodingMixin._encode_params -- Will successfully encode parameters when passed as a dict or a list of ...\n#  PreparedRequest().prepare_url(url, params) -- nicely cares about url encodings etc\n#\n\ndef _guess_ri_cls(ri):\n    \"\"\"Factory function which would determine which type of a ri a provided string is\"\"\"\n    # We assume that it is a URL and parse it. Depending on the result\n    # we might decide that it was something else ;)\n    fields = URL._pr_to_fields(urlparse(ri))\n    lgr.log(5, \"Parsed ri %s into fields %s\" % (ri, fields))\n\n    type_ = 'url'\n    # Special treatments\n    # file:///path should stay file:\n    if fields['scheme'] and fields['scheme'] not in {'file'} \\\n            and not fields['hostname']:\n        # dl+archive:... or just for ssh   hostname:path/p1\n        if '+' not in fields['scheme']:\n            type_ = 'ssh'\n            lgr.log(5, \"Assuming ssh style ri, adjusted: %s\" % (fields,))\n\n    if not fields['scheme'] and not fields['hostname']:\n        parts = _split_colon(ri)\n        if fields['path'] and '@' in fields['path'] or len(parts) > 1:\n            # user@host:path/sp1\n            # or host_name: (hence parts check)\n            # TODO: we need a regex to catch those really, parts check is not suff\n            type_ = 'ssh'\n        elif ri.startswith('//'):\n            # e.g. // or ///path\n            type_ = 'datalad'\n        else:\n            type_ = 'file'\n\n    if not fields['scheme'] and fields['hostname']:\n        # e.g. //a/path\n        type_ = 'datalad'\n\n    TYPES = {\n        'url': URL,\n        'ssh':  SSHRI,\n        'file': PathRI,\n        'datalad': DataLadRI\n    }\n    cls = TYPES[type_]\n    # just parse the ri according to regex matchint ssh \"ri\" specs\n    lgr.log(5, \"Detected %s ri\" % type_)\n    return cls\n\n\nclass RI(object):\n    \"\"\"Resource Identifier - base class and a factory for URL, SSHRI, etc\n\n    Intended to be a R/O object (i.e. no fields should be changed in-place).\n    Subclasses define specific collections of fields they care about in _FIELDS\n    class variable.\n    The idea is that this class should help to break apart a URL, while being\n    able to rebuild itself into a string representation for reuse\n\n    `RI` could be used as factory, whenever type of the resource is unknown and\n    must be guessed from the string representation.  One of the subclasses will be\n    provided as output, e.g.\n\n    >>> RI('http://example.com')\n    URL(hostname='example.com', scheme='http')\n    >>> RI('example.com:path')\n    SSHRI(hostname='example.com', path='path')\n    \"\"\"\n\n    # All of the subclasses will provide path\n    _FIELDS = (\n        'path',\n    )\n\n    __slots__ = _FIELDS + ('_fields', '_str')\n\n    def __new__(cls, ri=None, **kwargs):\n        \"\"\"Used as a possible factory for known RI types\n\n        Returns\n        -------\n        RI\n           uninitialized RI object of appropriate class with _str\n           set to string representation if was provided\n\n        \"\"\"\n        if cls is RI and ri is not None:\n            # RI class was used as a factory\n            cls = _guess_ri_cls(ri)\n\n        ri_obj = super(RI, cls).__new__(cls)\n        # Store internally original str\n        ri_obj._str = ri\n        return ri_obj\n\n    def __init__(self, ri=None, **fields):\n        \"\"\"\n        Parameters\n        ----------\n        ri: str, optional\n          String version of a resource specific for this class.  If you would like\n          a type of the resource be deduced, use RI(ri)\n        **fields: dict, optional\n          The values for the fields defined in _FIELDS class variable.\n        \"\"\"\n        if ri and (bool(ri) == bool(fields)):\n            raise ValueError(\n                \"Specify either ri or breakdown from the fields, not both. \"\n                \"Got ri=%r, fields=%r\" % (ri, fields))\n\n        self._fields = self._get_blank_fields()\n        if ri is not None:\n            fields = self._str_to_fields(ri)\n        self._set_from_fields(**fields)\n\n        # If was initialized from a string representation\n        if self._str is not None:\n            # well -- some ris might not unparse identically back\n            # strictly speaking, but let's assume they do\n            ri_ = self.as_str()\n            if ri != ri_:\n                lgr.warning(\"Parsed version of %s %r differs from original %r\",\n                            self.__class__.__name__, ri_, ri)\n\n    @classmethod\n    def _get_blank_fields(cls, **fields):\n        return OrderedDict(((f, fields.get(f, '')) for f in cls._FIELDS))\n\n    @property\n    def fields(self):\n        \"\"\"Returns shallow copy of fields to ease manipulations\"\"\"\n        return self._fields.copy()\n\n    def __repr__(self):\n        # since auto_repr doesn't support \"non-0\" values atm\n        return \"%s(%s)\" % (\n            self.__class__.__name__,\n            \", \".join([\"%s=%r\" % (k, v)\n                       for k, v in sorted(self._fields.items())\n                       if v]))\n\n    # Lazily evaluated if _str was not set\n    def __str__(self):\n        if self._str is None:\n            self._str = self.as_str()\n        return self._str\n\n    @classmethod\n    def from_str(cls, ri_str):\n        obj = cls(**cls._str_to_fields(ri_str))\n        obj._str = ri_str\n        return obj\n\n    # Apparently doesn't quite play nicely with multiple inheritence for MixIn'\n    # of regexp based URLs\n    #@abstractmethod\n    #@classmethod\n    #def _str_to_fields(cls, ri_str):\n    #    raise NotImplementedError\n\n    #\n    # If any field is specified, URL is not considered 'False', i.e.\n    # non-existing, although may be we could/shout omit having only\n    # scheme or port specified since it doesn't point to any useful\n    # location\n    #\n\n    def __nonzero__(self):\n        fields = self._fields\n        return any(fields.values())\n\n    # for PY3\n    __bool__ = __nonzero__\n\n    #\n    # Helpers to deal with internal structures and conversions\n    #\n\n    def _set_from_fields(self, **fields):\n        unknown_fields = set(fields).difference(self._FIELDS)\n        if unknown_fields:\n            raise ValueError(\"Do not know about %s. Known fields for %s are: %s\"\n                             % (unknown_fields, self.__class__, self._FIELDS))\n\n        # encode dicts for query or fragment into\n        for f in {'query', 'fragment'}:\n            v = fields.get(f)\n            if isinstance(v, dict):\n\n                ev = urlencode(v)\n                # / is reserved char within query\n                if f == 'fragment' and '%2F' not in str(v):\n                    # but seems to be ok'ish within the fragment which is\n                    # the last element of URI and anyways used only by the\n                    # client (i.e. by us here if used to compose the URL)\n                    # so let's return / back for clarity if there were no\n                    # awkward %2F to startswith\n                    ev = ev.replace('%2F', '/')\n                fields[f] = ev\n\n        self._fields.update(fields)\n\n    #\n    # Quick comparators\n    #\n\n    def __eq__(self, other):\n        if not isinstance(other, RI):\n            other = RI(other)\n        return isinstance(other, self.__class__) and dict(other._fields) == dict(self._fields)\n\n    def __ne__(self, other):\n        return not (self == other)\n\n    def __getattribute__(self, item):\n        if item.startswith('_') or item not in self._FIELDS:\n            return super(RI, self).__getattribute__(item)\n        else:\n            return self._fields[item]\n\n\nclass URL(RI):\n    \"\"\"Universal resource locator\n\n    Although largely decorating urlparse.ParseResult, it\n    - doesn't mandate providing all parts of the URL\n    - doesn't require netloc but rather asks for separate username, password, and hostname\n    \"\"\"\n\n    _FIELDS = RI._FIELDS + (\n        'scheme',\n        'username',\n        'password',\n        'hostname', 'port',\n        'query',\n        'fragment',\n    )\n\n    def as_str(self):\n        \"\"\"Render URL as a string\"\"\"\n        return urlunparse(self.to_pr())\n\n    @classmethod\n    def _str_to_fields(cls, url_str):\n        fields = URL._pr_to_fields(urlparse(url_str))\n        fields['path'] = urlunquote(fields['path'])\n        return fields\n\n    def to_pr(self):\n        \"\"\"Convert URL to urlparse.ParseResults namedtuple\"\"\"\n        return self._fields_to_pr(self._fields)\n\n    @classmethod\n    def _fields_to_pr(cls, fields):\n        \"\"\"Recompose back fields dict to ParseResult\"\"\"\n        netloc = fields['username'] or ''\n        if fields['password']:\n            netloc += ':' + fields['password']\n        if netloc:\n            netloc += '@'\n        netloc += fields['hostname']\n        if fields['port']:\n            netloc += ':%s' % fields['port']\n\n        pr_fields = {\n            f: fields[f]\n            for f in cls._FIELDS\n            if f not in ('hostname', 'password', 'username', 'port')\n        }\n        pr_fields['netloc'] = netloc\n        pr_fields['params'] = ''\n        # We need to quote the path\n        pr_fields['path'] = urlquote(pr_fields['path'])\n        # TODO: figure out what to do with query/fragment... one step at a time\n        return ParseResult(**pr_fields)\n\n    @classmethod\n    def _pr_to_fields(cls, pr):\n        \"\"\"ParseResult is a tuple so immutable, which complicates adjusting it\n\n        This function converts ParseResult into dict\"\"\"\n\n        if pr.params:\n            lgr.warning(\"ParseResults contains params %r, which will be ignored\"\n                        % (pr.params,))\n\n        # can't use just pr._asdict since we care to ask those properties\n        # such as .port , .hostname etc\n        # Forcing '' instead of None since those properties (.hostname), .password,\n        # .username return None if not available and we decided to uniformize\n        return {f: (getattr(pr, f) or '') for f in cls._FIELDS}\n\n    #\n    # Access helpers\n    #\n\n    def _parse_qs(self, s, auto_delist=True):\n        \"\"\"Helper around parse_qs to strip unneeded 'list'ing etc and return a dict of key=values\"\"\"\n        if not s:\n            return {}\n        out = OrderedDict(parse_qsl(s, 1))\n        if not auto_delist:\n            return out\n        for k in out:\n            v = out[k]\n            if isinstance(v, list) and len(v) == 1:\n                v = v[0]\n                out[k] = None if v == '' else v\n        return out\n\n    @property\n    def query_dict(self):\n        return self._parse_qs(self.query)\n\n    @property\n    def fragment_dict(self):\n        return self._parse_qs(self.fragment)\n\n\nclass PathRI(RI):\n    \"\"\"RI pointing to a (local) file/directory\"\"\"\n    def as_str(self):\n        return self.path\n\n    @classmethod\n    def _str_to_fields(cls, url_str):\n        return dict(path=url_str)\n\n\nclass RegexBasedURLMixin(object):\n    \"\"\"Base class for URLs which we could simple parse using regular expressions\"\"\"\n\n    _REGEX = None\n\n    # not used ATM but possible ;)\n    # @classmethod\n    # def is_str_matches(cls, url_str):\n    #     return bool(cls._REGEX.match(url_str))\n\n    @classmethod\n    def _str_to_fields(cls, url_str):\n        re_match = cls._REGEX.match(url_str)\n        if not re_match:\n            # TODO: custom error?\n            raise ValueError(\n                \"Possibly incorrectly determined string %r correspond to %s address\"\n                \" -- it failed matching regex. Dunno how to handle. Contact developers\"\n                % (cls, url_str,)\n            )\n        fields = cls._get_blank_fields()\n        fields.update({k: v for k, v in iteritems(re_match.groupdict()) if v})\n        cls._normalize_fields(fields)\n        return fields\n\n    @classmethod\n    def _normalize_fields(self, fields):\n        \"\"\"Helper to be ran if any of the fields need to be normalized after parsing\"\"\"\n        pass\n\n\nclass SSHRI(RI, RegexBasedURLMixin):\n    \"\"\"RI pointing to a remote location reachable via SSH\"\"\"\n\n    _FIELDS = RI._FIELDS + (\n        'username',\n        'hostname',\n        'port',\n    )\n\n    _REGEX = re.compile(r'((?P<username>\\S*)@)?(?P<hostname>[^:]+)(\\:(?P<path>.*))?$')\n\n    @classmethod\n    def _normalize_fields(cls, fields):\n        if fields['path'] and fields['path'].startswith('//'):\n            # Let's normalize for now to avoid multiple leading slashes\n            fields['path'] = '/' + fields['path'].lstrip('/')\n        # escape path so we have direct representation of the path to work with\n        fields['path'] = unescape_ssh_path(fields['path'])\n\n    def as_str(self):\n        fields = self.fields  # copy so we could escape symbols\n        url_fmt = '{hostname}'\n        if fields['username']:\n            url_fmt = \"{username}@\" + url_fmt\n        if fields['path']:\n            url_fmt += ':{path}'\n        fields['path'] = escape_ssh_path(fields['path'])\n        return url_fmt.format(**fields)\n\n\nclass DataLadRI(RI, RegexBasedURLMixin):\n    \"\"\"RI pointing to datasets within central DataLad super-dataset\"\"\"\n\n    _FIELDS = RI._FIELDS + (\n        'remote',\n    )\n\n    # For now or forever we don't deal with any fragments or other special stuff\n    _REGEX = re.compile(r'//(?P<remote>[^\\s/]*)/(?P<path>.*)$')\n\n    # do they need to be normalized??? loosing track ...\n\n    def as_str(self):\n        return \"//{remote}/{path}\".format(**self._fields)\n\n\ndef _split_colon(s, maxsplit=1):\n    \"\"\"Split on unescaped colon\"\"\"\n    return re.compile(r'(?<!\\\\):').split(s, maxsplit=maxsplit)\n\n# \\ should be first to deal with\n_SSH_ESCAPED_CHARACTERS = '\\\\#&;`|*?~<>^()[]{}$\\'\" '\n\n\n# TODO: RF using re.sub\ndef escape_ssh_path(path):\n    \"\"\"Escape all special characters present in the path\"\"\"\n    for c in _SSH_ESCAPED_CHARACTERS:\n        if c in path:\n            path = path.replace(c, '\\\\' + c)\n    return path\n\n\ndef unescape_ssh_path(path):\n    \"\"\"Un-escape all special characters present in the path\"\"\"\n    for c in _SSH_ESCAPED_CHARACTERS[::-1]:\n        if c in path:\n            path = path.replace('\\\\' + c, c)\n    return path\n\n\ndef parse_url_opts(url):\n    \"\"\"Given a string with url-style query, split into content before # and options as dict\"\"\"\n    url = URL(url)\n    # we need to filter out query and fragment to get the base url\n    fields = url.fields\n    fields.pop('query')\n    fields.pop('fragment')\n    opts = url.query_dict\n    return str(URL(**fields)), opts\n\n\n# TODO: should we just define URL.good_for_git or smth like that? ;)\n# although git also understands regular paths\ndef is_url(s):\n    \"\"\"Returns whether a string looks like something what datalad should treat as a URL\n\n    This includes ssh \"urls\" which git understands.\n    \"\"\"\n    try:\n        ri = RI(s)\n    except:\n        return False\n    return isinstance(ri, (URL, SSHRI))\n\n\n# TODO: better name? additionally may be move to SSHRI.is_valid() or sth.\ndef is_ssh(ri):\n    \"\"\"helper to determine, whether `ri` requires an SSH connection\n\n    Parameters\n    ----------\n    ri: str or RI\n\n    Returns\n    -------\n    bool\n    \"\"\"\n\n    # not exactly fitting the doc, but we actually can deal not necessarily with\n    # string or RI only, but with everything RI itself can deal with:\n    _ri = RI(ri) if not isinstance(ri, RI) else ri\n\n    return isinstance(_ri, SSHRI) or \\\n           (isinstance(_ri, URL) and _ri.scheme == 'ssh')\n\n\n#### windows workaround ###\n# TODO: There should be a better way\ndef get_local_file_url(fname):\n    \"\"\"Return OS specific URL pointing to a local file\n\n    Parameters\n    ----------\n    fname : string\n        Filename.  If not absolute, abspath is used\n    \"\"\"\n    fname = fname if isabs(fname) else abspath(fname)\n    if on_windows:\n        fname_rep = fname.replace('\\\\', '/')\n        furl = \"file:///%s\" % urlquote(fname_rep)\n        lgr.debug(\"Replaced '\\\\' in file\\'s url: %s\" % furl)\n    else:\n        # TODO:  need to fix for all the encoding etc\n        furl = str(URL(scheme='file', path=fname))\n    return furl\n\n\ndef get_local_path_from_url(url):\n    \"\"\"If given a file:// URL, returns a local path, if possible.\n\n    Raises `ValueError` if not possible, for example, if the URL\n    scheme is different, or if the `host` isn't empty or 'localhost'\n\n    The returned path is always absolute.\n    \"\"\"\n    urlparts = urlsplit(url)\n    if not urlparts.scheme == 'file':\n        raise ValueError(\n            \"Non 'file://' URL cannot be resolved to a local path\")\n    if not (urlparts.netloc in ('', 'localhost', '::1') \\\n            or urlparts.netloc.startswith('127.')):\n        raise ValueError(\"file:// URL does not point to 'localhost'\")\n    return urlunquote(urlparts.path)\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:** `is_url` Fails to Recognize RI Instances as URLs

**Description:**
The `is_url` function currently does not handle `RI` (Resource Identifier) instances correctly. When an `RI` instance is passed to `is_url`, the function fails to identify it as a valid URL, leading to incorrect behavior.

**Example Buggy Code:**
```python
from datalad.support.network import is_url, RI

# Attempting to check if an RI instance is a URL
result = is_url(RI('file://localhost/some'))
print(result)  # Unexpectedly returns False
```

**Expected Behavior:**
The `is_url` function should return `True` when a valid `RI` instance representing a URL is passed. It should correctly identify and handle both string URLs and `RI` instances.

**Actual Behavior:**
Passing an `RI` instance to `is_url` results in `False`, even when the `RI` instance represents a valid URL. This prevents proper URL recognition and handling within the application.

[/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/support/network.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.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##

import calendar
import email.utils
import gzip
import os
import re
import shutil
import time

from collections import OrderedDict
from os.path import abspath, isabs

from six import string_types
from six import iteritems
from six.moves.urllib.request import urlopen, Request
from six.moves.urllib.parse import quote as urlquote, unquote as urlunquote
from six.moves.urllib.parse import urljoin, urlparse, urlsplit, urlunsplit, urlunparse, ParseResult
from six.moves.urllib.parse import parse_qsl
from six.moves.urllib.parse import urlencode
from six.moves.urllib.error import URLError

from datalad.utils import on_windows

from datalad.utils import auto_repr
# TODO not sure what needs to use `six` here yet
import requests

import logging
lgr = logging.getLogger('datalad.network')


def get_response_disposition_filename(s):
    """Given a string s as from HTTP Content-Disposition field in the response
    return possibly present filename if any
    """
    if not s:
        return None
    # If the response has Content-Disposition, try to get filename from it
    cd = dict(map(
        lambda x: x.strip().split('=') if '=' in x else (x.strip(),''),
        s.split(';')))
    if 'filename' in cd:
        filename = cd['filename'].strip("\"'")
        return filename
    return None


def get_url_disposition_filename(url, headers=None):
    """Get filename as possibly provided by the server in Content-Disposition
    """
    if headers is None:
        request = Request(url)
        r = retry_urlopen(request)
        # things are different in requests
        if 'requests.' in str(r.__class__):
            headers = r.headers
        else:
            headers = r.info()
    else:
        r = None
    try:
        return get_response_disposition_filename(headers.get('Content-Disposition', ''))
    finally:
        if r:
            r.close()


def get_url_straight_filename(url, strip=[], allowdir=False):
    """Get file/dir name of the last path component of the URL

    Parameters
    ----------
    strip: list, optional
      If provided, listed names will not be considered and their
      parent directory will be selected
    allowdir: bool, optional
      If url points to a "directory" (ends with /), empty string
      would be returned unless allowdir is True, in which case the
      name of the directory would be returned
    """
    path = urlunquote(urlsplit(url).path)
    path_parts = path.split('/')

    if allowdir:
        # strip empty ones
        while len(path_parts) > 1 and not path_parts[-1]:
            path_parts = path_parts[:-1]

    if strip:
        while path_parts and path_parts[-1] in strip:
            path_parts = path_parts[:-1]

    if path_parts:
        return path_parts[-1]
    else:
        return None


def get_url_filename(url, headers=None, strip=[]):
    """Get filename from the url, first consulting server about Content-Disposition
    """
    filename = get_url_disposition_filename(url, headers)
    if filename:
        return filename
    return get_url_straight_filename(url, strip=[])


def get_url_response_stamp(url, response_info):
    size, mtime = None, None
    if 'Content-length' in response_info:
        size = int(response_info['Content-length'])
    if 'Last-modified' in response_info:
        mtime = calendar.timegm(email.utils.parsedate(
            response_info['Last-modified']))
    return dict(size=size, mtime=mtime, url=url)


def get_tld(url):
    """Return top level domain from a url

    Parameters
    ----------
    url : str
    """
    # maybe use this instead to be safe:  https://pypi.python.org/pypi/tld
    if not url.strip():
        raise ValueError("Empty URL has no TLD")
    rec = urlsplit(url)
    if not rec.netloc:
        if not rec.scheme:
            # There were no scheme provided thus netloc was empty -- must have been a simple 'path like'
            return url.split('/', 1)[0]
        else:
            raise ValueError("It seems that only the scheme was provided without the net location/TLD")
    return rec.netloc


from email.utils import parsedate_tz, mktime_tz
def rfc2822_to_epoch(datestr):
    """Given rfc2822 date/time format, return seconds since epoch"""
    return mktime_tz(parsedate_tz(datestr))


import calendar
from datetime import datetime
def iso8601_to_epoch(datestr):
    return calendar.timegm(datetime.strptime(datestr, "%Y-%m-%dT%H:%M:%S.%fZ").timetuple())


def __urlopen_requests(url, header_vals=None):
    # XXX Workaround for now for ... broken code
    if isinstance(url, Request):
        url = url.get_full_url()
    return requests.Session().get(url)


def retry_urlopen(url, retries=3):
    for t in range(retries):
        try:
            return __urlopen_requests(url)
        except URLError as e:
            lgr.warn("Received exception while reading %s: %s" % (url, e))
            if t == retries - 1:
                # if we have reached allowed number of retries -- reraise
                raise


def is_url_quoted(url):
    """Return either URL looks being already quoted
    """
    try:
        url_ = urlunquote(url)
        return url != url_
    except:  # problem with unquoting -- then it must be wasn't quoted (correctly)
        return False


def same_website(url_rec, u_rec):
    """Decide either a link leads to external site

    Parameters
    ----------
    url_rec: ParseResult
      record for original url
    u_rec: ParseResult
      record for new url
    """
    if isinstance(url_rec, string_types):
        url_rec = urlparse(url_rec)
    if isinstance(u_rec, string_types):
        u_rec = urlparse(u_rec)
    return (url_rec.netloc == u_rec.netloc)
    # todo: collect more of sample cases.
    # disabled below check while working on ratholeradio, since links
    # could go to the parent and that is ok.  Figure out when it was
    # desired not to go to the parent -- we might need explicit option
    # and u_rec.path.startswith(url_rec.path)):


def dlurljoin(u_path, url):
    url_rec = urlparse(url)  # probably duplicating parsing :-/ TODO
    if url_rec.scheme:
        # independent full url, so just return it
        return url
    if u_path.endswith('/'):  # should here be also a scheme use?
        if url.startswith('/'):  # jump to the root
            u_path_rec = urlparse(u_path)
            return urljoin(urlunparse(
                (u_path_rec.scheme, u_path_rec.netloc, '', '', '', '')), url)
        else:
            return os.path.join(u_path, url)
    # TODO: recall where all this dirname came from and bring into the test
    return urljoin(os.path.dirname(u_path) + '/', url)


# TODO should it be a node maybe?
class SimpleURLStamper(object):
    """Gets a simple stamp about the URL: {url, time, size} of whatever was provided in the header
    """
    def __init__(self, mode='full'):
        self.mode = mode

    def __call__(self, url):
        # Extracted from above madness
        # TODO: add mode alike to 'relaxed' where we would not
        # care about content-disposition filename
        # http://stackoverflow.com/questions/862173/how-to-download-a-file-using-python-in-a-smarter-way
        request = Request(url)

        # No traffic compression since we do not know how to identify
        # exactly either it has to be decompressed
        # request.add_header('Accept-encoding', 'gzip,deflate')
        #
        # TODO: think about stamping etc -- we seems to be redoing
        # what git-annex does for us already... not really
        r = retry_urlopen(request)
        try:
            r_info = r.info()
            r_stamp = get_url_response_stamp(url, r_info)

            return dict(mtime=r_stamp['mtime'], size=r_stamp['size'], url=url)
        finally:
            r.close()


# TODO:  make it consistent/clear at what stage % encoding/decoding happens!
# now it is a mix!

#
# Useful functionality in requests.models
#  utils.requote_uri -- quote/unquote cycle to guarantee consistent appearance
#  RequestEncodingMixin._encode_params -- Will successfully encode parameters when passed as a dict or a list of ...
#  PreparedRequest().prepare_url(url, params) -- nicely cares about url encodings etc
#

def _guess_ri_cls(ri):
    """Factory function which would determine which type of a ri a provided string is"""
    # We assume that it is a URL and parse it. Depending on the result
    # we might decide that it was something else ;)
    fields = URL._pr_to_fields(urlparse(ri))
    lgr.log(5, "Parsed ri %s into fields %s" % (ri, fields))

    type_ = 'url'
    # Special treatments
    # file:///path should stay file:
    if fields['scheme'] and fields['scheme'] not in {'file'} \
            and not fields['hostname']:
        # dl+archive:... or just for ssh   hostname:path/p1
        if '+' not in fields['scheme']:
            type_ = 'ssh'
            lgr.log(5, "Assuming ssh style ri, adjusted: %s" % (fields,))

    if not fields['scheme'] and not fields['hostname']:
        parts = _split_colon(ri)
        if fields['path'] and '@' in fields['path'] or len(parts) > 1:
            # user@host:path/sp1
            # or host_name: (hence parts check)
            # TODO: we need a regex to catch those really, parts check is not suff
            type_ = 'ssh'
        elif ri.startswith('//'):
            # e.g. // or ///path
            type_ = 'datalad'
        else:
            type_ = 'file'

    if not fields['scheme'] and fields['hostname']:
        # e.g. //a/path
        type_ = 'datalad'

    TYPES = {
        'url': URL,
        'ssh':  SSHRI,
        'file': PathRI,
        'datalad': DataLadRI
    }
    cls = TYPES[type_]
    # just parse the ri according to regex matchint ssh "ri" specs
    lgr.log(5, "Detected %s ri" % type_)
    return cls


class RI(object):
    """Resource Identifier - base class and a factory for URL, SSHRI, etc

    Intended to be a R/O object (i.e. no fields should be changed in-place).
    Subclasses define specific collections of fields they care about in _FIELDS
    class variable.
    The idea is that this class should help to break apart a URL, while being
    able to rebuild itself into a string representation for reuse

    `RI` could be used as factory, whenever type of the resource is unknown and
    must be guessed from the string representation.  One of the subclasses will be
    provided as output, e.g.

    >>> RI('http://example.com')
    URL(hostname='example.com', scheme='http')
    >>> RI('example.com:path')
    SSHRI(hostname='example.com', path='path')
    """

    # All of the subclasses will provide path
    _FIELDS = (
        'path',
    )

    __slots__ = _FIELDS + ('_fields', '_str')

    def __new__(cls, ri=None, **kwargs):
        """Used as a possible factory for known RI types

        Returns
        -------
        RI
           uninitialized RI object of appropriate class with _str
           set to string representation if was provided

        """
        if cls is RI and ri is not None:
            # RI class was used as a factory
            cls = _guess_ri_cls(ri)

        ri_obj = super(RI, cls).__new__(cls)
        # Store internally original str
        ri_obj._str = ri
        return ri_obj

    def __init__(self, ri=None, **fields):
        """
        Parameters
        ----------
        ri: str, optional
          String version of a resource specific for this class.  If you would like
          a type of the resource be deduced, use RI(ri)
        **fields: dict, optional
          The values for the fields defined in _FIELDS class variable.
        """
        if ri and (bool(ri) == bool(fields)):
            raise ValueError(
                "Specify either ri or breakdown from the fields, not both. "
                "Got ri=%r, fields=%r" % (ri, fields))

        self._fields = self._get_blank_fields()
        if ri is not None:
            fields = self._str_to_fields(ri)
        self._set_from_fields(**fields)

        # If was initialized from a string representation
        if self._str is not None:
            # well -- some ris might not unparse identically back
            # strictly speaking, but let's assume they do
            ri_ = self.as_str()
            if ri != ri_:
                lgr.warning("Parsed version of %s %r differs from original %r",
                            self.__class__.__name__, ri_, ri)

    @classmethod
    def _get_blank_fields(cls, **fields):
        return OrderedDict(((f, fields.get(f, '')) for f in cls._FIELDS))

    @property
    def fields(self):
        """Returns shallow copy of fields to ease manipulations"""
        return self._fields.copy()

    def __repr__(self):
        # since auto_repr doesn't support "non-0" values atm
        return "%s(%s)" % (
            self.__class__.__name__,
            ", ".join(["%s=%r" % (k, v)
                       for k, v in sorted(self._fields.items())
                       if v]))

    # Lazily evaluated if _str was not set
    def __str__(self):
        if self._str is None:
            self._str = self.as_str()
        return self._str

    @classmethod
    def from_str(cls, ri_str):
        obj = cls(**cls._str_to_fields(ri_str))
        obj._str = ri_str
        return obj

    # Apparently doesn't quite play nicely with multiple inheritence for MixIn'
    # of regexp based URLs
    #@abstractmethod
    #@classmethod
    #def _str_to_fields(cls, ri_str):
    #    raise NotImplementedError

    #
    # If any field is specified, URL is not considered 'False', i.e.
    # non-existing, although may be we could/shout omit having only
    # scheme or port specified since it doesn't point to any useful
    # location
    #

    def __nonzero__(self):
        fields = self._fields
        return any(fields.values())

    # for PY3
    __bool__ = __nonzero__

    #
    # Helpers to deal with internal structures and conversions
    #

    def _set_from_fields(self, **fields):
        unknown_fields = set(fields).difference(self._FIELDS)
        if unknown_fields:
            raise ValueError("Do not know about %s. Known fields for %s are: %s"
                             % (unknown_fields, self.__class__, self._FIELDS))

        # encode dicts for query or fragment into
        for f in {'query', 'fragment'}:
            v = fields.get(f)
            if isinstance(v, dict):

                ev = urlencode(v)
                # / is reserved char within query
                if f == 'fragment' and '%2F' not in str(v):
                    # but seems to be ok'ish within the fragment which is
                    # the last element of URI and anyways used only by the
                    # client (i.e. by us here if used to compose the URL)
                    # so let's return / back for clarity if there were no
                    # awkward %2F to startswith
                    ev = ev.replace('%2F', '/')
                fields[f] = ev

        self._fields.update(fields)

    #
    # Quick comparators
    #

    def __eq__(self, other):
        if not isinstance(other, RI):
            other = RI(other)
        return isinstance(other, self.__class__) and dict(other._fields) == dict(self._fields)

    def __ne__(self, other):
        return not (self == other)

    def __getattribute__(self, item):
        if item.startswith('_') or item not in self._FIELDS:
            return super(RI, self).__getattribute__(item)
        else:
            return self._fields[item]


class URL(RI):
    """Universal resource locator

    Although largely decorating urlparse.ParseResult, it
    - doesn't mandate providing all parts of the URL
    - doesn't require netloc but rather asks for separate username, password, and hostname
    """

    _FIELDS = RI._FIELDS + (
        'scheme',
        'username',
        'password',
        'hostname', 'port',
        'query',
        'fragment',
    )

    def as_str(self):
        """Render URL as a string"""
        return urlunparse(self.to_pr())

    @classmethod
    def _str_to_fields(cls, url_str):
        fields = URL._pr_to_fields(urlparse(url_str))
        fields['path'] = urlunquote(fields['path'])
        return fields

    def to_pr(self):
        """Convert URL to urlparse.ParseResults namedtuple"""
        return self._fields_to_pr(self._fields)

    @classmethod
    def _fields_to_pr(cls, fields):
        """Recompose back fields dict to ParseResult"""
        netloc = fields['username'] or ''
        if fields['password']:
            netloc += ':' + fields['password']
        if netloc:
            netloc += '@'
        netloc += fields['hostname']
        if fields['port']:
            netloc += ':%s' % fields['port']

        pr_fields = {
            f: fields[f]
            for f in cls._FIELDS
            if f not in ('hostname', 'password', 'username', 'port')
        }
        pr_fields['netloc'] = netloc
        pr_fields['params'] = ''
        # We need to quote the path
        pr_fields['path'] = urlquote(pr_fields['path'])
        # TODO: figure out what to do with query/fragment... one step at a time
        return ParseResult(**pr_fields)

    @classmethod
    def _pr_to_fields(cls, pr):
        """ParseResult is a tuple so immutable, which complicates adjusting it

        This function converts ParseResult into dict"""

        if pr.params:
            lgr.warning("ParseResults contains params %r, which will be ignored"
                        % (pr.params,))

        # can't use just pr._asdict since we care to ask those properties
        # such as .port , .hostname etc
        # Forcing '' instead of None since those properties (.hostname), .password,
        # .username return None if not available and we decided to uniformize
        return {f: (getattr(pr, f) or '') for f in cls._FIELDS}

    #
    # Access helpers
    #

    def _parse_qs(self, s, auto_delist=True):
        """Helper around parse_qs to strip unneeded 'list'ing etc and return a dict of key=values"""
        if not s:
            return {}
        out = OrderedDict(parse_qsl(s, 1))
        if not auto_delist:
            return out
        for k in out:
            v = out[k]
            if isinstance(v, list) and len(v) == 1:
                v = v[0]
                out[k] = None if v == '' else v
        return out

    @property
    def query_dict(self):
        return self._parse_qs(self.query)

    @property
    def fragment_dict(self):
        return self._parse_qs(self.fragment)


class PathRI(RI):
    """RI pointing to a (local) file/directory"""
    def as_str(self):
        return self.path

    @classmethod
    def _str_to_fields(cls, url_str):
        return dict(path=url_str)


class RegexBasedURLMixin(object):
    """Base class for URLs which we could simple parse using regular expressions"""

    _REGEX = None

    # not used ATM but possible ;)
    # @classmethod
    # def is_str_matches(cls, url_str):
    #     return bool(cls._REGEX.match(url_str))

    @classmethod
    def _str_to_fields(cls, url_str):
        re_match = cls._REGEX.match(url_str)
        if not re_match:
            # TODO: custom error?
            raise ValueError(
                "Possibly incorrectly determined string %r correspond to %s address"
                " -- it failed matching regex. Dunno how to handle. Contact developers"
                % (cls, url_str,)
            )
        fields = cls._get_blank_fields()
        fields.update({k: v for k, v in iteritems(re_match.groupdict()) if v})
        cls._normalize_fields(fields)
        return fields

    @classmethod
    def _normalize_fields(self, fields):
        """Helper to be ran if any of the fields need to be normalized after parsing"""
        pass


class SSHRI(RI, RegexBasedURLMixin):
    """RI pointing to a remote location reachable via SSH"""

    _FIELDS = RI._FIELDS + (
        'username',
        'hostname',
        'port',
    )

    _REGEX = re.compile(r'((?P<username>\S*)@)?(?P<hostname>[^:]+)(\:(?P<path>.*))?$')

    @classmethod
    def _normalize_fields(cls, fields):
        if fields['path'] and fields['path'].startswith('//'):
            # Let's normalize for now to avoid multiple leading slashes
            fields['path'] = '/' + fields['path'].lstrip('/')
        # escape path so we have direct representation of the path to work with
        fields['path'] = unescape_ssh_path(fields['path'])

    def as_str(self):
        fields = self.fields  # copy so we could escape symbols
        url_fmt = '{hostname}'
        if fields['username']:
            url_fmt = "{username}@" + url_fmt
        if fields['path']:
            url_fmt += ':{path}'
        fields['path'] = escape_ssh_path(fields['path'])
        return url_fmt.format(**fields)


class DataLadRI(RI, RegexBasedURLMixin):
    """RI pointing to datasets within central DataLad super-dataset"""

    _FIELDS = RI._FIELDS + (
        'remote',
    )

    # For now or forever we don't deal with any fragments or other special stuff
    _REGEX = re.compile(r'//(?P<remote>[^\s/]*)/(?P<path>.*)$')

    # do they need to be normalized??? loosing track ...

    def as_str(self):
        return "//{remote}/{path}".format(**self._fields)


def _split_colon(s, maxsplit=1):
    """Split on unescaped colon"""
    return re.compile(r'(?<!\\):').split(s, maxsplit=maxsplit)

# \ should be first to deal with
_SSH_ESCAPED_CHARACTERS = '\\#&;`|*?~<>^()[]{}$\'" '


# TODO: RF using re.sub
def escape_ssh_path(path):
    """Escape all special characters present in the path"""
    for c in _SSH_ESCAPED_CHARACTERS:
        if c in path:
            path = path.replace(c, '\\' + c)
    return path


def unescape_ssh_path(path):
    """Un-escape all special characters present in the path"""
    for c in _SSH_ESCAPED_CHARACTERS[::-1]:
        if c in path:
            path = path.replace('\\' + c, c)
    return path


def parse_url_opts(url):
    """Given a string with url-style query, split into content before # and options as dict"""
    url = URL(url)
    # we need to filter out query and fragment to get the base url
    fields = url.fields
    fields.pop('query')
    fields.pop('fragment')
    opts = url.query_dict
    return str(URL(**fields)), opts


# TODO: should we just define URL.good_for_git or smth like that? ;)
# although git also understands regular paths
def is_url(s):
    """Returns whether a string looks like something what datalad should treat as a URL

    This includes ssh "urls" which git understands.
    """
    try:
        ri = RI(s)
    except:
        return False
    return isinstance(ri, (URL, SSHRI))


# TODO: better name? additionally may be move to SSHRI.is_valid() or sth.
def is_ssh(ri):
    """helper to determine, whether `ri` requires an SSH connection

    Parameters
    ----------
    ri: str or RI

    Returns
    -------
    bool
    """

    # not exactly fitting the doc, but we actually can deal not necessarily with
    # string or RI only, but with everything RI itself can deal with:
    _ri = RI(ri) if not isinstance(ri, RI) else ri

    return isinstance(_ri, SSHRI) or \
           (isinstance(_ri, URL) and _ri.scheme == 'ssh')


#### windows workaround ###
# TODO: There should be a better way
def get_local_file_url(fname):
    """Return OS specific URL pointing to a local file

    Parameters
    ----------
    fname : string
        Filename.  If not absolute, abspath is used
    """
    fname = fname if isabs(fname) else abspath(fname)
    if on_windows:
        fname_rep = fname.replace('\\', '/')
        furl = "file:///%s" % urlquote(fname_rep)
        lgr.debug("Replaced '\\' in file\'s url: %s" % furl)
    else:
        # TODO:  need to fix for all the encoding etc
        furl = str(URL(scheme='file', path=fname))
    return furl


def get_local_path_from_url(url):
    """If given a file:// URL, returns a local path, if possible.

    Raises `ValueError` if not possible, for example, if the URL
    scheme is different, or if the `host` isn't empty or 'localhost'

    The returned path is always absolute.
    """
    urlparts = urlsplit(url)
    if not urlparts.scheme == 'file':
        raise ValueError(
            "Non 'file://' URL cannot be resolved to a local path")
    if not (urlparts.netloc in ('', 'localhost', '::1') \
            or urlparts.netloc.startswith('127.')):
        raise ValueError("file:// URL does not point to 'localhost'")
    return urlunquote(urlparts.path)

```
--- 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