{
    "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\"\"\"Module to help maintain a registry of versions for external modules etc\n\"\"\"\nimport sys\nfrom os import linesep\nfrom six import string_types\n\nfrom distutils.version import StrictVersion, LooseVersion\n\nfrom datalad.dochelpers import exc_str\nfrom datalad.log import lgr\n\n\n# To depict an unknown version, which can't be compared by mistake etc\nclass UnknownVersion:\n    \"\"\"For internal use\n    \"\"\"\n\n    def __str__(self):\n        return \"UNKNOWN\"\n\n    def __cmp__(self, other):\n        if other is self:\n            return 0\n        raise TypeError(\"UNKNOWN version is not comparable\")\n\n\n#\n# Custom handlers\n#\n\ndef _get_annex_version():\n    \"\"\"Return version of annex available\"\"\"\n    from datalad.cmd import Runner\n    return Runner().run('git annex version --raw'.split())[0]\n\n\nclass ExternalVersions(object):\n    \"\"\"Helper to figure out/use versions of the externals (modules, cmdline tools, etc).\n\n    It maintains a dictionary of `distuil.version.StrictVersion`s to make\n    comparisons easy.  If version string doesn't conform the StrictVersion\n    LooseVersion will be used.  If version can't be deduced for the external,\n    `UnknownVersion()` is assigned.  If external is not present (can't be\n    imported, or custom check throws exception), None is returned without\n    storing it, so later call will re-evaluate fully\n    \"\"\"\n\n    UNKNOWN = UnknownVersion()\n\n    CUSTOM = {\n        'annex': _get_annex_version\n    }\n\n    def __init__(self):\n        self._versions = {}\n\n    @classmethod\n    def _deduce_version(klass, module):\n        version = None\n        for attr in ('__version__', 'version'):\n            if hasattr(module, attr):\n                version = getattr(module, attr)\n                break\n\n        if isinstance(version, tuple) or isinstance(version, list):\n            #  Generate string representation\n            version = \".\".join(str(x) for x in version)\n\n        if version:\n            try:\n                return StrictVersion(version)\n            except ValueError:\n                # let's then go with Loose one\n                return LooseVersion(version)\n        else:\n            return klass.UNKNOWN\n\n    def __getitem__(self, module):\n        # when ran straight in its source code -- fails to discover nipy's version.. TODO\n        #if module == 'nipy':\n        #    import pdb; pdb.set_trace()\n        if not isinstance(module, string_types):\n            modname = module.__name__\n        else:\n            modname = module\n            module = None\n\n        # Early returns None so we do not store prev result for  them\n        # and allow users to install things at run time, so later check\n        # doesn't pick it up from the _versions\n        if modname not in self._versions:\n            version = None   # by default -- not present\n            if modname in self.CUSTOM:\n                try:\n                    version = self.CUSTOM[modname]()\n                except Exception as exc:\n                    lgr.debug(\"Failed to deduce version of %s due to %s\"\n                              % (modname, exc_str(exc)))\n                    return None\n            else:\n                if module is None:\n                    if modname not in sys.modules:\n                        try:\n                            module = __import__(modname)\n                        except ImportError:\n                            lgr.debug(\"Module %s seems to be not present\" % modname)\n                            return None\n                    else:\n                        module = sys.modules[modname]\n                if module:\n                    version = self._deduce_version(module)\n            self._versions[modname] = version\n\n        return self._versions.get(modname, self.UNKNOWN)\n\n    def keys(self):\n        \"\"\"Return names of the known modules\"\"\"\n        return self._versions.keys()\n\n    def __contains__(self, item):\n        return item in self._versions\n\n    @property\n    def versions(self):\n        \"\"\"Return dictionary (copy) of versions\"\"\"\n        return self._versions.copy()\n\n    def dumps(self, indent=False, preamble=\"Versions:\"):\n        \"\"\"Return listing of versions as a string\n\n        Parameters\n        ----------\n        indent: bool or str, optional\n          If set would instruct on how to indent entries (if just True, ' '\n          is used). Otherwise returned in a single line\n        preamble: str, optional\n          What preamble to the listing to use\n        \"\"\"\n        if indent and (indent is True):\n            indent = ' '\n        items = [\"%s=%s\" % (k, self._versions[k]) for k in sorted(self._versions)]\n        out = \"%s\" % preamble\n        if indent:\n            out += (linesep + indent).join([''] + items) + linesep\n        else:\n            out += \" \" + ' '.join(items)\n        return out\n\n\nexternal_versions = ExternalVersions()\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\"\"\"Module to help maintain a registry of versions for external modules etc\n\"\"\"\nimport sys\nfrom os import linesep\nfrom six import string_types\n\nfrom distutils.version import StrictVersion, LooseVersion\n\nfrom datalad.dochelpers import exc_str\nfrom datalad.log import lgr\n\n__all__ = ['UnknownVersion', 'ExternalVersions', 'external_versions']\n\n\n# To depict an unknown version, which can't be compared by mistake etc\nclass UnknownVersion:\n    \"\"\"For internal use\n    \"\"\"\n\n    def __str__(self):\n        return \"UNKNOWN\"\n\n    def __cmp__(self, other):\n        if other is self:\n            return 0\n        raise TypeError(\"UNKNOWN version is not comparable\")\n\n\n#\n# Custom handlers\n#\nfrom datalad.cmd import Runner\n_runner = Runner()\n\n\ndef _get_annex_version():\n    \"\"\"Return version of available git-annex\"\"\"\n    return _runner.run('git annex version --raw'.split())[0]\n\n\ndef _get_git_version():\n    \"\"\"Return version of available git\"\"\"\n    return _runner.run('git version'.split())[0].split()[-1]\n\n\nclass ExternalVersions(object):\n    \"\"\"Helper to figure out/use versions of the externals (modules, cmdline tools, etc).\n\n    To avoid collision between names of python modules and command line tools,\n    prepend names for command line tools with `cmd:`.\n\n    It maintains a dictionary of `distuil.version.StrictVersion`s to make\n    comparisons easy.  If version string doesn't conform the StrictVersion\n    LooseVersion will be used.  If version can't be deduced for the external,\n    `UnknownVersion()` is assigned.  If external is not present (can't be\n    imported, or custom check throws exception), None is returned without\n    storing it, so later call will re-evaluate fully.\n    \"\"\"\n\n    UNKNOWN = UnknownVersion()\n\n    CUSTOM = {\n        'cmd:annex': _get_annex_version,\n        'cmd:git': _get_git_version\n    }\n\n    def __init__(self):\n        self._versions = {}\n\n    @classmethod\n    def _deduce_version(klass, module):\n        version = None\n        for attr in ('__version__', 'version'):\n            if hasattr(module, attr):\n                version = getattr(module, attr)\n                break\n\n        if isinstance(version, tuple) or isinstance(version, list):\n            #  Generate string representation\n            version = \".\".join(str(x) for x in version)\n\n        if version:\n            try:\n                return StrictVersion(version)\n            except ValueError:\n                # let's then go with Loose one\n                return LooseVersion(version)\n        else:\n            return klass.UNKNOWN\n\n    def __getitem__(self, module):\n        # when ran straight in its source code -- fails to discover nipy's version.. TODO\n        #if module == 'nipy':\n        #    import pdb; pdb.set_trace()\n        if not isinstance(module, string_types):\n            modname = module.__name__\n        else:\n            modname = module\n            module = None\n\n        # Early returns None so we do not store prev result for  them\n        # and allow users to install things at run time, so later check\n        # doesn't pick it up from the _versions\n        if modname not in self._versions:\n            version = None   # by default -- not present\n            if modname in self.CUSTOM:\n                try:\n                    version = self.CUSTOM[modname]()\n                except Exception as exc:\n                    lgr.debug(\"Failed to deduce version of %s due to %s\"\n                              % (modname, exc_str(exc)))\n                    return None\n            else:\n                if module is None:\n                    if modname not in sys.modules:\n                        try:\n                            module = __import__(modname)\n                        except ImportError:\n                            lgr.debug(\"Module %s seems to be not present\" % modname)\n                            return None\n                    else:\n                        module = sys.modules[modname]\n                if module:\n                    version = self._deduce_version(module)\n            self._versions[modname] = version\n\n        return self._versions.get(modname, self.UNKNOWN)\n\n    def keys(self):\n        \"\"\"Return names of the known modules\"\"\"\n        return self._versions.keys()\n\n    def __contains__(self, item):\n        return item in self._versions\n\n    @property\n    def versions(self):\n        \"\"\"Return dictionary (copy) of versions\"\"\"\n        return self._versions.copy()\n\n    def dumps(self, indent=False, preamble=\"Versions:\"):\n        \"\"\"Return listing of versions as a string\n\n        Parameters\n        ----------\n        indent: bool or str, optional\n          If set would instruct on how to indent entries (if just True, ' '\n          is used). Otherwise returned in a single line\n        preamble: str, optional\n          What preamble to the listing to use\n        \"\"\"\n        if indent and (indent is True):\n            indent = ' '\n        items = [\"%s=%s\" % (k, self._versions[k]) for k in sorted(self._versions)]\n        out = \"%s\" % preamble\n        if indent:\n            out += (linesep + indent).join([''] + items) + linesep\n        else:\n            out += \" \" + ' '.join(items)\n        return out\n\n\nexternal_versions = ExternalVersions()\n",
            "header": {
                "file": {
                    "path": "datalad/support/external_versions.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "3c2d07c6d",
                "new_commit_hash": "562898493",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/datalad/support/external_versions.py"
            },
            "plus_file": {
                "path": "b/datalad/support/external_versions.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 17,
                            "length": 6
                        },
                        "new_range": {
                            "start": 17,
                            "length": 8
                        },
                        "section": "from distutils.version import StrictVersion, LooseVersion"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "from datalad.dochelpers import exc_str",
                                "type": "context"
                            },
                            {
                                "content": "from datalad.log import lgr",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "__all__ = ['UnknownVersion', 'ExternalVersions', 'external_versions']",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "# To depict an unknown version, which can't be compared by mistake etc",
                                "type": "context"
                            },
                            {
                                "content": "class UnknownVersion:",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "datalad/support/external_versions.py",
                            "type": "statement",
                            "name": "",
                            "content": "__all__ = ['UnknownVersion', 'ExternalVersions', 'external_versions']",
                            "ast_type_str": "Assign",
                            "start_lineno": 20,
                            "end_lineno": 20,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 35,
                            "length": 28
                        },
                        "new_range": {
                            "start": 37,
                            "length": 39
                        },
                        "section": "class UnknownVersion:"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "#",
                                "type": "context"
                            },
                            {
                                "content": "# Custom handlers",
                                "type": "context"
                            },
                            {
                                "content": "#",
                                "type": "context"
                            },
                            {
                                "content": "from datalad.cmd import Runner",
                                "type": "added"
                            },
                            {
                                "content": "_runner = Runner()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "def _get_annex_version():",
                                "type": "context"
                            },
                            {
                                "content": "    \"\"\"Return version of annex available\"\"\"",
                                "type": "deleted"
                            },
                            {
                                "content": "    from datalad.cmd import Runner",
                                "type": "deleted"
                            },
                            {
                                "content": "    return Runner().run('git annex version --raw'.split())[0]",
                                "type": "deleted"
                            },
                            {
                                "content": "    \"\"\"Return version of available git-annex\"\"\"",
                                "type": "added"
                            },
                            {
                                "content": "    return _runner.run('git annex version --raw'.split())[0]",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "def _get_git_version():",
                                "type": "added"
                            },
                            {
                                "content": "    \"\"\"Return version of available git\"\"\"",
                                "type": "added"
                            },
                            {
                                "content": "    return _runner.run('git version'.split())[0].split()[-1]",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class ExternalVersions(object):",
                                "type": "context"
                            },
                            {
                                "content": "    \"\"\"Helper to figure out/use versions of the externals (modules, cmdline tools, etc).",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    To avoid collision between names of python modules and command line tools,",
                                "type": "added"
                            },
                            {
                                "content": "    prepend names for command line tools with `cmd:`.",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    It maintains a dictionary of `distuil.version.StrictVersion`s to make",
                                "type": "context"
                            },
                            {
                                "content": "    comparisons easy.  If version string doesn't conform the StrictVersion",
                                "type": "context"
                            },
                            {
                                "content": "    LooseVersion will be used.  If version can't be deduced for the external,",
                                "type": "context"
                            },
                            {
                                "content": "    `UnknownVersion()` is assigned.  If external is not present (can't be",
                                "type": "context"
                            },
                            {
                                "content": "    imported, or custom check throws exception), None is returned without",
                                "type": "context"
                            },
                            {
                                "content": "    storing it, so later call will re-evaluate fully",
                                "type": "deleted"
                            },
                            {
                                "content": "    storing it, so later call will re-evaluate fully.",
                                "type": "added"
                            },
                            {
                                "content": "    \"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    UNKNOWN = UnknownVersion()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    CUSTOM = {",
                                "type": "context"
                            },
                            {
                                "content": "        'annex': _get_annex_version",
                                "type": "deleted"
                            },
                            {
                                "content": "        'cmd:annex': _get_annex_version,",
                                "type": "added"
                            },
                            {
                                "content": "        'cmd:git': _get_git_version",
                                "type": "added"
                            },
                            {
                                "content": "    }",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def __init__(self):",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "datalad/support/external_versions.py",
                            "type": "class",
                            "name": "ExternalVersions",
                            "content": "class ExternalVersions(object):\n    \"\"\"Helper to figure out/use versions of the externals (modules, cmdline tools, etc).\n\n    It maintains a dictionary of `distuil.version.StrictVersion`s to make\n    comparisons easy.  If version string doesn't conform the StrictVersion\n    LooseVersion will be used.  If version can't be deduced for the external,\n    `UnknownVersion()` is assigned.  If external is not present (can't be\n    imported, or custom check throws exception), None is returned without\n    storing it, so later call will re-evaluate fully\n    \"\"\"\n\n    UNKNOWN = UnknownVersion()\n\n    CUSTOM = {\n        'annex': _get_annex_version\n    }\n\n    def __init__(self):\n        self._versions = {}\n\n    @classmethod\n    def _deduce_version(klass, module):\n        version = None\n        for attr in ('__version__', 'version'):\n            if hasattr(module, attr):\n                version = getattr(module, attr)\n                break\n\n        if isinstance(version, tuple) or isinstance(version, list):\n            #  Generate string representation\n            version = \".\".join(str(x) for x in version)\n\n        if version:\n            try:\n                return StrictVersion(version)\n            except ValueError:\n                # let's then go with Loose one\n                return LooseVersion(version)\n        else:\n            return klass.UNKNOWN\n\n    def __getitem__(self, module):\n        # when ran straight in its source code -- fails to discover nipy's version.. TODO\n        #if module == 'nipy':\n        #    import pdb; pdb.set_trace()\n        if not isinstance(module, string_types):\n            modname = module.__name__\n        else:\n            modname = module\n            module = None\n\n        # Early returns None so we do not store prev result for  them\n        # and allow users to install things at run time, so later check\n        # doesn't pick it up from the _versions\n        if modname not in self._versions:\n            version = None   # by default -- not present\n            if modname in self.CUSTOM:\n                try:\n                    version = self.CUSTOM[modname]()\n                except Exception as exc:\n                    lgr.debug(\"Failed to deduce version of %s due to %s\"\n                              % (modname, exc_str(exc)))\n                    return None\n            else:\n                if module is None:\n                    if modname not in sys.modules:\n                        try:\n                            module = __import__(modname)\n                        except ImportError:\n                            lgr.debug(\"Module %s seems to be not present\" % modname)\n                            return None\n                    else:\n                        module = sys.modules[modname]\n                if module:\n                    version = self._deduce_version(module)\n            self._versions[modname] = version\n\n        return self._versions.get(modname, self.UNKNOWN)\n\n    def keys(self):\n        \"\"\"Return names of the known modules\"\"\"\n        return self._versions.keys()\n\n    def __contains__(self, item):\n        return item in self._versions\n\n    @property\n    def versions(self):\n        \"\"\"Return dictionary (copy) of versions\"\"\"\n        return self._versions.copy()\n\n    def dumps(self, indent=False, preamble=\"Versions:\"):\n        \"\"\"Return listing of versions as a string\n\n        Parameters\n        ----------\n        indent: bool or str, optional\n          If set would instruct on how to indent entries (if just True, ' '\n          is used). Otherwise returned in a single line\n        preamble: str, optional\n          What preamble to the listing to use\n        \"\"\"\n        if indent and (indent is True):\n            indent = ' '\n        items = [\"%s=%s\" % (k, self._versions[k]) for k in sorted(self._versions)]\n        out = \"%s\" % preamble\n        if indent:\n            out += (linesep + indent).join([''] + items) + linesep\n        else:\n            out += \" \" + ' '.join(items)\n        return out",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 45,
                            "end_lineno": 155,
                            "parent": null
                        },
                        {
                            "file_name": "datalad/support/external_versions.py",
                            "type": "function",
                            "name": "_get_annex_version",
                            "content": "def _get_annex_version():\n    \"\"\"Return version of annex available\"\"\"\n    from datalad.cmd import Runner\n    return Runner().run('git annex version --raw'.split())[0]",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 39,
                            "end_lineno": 42,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "datalad/support/external_versions.py",
                            "type": "function",
                            "name": "_get_git_version",
                            "content": "def _get_git_version():\n    \"\"\"Return version of available git\"\"\"\n    return _runner.run('git version'.split())[0].split()[-1]",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 49,
                            "end_lineno": 51,
                            "parent": null
                        },
                        {
                            "file_name": "datalad/support/external_versions.py",
                            "type": "statement",
                            "name": "",
                            "content": "from datalad.cmd import Runner",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 40,
                            "end_lineno": 40,
                            "parent": null
                        },
                        {
                            "file_name": "datalad/support/external_versions.py",
                            "type": "statement",
                            "name": "",
                            "content": "_runner = Runner()",
                            "ast_type_str": "Assign",
                            "start_lineno": 41,
                            "end_lineno": 41,
                            "parent": null
                        }
                    ],
                    "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\nfrom os import linesep\n\nfrom ...version import __version__\nfrom ..external_versions import ExternalVersions, StrictVersion\n\nfrom nose.tools import assert_true, assert_false\nfrom nose.tools import assert_equal, assert_greater_equal, assert_greater\nfrom nose.tools import assert_raises\nfrom nose import SkipTest\nfrom six import PY3\n\nif PY3:\n    # just to ease testing\n    def cmp(a, b):\n        return (a > b) - (a < b)\n\n\ndef test_external_versions_basic():\n    ev = ExternalVersions()\n    our_module = 'datalad'\n    assert_equal(ev.versions, {})\n    assert_equal(ev[our_module], __version__)\n    # and it could be compared\n    assert_greater_equal(ev[our_module], __version__)\n    assert_greater(ev[our_module], '0.1')\n    assert_equal(list(ev.keys()), [our_module])\n    assert_true(our_module in ev)\n    assert_false('unknown' in ev)\n\n    # StrictVersion might remove training .0\n    version_str = str(ev[our_module]) \\\n        if isinstance(ev[our_module], StrictVersion) \\\n        else __version__\n    assert_equal(ev.dumps(), \"Versions: %s=%s\" % (our_module, version_str))\n\n    # For non-existing one we get None\n    assert_equal(ev['custom__nonexisting'], None)\n    # and nothing gets added to _versions for nonexisting\n    assert_equal(set(ev.versions.keys()), {our_module})\n\n    # but if it is a module without version, we get it set to UNKNOWN\n    assert_equal(ev['os'], ev.UNKNOWN)\n    # And get a record on that inside\n    assert_equal(ev.versions.get('os'), ev.UNKNOWN)\n    # And that thing is \"True\", i.e. present\n    assert(ev['os'])\n    # but not comparable with anything besides itself (was above)\n    assert_raises(TypeError, cmp, ev['os'], '0')\n    assert_raises(TypeError, assert_greater, ev['os'], '0')\n\n    return\n    # Code below is from original duecredit, and we don't care about\n    # testing this one\n    # And we can get versions based on modules themselves\n    from datalad.tests import mod\n    assert_equal(ev[mod], mod.__version__)\n\n    # Check that we can get a copy of the versions\n    versions_dict = ev.versions\n    versions_dict[our_module] = \"0.0.1\"\n    assert_equal(versions_dict[our_module], \"0.0.1\")\n    assert_equal(ev[our_module], __version__)\n\n\ndef test_external_versions_unknown():\n    assert_equal(str(ExternalVersions.UNKNOWN), 'UNKNOWN')\n\n\ndef _test_external(ev, modname):\n    try:\n        exec (\"import %s\" % modname, globals(), locals())\n    except ImportError:\n        raise SkipTest(\"External %s not present\" % modname)\n    except Exception as e:\n        raise SkipTest(\"External %s fails to import: %s\" % (modname, e))\n    assert (ev[modname] is not ev.UNKNOWN)\n    assert_greater(ev[modname], '0.0.1')\n    assert_greater('1000000.0', ev[modname])  # unlikely in our lifetimes\n\n\ndef test_external_versions_popular_packages():\n    ev = ExternalVersions()\n\n    for modname in ('scipy', 'numpy', 'mvpa2', 'sklearn', 'statsmodels', 'pandas',\n                    'matplotlib', 'psychopy'):\n        yield _test_external, ev, modname\n\n    # more of a smoke test\n    assert_false(linesep in ev.dumps())\n    assert_true(ev.dumps(indent=True).endswith(linesep))\n\n\ndef test_custom_versions():\n    ev = ExternalVersions()\n    assert(ev['annex'] > '6.20160101')  # annex must be present and recentish\n    assert_equal(set(ev.versions.keys()), {'annex'})\n\n    ev.CUSTOM = {'bogus': lambda: 1/0}\n    assert_equal(ev['bogus'], None)\n    assert_equal(set(ev.versions.keys()), {'annex'})",
            "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\nfrom os import linesep\n\nfrom ...version import __version__\nfrom ..external_versions import ExternalVersions, StrictVersion\n\nfrom nose.tools import assert_true, assert_false\nfrom nose.tools import assert_equal, assert_greater_equal, assert_greater\nfrom nose.tools import assert_raises\nfrom nose import SkipTest\nfrom six import PY3\n\nif PY3:\n    # just to ease testing\n    def cmp(a, b):\n        return (a > b) - (a < b)\n\n\ndef test_external_versions_basic():\n    ev = ExternalVersions()\n    our_module = 'datalad'\n    assert_equal(ev.versions, {})\n    assert_equal(ev[our_module], __version__)\n    # and it could be compared\n    assert_greater_equal(ev[our_module], __version__)\n    assert_greater(ev[our_module], '0.1')\n    assert_equal(list(ev.keys()), [our_module])\n    assert_true(our_module in ev)\n    assert_false('unknown' in ev)\n\n    # StrictVersion might remove training .0\n    version_str = str(ev[our_module]) \\\n        if isinstance(ev[our_module], StrictVersion) \\\n        else __version__\n    assert_equal(ev.dumps(), \"Versions: %s=%s\" % (our_module, version_str))\n\n    # For non-existing one we get None\n    assert_equal(ev['custom__nonexisting'], None)\n    # and nothing gets added to _versions for nonexisting\n    assert_equal(set(ev.versions.keys()), {our_module})\n\n    # but if it is a module without version, we get it set to UNKNOWN\n    assert_equal(ev['os'], ev.UNKNOWN)\n    # And get a record on that inside\n    assert_equal(ev.versions.get('os'), ev.UNKNOWN)\n    # And that thing is \"True\", i.e. present\n    assert(ev['os'])\n    # but not comparable with anything besides itself (was above)\n    assert_raises(TypeError, cmp, ev['os'], '0')\n    assert_raises(TypeError, assert_greater, ev['os'], '0')\n\n    return\n    # Code below is from original duecredit, and we don't care about\n    # testing this one\n    # And we can get versions based on modules themselves\n    from datalad.tests import mod\n    assert_equal(ev[mod], mod.__version__)\n\n    # Check that we can get a copy of the versions\n    versions_dict = ev.versions\n    versions_dict[our_module] = \"0.0.1\"\n    assert_equal(versions_dict[our_module], \"0.0.1\")\n    assert_equal(ev[our_module], __version__)\n\n\ndef test_external_versions_unknown():\n    assert_equal(str(ExternalVersions.UNKNOWN), 'UNKNOWN')\n\n\ndef _test_external(ev, modname):\n    try:\n        exec (\"import %s\" % modname, globals(), locals())\n    except ImportError:\n        raise SkipTest(\"External %s not present\" % modname)\n    except Exception as e:\n        raise SkipTest(\"External %s fails to import: %s\" % (modname, e))\n    assert (ev[modname] is not ev.UNKNOWN)\n    assert_greater(ev[modname], '0.0.1')\n    assert_greater('1000000.0', ev[modname])  # unlikely in our lifetimes\n\n\ndef test_external_versions_popular_packages():\n    ev = ExternalVersions()\n\n    for modname in ('scipy', 'numpy', 'mvpa2', 'sklearn', 'statsmodels', 'pandas',\n                    'matplotlib', 'psychopy'):\n        yield _test_external, ev, modname\n\n    # more of a smoke test\n    assert_false(linesep in ev.dumps())\n    assert_true(ev.dumps(indent=True).endswith(linesep))\n\n\ndef test_custom_versions():\n    ev = ExternalVersions()\n    assert(ev['cmd:annex'] > '6.20160101')  # annex must be present and recentish\n    assert_equal(set(ev.versions.keys()), {'cmd:annex'})\n    assert(ev['cmd:git'] > '2')  # git must be present and recentish\n    assert_equal(set(ev.versions.keys()), {'cmd:annex', 'cmd:git'})\n\n    ev.CUSTOM = {'bogus': lambda: 1/0}\n    assert_equal(ev['bogus'], None)\n    assert_equal(set(ev.versions.keys()), {'cmd:annex', 'cmd:git'})",
            "header": {
                "file": {
                    "path": "datalad/support/tests/test_external_versions.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "41cb21fc8",
                "new_commit_hash": "e64364138",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/datalad/support/tests/test_external_versions.py"
            },
            "plus_file": {
                "path": "b/datalad/support/tests/test_external_versions.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 101,
                            "length": 9
                        },
                        "new_range": {
                            "start": 101,
                            "length": 11
                        },
                        "section": "def test_external_versions_popular_packages():"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "def test_custom_versions():",
                                "type": "context"
                            },
                            {
                                "content": "    ev = ExternalVersions()",
                                "type": "context"
                            },
                            {
                                "content": "    assert(ev['annex'] > '6.20160101')  # annex must be present and recentish",
                                "type": "deleted"
                            },
                            {
                                "content": "    assert_equal(set(ev.versions.keys()), {'annex'})",
                                "type": "deleted"
                            },
                            {
                                "content": "    assert(ev['cmd:annex'] > '6.20160101')  # annex must be present and recentish",
                                "type": "added"
                            },
                            {
                                "content": "    assert_equal(set(ev.versions.keys()), {'cmd:annex'})",
                                "type": "added"
                            },
                            {
                                "content": "    assert(ev['cmd:git'] > '2')  # git must be present and recentish",
                                "type": "added"
                            },
                            {
                                "content": "    assert_equal(set(ev.versions.keys()), {'cmd:annex', 'cmd:git'})",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    ev.CUSTOM = {'bogus': lambda: 1/0}",
                                "type": "context"
                            },
                            {
                                "content": "    assert_equal(ev['bogus'], None)",
                                "type": "context"
                            },
                            {
                                "content": "    assert_equal(set(ev.versions.keys()), {'annex'})",
                                "type": "deleted"
                            },
                            {
                                "content": "No newline at end of file",
                                "type": "note"
                            },
                            {
                                "content": "    assert_equal(set(ev.versions.keys()), {'cmd:annex', 'cmd:git'})",
                                "type": "added"
                            },
                            {
                                "content": "No newline at end of file",
                                "type": "note"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "datalad/support/tests/test_external_versions.py",
                            "type": "function",
                            "name": "test_custom_versions",
                            "content": "def test_custom_versions():\n    ev = ExternalVersions()\n    assert(ev['annex'] > '6.20160101')  # annex must be present and recentish\n    assert_equal(set(ev.versions.keys()), {'annex'})\n\n    ev.CUSTOM = {'bogus': lambda: 1/0}\n    assert_equal(ev['bogus'], None)\n    assert_equal(set(ev.versions.keys()), {'annex'})",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 102,
                            "end_lineno": 109,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "27bfd015eb7de221ea9b6090f6fb7c8450848891^",
    "new_commit_hash": "27bfd015eb7de221ea9b6090f6fb7c8450848891",
    "commit_message": "RF: versions -- prepend names for cmdline tools with cmd: to avoid collisions with python modules",
    "commit_date": "2016-07-11T11:01:51-04:00",
    "metadata": {}
}
{
    "repo_name": "datalad",
    "new_commit_hash": "27bfd015eb7de221ea9b6090f6fb7c8450848891",
    "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\nfrom os import linesep\n\nfrom datalad.version import __version__\nfrom datalad.support.external_versions import ExternalVersions, StrictVersion\n\nfrom nose.tools import assert_true, assert_false\nfrom nose.tools import assert_equal, assert_greater_equal, assert_greater\nfrom nose.tools import assert_raises\nfrom nose import SkipTest\nfrom six import PY3\n\nif PY3:\n    # just to ease testing\n    def cmp(a, b):\n        return (a > b) - (a < b)\n\n\ndef test_external_versions_basic():\n    ev = ExternalVersions()\n    our_module = 'datalad'\n    assert_equal(ev.versions, {})\n    assert_equal(ev[our_module], __version__)\n    # and it could be compared\n    assert_greater_equal(ev[our_module], __version__)\n    assert_greater(ev[our_module], '0.1')\n    assert_equal(list(ev.keys()), [our_module])\n    assert_true(our_module in ev)\n    assert_false('unknown' in ev)\n\n    # StrictVersion might remove training .0\n    version_str = str(ev[our_module]) \\\n        if isinstance(ev[our_module], StrictVersion) \\\n        else __version__\n    assert_equal(ev.dumps(), \"Versions: %s=%s\" % (our_module, version_str))\n\n    # For non-existing one we get None\n    assert_equal(ev['custom__nonexisting'], None)\n    # and nothing gets added to _versions for nonexisting\n    assert_equal(set(ev.versions.keys()), {our_module})\n\n    # but if it is a module without version, we get it set to UNKNOWN\n    assert_equal(ev['os'], ev.UNKNOWN)\n    # And get a record on that inside\n    assert_equal(ev.versions.get('os'), ev.UNKNOWN)\n    # And that thing is \"True\", i.e. present\n    assert(ev['os'])\n    # but not comparable with anything besides itself (was above)\n    assert_raises(TypeError, cmp, ev['os'], '0')\n    assert_raises(TypeError, assert_greater, ev['os'], '0')\n\n    return\n    # Code below is from original duecredit, and we don't care about\n    # testing this one\n    # And we can get versions based on modules themselves\n    from datalad.tests import mod\n    assert_equal(ev[mod], mod.__version__)\n\n    # Check that we can get a copy of the versions\n    versions_dict = ev.versions\n    versions_dict[our_module] = \"0.0.1\"\n    assert_equal(versions_dict[our_module], \"0.0.1\")\n    assert_equal(ev[our_module], __version__)\n\n\ndef test_external_versions_unknown():\n    assert_equal(str(ExternalVersions.UNKNOWN), 'UNKNOWN')\n\n\ndef _test_external(ev, modname):\n    try:\n        exec (\"import %s\" % modname, globals(), locals())\n    except ImportError:\n        raise SkipTest(\"External %s not present\" % modname)\n    except Exception as e:\n        raise SkipTest(\"External %s fails to import: %s\" % (modname, e))\n    assert (ev[modname] is not ev.UNKNOWN)\n    assert_greater(ev[modname], '0.0.1')\n    assert_greater('1000000.0', ev[modname])  # unlikely in our lifetimes\n\n\ndef test_external_versions_popular_packages():\n    ev = ExternalVersions()\n\n    for modname in ('scipy', 'numpy', 'mvpa2', 'sklearn', 'statsmodels', 'pandas',\n                    'matplotlib', 'psychopy'):\n        yield _test_external, ev, modname\n\n    # more of a smoke test\n    assert_false(linesep in ev.dumps())\n    assert_true(ev.dumps(indent=True).endswith(linesep))\n\n\ndef test_custom_versions():\n    ev = ExternalVersions()\n    assert(ev['cmd:annex'] > '6.20160101')  # annex must be present and recentish\n    assert_equal(set(ev.versions.keys()), {'cmd:annex'})\n    assert(ev['cmd:git'] > '2')  # git must be present and recentish\n    assert_equal(set(ev.versions.keys()), {'cmd:annex', 'cmd:git'})\n\n    ev.CUSTOM = {'bogus': lambda: 1/0}\n    assert_equal(ev['bogus'], None)\n    assert_equal(set(ev.versions.keys()), {'cmd:annex', 'cmd:git'})",
        "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.3\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 82ms\nInstalled 25 packages in 4.56s\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/.tmp1OaZok/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/.tmp1OaZok/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/.tmp1OaZok/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/.tmp1OaZok/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/.tmp1OaZok/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/.tmp3AzOat/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/.tmp3AzOat/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/.tmp3AzOat/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/.tmp3AzOat/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/.tmp3AzOat/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_27bfd015eb7de221ea9b6090f6fb7c8450848891/datalad/__init__.py\", line 20, in <module>\n    from .config import ConfigManager\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_27bfd015eb7de221ea9b6090f6fb7c8450848891/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 374ms\nInstalled 26 packages in 6.27s\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 68 packages in 3.24s\nPrepared 1 package in 1.92s\nInstalled 62 packages in 55ms\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.3 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_27bfd015eb7de221ea9b6090f6fb7c8450848891)\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 + iso8601==2.1.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_27bfd015eb7de221ea9b6090f6fb7c8450848891/.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": 0,
    "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_27bfd015eb7de221ea9b6090f6fb7c8450848891\nplugins: cov-4.1.0\ncollected 4 items\n\nr2e_tests/test_1.py ..x.                                                 [100%]\n\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::test_external_versions_basic\nPASSED r2e_tests/test_1.py::test_external_versions_unknown\nPASSED r2e_tests/test_1.py::test_custom_versions\nXFAIL r2e_tests/test_1.py::test_external_versions_popular_packages - reason: [NOTRUN] yield tests were removed in pytest 4.0 - test_external_versions_popular_packages will be ignored\n========================= 3 passed, 1 xfailed in 0.75s =========================\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_27bfd015eb7de221ea9b6090f6fb7c8450848891\nplugins: cov-4.1.0\ncollected 4 items\n\nr2e_tests/test_1.py ..xF                                                 [100%]\n\n=================================== FAILURES ===================================\n_____________________________ test_custom_versions _____________________________\n\n    def test_custom_versions():\n        ev = ExternalVersions()\n>       assert(ev['cmd:annex'] > '6.20160101')  # annex must be present and recentish\nE       TypeError: '>' not supported between instances of 'NoneType' and 'str'\n\nr2e_tests/test_1.py:104: TypeError\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::test_external_versions_basic\nPASSED r2e_tests/test_1.py::test_external_versions_unknown\nXFAIL r2e_tests/test_1.py::test_external_versions_popular_packages - reason: [NOTRUN] yield tests were removed in pytest 4.0 - test_external_versions_popular_packages will be ignored\nFAILED r2e_tests/test_1.py::test_custom_versions - TypeError: '>' not support...\n==================== 1 failed, 2 passed, 1 xfailed in 0.56s ====================\n",
    "old_commit_res_stderr": ""
}
datalad/support/external_versions.py datalad/support/tests/test_external_versions.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Version Retrieval Fails Due to Name Collision Between Command-Line Tools and Python Modules

**Description:**
When attempting to retrieve the version of command-line tools, a name collision with Python modules causes the retrieval to fail, resulting in unexpected behavior.

**Example Buggy Code:**
```python
from datalad.support.external_versions import ExternalVersions

ev = ExternalVersions()
annex_version = ev['annex']  # Expected to retrieve git-annex version
print(annex_version > '6.20160101')
```

**Expected Behavior:**
The `ev['annex']` should successfully return the version string of the `git-annex` command-line tool, allowing for proper comparison with the expected version.

**Actual Behavior:**
Due to a naming collision with a Python module named `annex`, `ev['annex']` returns `None`. This leads to a `TypeError` when attempting to compare `None` with a string:
```
TypeError: '>' not supported between instances of 'NoneType' and 'str'
```
[/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/external_versions.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.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""Module to help maintain a registry of versions for external modules etc
"""
import sys
from os import linesep
from six import string_types

from distutils.version import StrictVersion, LooseVersion

from datalad.dochelpers import exc_str
from datalad.log import lgr


# To depict an unknown version, which can't be compared by mistake etc
class UnknownVersion:
    """For internal use
    """

    def __str__(self):
        return "UNKNOWN"

    def __cmp__(self, other):
        if other is self:
            return 0
        raise TypeError("UNKNOWN version is not comparable")


#
# Custom handlers
#

def _get_annex_version():
    """Return version of annex available"""
    from datalad.cmd import Runner
    return Runner().run('git annex version --raw'.split())[0]


class ExternalVersions(object):
    """Helper to figure out/use versions of the externals (modules, cmdline tools, etc).

    It maintains a dictionary of `distuil.version.StrictVersion`s to make
    comparisons easy.  If version string doesn't conform the StrictVersion
    LooseVersion will be used.  If version can't be deduced for the external,
    `UnknownVersion()` is assigned.  If external is not present (can't be
    imported, or custom check throws exception), None is returned without
    storing it, so later call will re-evaluate fully
    """

    UNKNOWN = UnknownVersion()

    CUSTOM = {
        'annex': _get_annex_version
    }

    def __init__(self):
        self._versions = {}

    @classmethod
    def _deduce_version(klass, module):
        version = None
        for attr in ('__version__', 'version'):
            if hasattr(module, attr):
                version = getattr(module, attr)
                break

        if isinstance(version, tuple) or isinstance(version, list):
            #  Generate string representation
            version = ".".join(str(x) for x in version)

        if version:
            try:
                return StrictVersion(version)
            except ValueError:
                # let's then go with Loose one
                return LooseVersion(version)
        else:
            return klass.UNKNOWN

    def __getitem__(self, module):
        # when ran straight in its source code -- fails to discover nipy's version.. TODO
        #if module == 'nipy':
        #    import pdb; pdb.set_trace()
        if not isinstance(module, string_types):
            modname = module.__name__
        else:
            modname = module
            module = None

        # Early returns None so we do not store prev result for  them
        # and allow users to install things at run time, so later check
        # doesn't pick it up from the _versions
        if modname not in self._versions:
            version = None   # by default -- not present
            if modname in self.CUSTOM:
                try:
                    version = self.CUSTOM[modname]()
                except Exception as exc:
                    lgr.debug("Failed to deduce version of %s due to %s"
                              % (modname, exc_str(exc)))
                    return None
            else:
                if module is None:
                    if modname not in sys.modules:
                        try:
                            module = __import__(modname)
                        except ImportError:
                            lgr.debug("Module %s seems to be not present" % modname)
                            return None
                    else:
                        module = sys.modules[modname]
                if module:
                    version = self._deduce_version(module)
            self._versions[modname] = version

        return self._versions.get(modname, self.UNKNOWN)

    def keys(self):
        """Return names of the known modules"""
        return self._versions.keys()

    def __contains__(self, item):
        return item in self._versions

    @property
    def versions(self):
        """Return dictionary (copy) of versions"""
        return self._versions.copy()

    def dumps(self, indent=False, preamble="Versions:"):
        """Return listing of versions as a string

        Parameters
        ----------
        indent: bool or str, optional
          If set would instruct on how to indent entries (if just True, ' '
          is used). Otherwise returned in a single line
        preamble: str, optional
          What preamble to the listing to use
        """
        if indent and (indent is True):
            indent = ' '
        items = ["%s=%s" % (k, self._versions[k]) for k in sorted(self._versions)]
        out = "%s" % preamble
        if indent:
            out += (linesep + indent).join([''] + items) + linesep
        else:
            out += " " + ' '.join(items)
        return out


external_versions = ExternalVersions()

```
--- 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:** Version Retrieval Fails Due to Name Collision Between Command-Line Tools and Python Modules

**Description:**
When attempting to retrieve the version of command-line tools, a name collision with Python modules causes the retrieval to fail, resulting in unexpected behavior.

**Example Buggy Code:**
```python
from datalad.support.external_versions import ExternalVersions

ev = ExternalVersions()
annex_version = ev['annex']  # Expected to retrieve git-annex version
print(annex_version > '6.20160101')
```

**Expected Behavior:**
The `ev['annex']` should successfully return the version string of the `git-annex` command-line tool, allowing for proper comparison with the expected version.

**Actual Behavior:**
Due to a naming collision with a Python module named `annex`, `ev['annex']` returns `None`. This leads to a `TypeError` when attempting to compare `None` with a string:
```
TypeError: '>' not supported between instances of 'NoneType' and 'str'
```
[/ISSUE]
{
    "test_external_versions_basic": "PASSED",
    "test_external_versions_unknown": "PASSED",
    "test_custom_versions": "PASSED"
}
diff --git a/datalad/support/external_versions.py b/datalad/support/external_versions.py
index 3c2d07c6d..562898493 100644
--- a/datalad/support/external_versions.py
+++ b/datalad/support/external_versions.py
@@ -17,6 +17,8 @@ from distutils.version import StrictVersion, LooseVersion
 from datalad.dochelpers import exc_str
 from datalad.log import lgr
 
+__all__ = ['UnknownVersion', 'ExternalVersions', 'external_versions']
+
 
 # To depict an unknown version, which can't be compared by mistake etc
 class UnknownVersion:
@@ -35,28 +37,39 @@ class UnknownVersion:
 #
 # Custom handlers
 #
+from datalad.cmd import Runner
+_runner = Runner()
+
 
 def _get_annex_version():
-    """Return version of annex available"""
-    from datalad.cmd import Runner
-    return Runner().run('git annex version --raw'.split())[0]
+    """Return version of available git-annex"""
+    return _runner.run('git annex version --raw'.split())[0]
+
+
+def _get_git_version():
+    """Return version of available git"""
+    return _runner.run('git version'.split())[0].split()[-1]
 
 
 class ExternalVersions(object):
     """Helper to figure out/use versions of the externals (modules, cmdline tools, etc).
 
+    To avoid collision between names of python modules and command line tools,
+    prepend names for command line tools with `cmd:`.
+
     It maintains a dictionary of `distuil.version.StrictVersion`s to make
     comparisons easy.  If version string doesn't conform the StrictVersion
     LooseVersion will be used.  If version can't be deduced for the external,
     `UnknownVersion()` is assigned.  If external is not present (can't be
     imported, or custom check throws exception), None is returned without
-    storing it, so later call will re-evaluate fully
+    storing it, so later call will re-evaluate fully.
     """
 
     UNKNOWN = UnknownVersion()
 
     CUSTOM = {
-        'annex': _get_annex_version
+        'cmd:annex': _get_annex_version,
+        'cmd:git': _get_git_version
     }
 
     def __init__(self):

{"datalad/support/external_versions.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\"\"\"Module to help maintain a registry of versions for external modules etc\n\"\"\"\nimport sys\nfrom os import linesep\nfrom six import string_types\n\nfrom distutils.version import StrictVersion, LooseVersion\n\nfrom datalad.dochelpers import exc_str\nfrom datalad.log import lgr\n\n\n# To depict an unknown version, which can't be compared by mistake etc\nclass UnknownVersion:\n    \"\"\"For internal use\n    \"\"\"\n\n    def __str__(self):\n        return \"UNKNOWN\"\n\n    def __cmp__(self, other):\n        if other is self:\n            return 0\n        raise TypeError(\"UNKNOWN version is not comparable\")\n\n\n#\n# Custom handlers\n#\n\ndef _get_annex_version():\n    \"\"\"Return version of annex available\"\"\"\n    from datalad.cmd import Runner\n    return Runner().run('git annex version --raw'.split())[0]\n\n\nclass ExternalVersions(object):\n    \"\"\"Helper to figure out/use versions of the externals (modules, cmdline tools, etc).\n\n    It maintains a dictionary of `distuil.version.StrictVersion`s to make\n    comparisons easy.  If version string doesn't conform the StrictVersion\n    LooseVersion will be used.  If version can't be deduced for the external,\n    `UnknownVersion()` is assigned.  If external is not present (can't be\n    imported, or custom check throws exception), None is returned without\n    storing it, so later call will re-evaluate fully\n    \"\"\"\n\n    UNKNOWN = UnknownVersion()\n\n    CUSTOM = {\n        'annex': _get_annex_version\n    }\n\n    def __init__(self):\n        self._versions = {}\n\n    @classmethod\n    def _deduce_version(klass, module):\n        version = None\n        for attr in ('__version__', 'version'):\n            if hasattr(module, attr):\n                version = getattr(module, attr)\n                break\n\n        if isinstance(version, tuple) or isinstance(version, list):\n            #  Generate string representation\n            version = \".\".join(str(x) for x in version)\n\n        if version:\n            try:\n                return StrictVersion(version)\n            except ValueError:\n                # let's then go with Loose one\n                return LooseVersion(version)\n        else:\n            return klass.UNKNOWN\n\n    def __getitem__(self, module):\n        # when ran straight in its source code -- fails to discover nipy's version.. TODO\n        #if module == 'nipy':\n        #    import pdb; pdb.set_trace()\n        if not isinstance(module, string_types):\n            modname = module.__name__\n        else:\n            modname = module\n            module = None\n\n        # Early returns None so we do not store prev result for  them\n        # and allow users to install things at run time, so later check\n        # doesn't pick it up from the _versions\n        if modname not in self._versions:\n            version = None   # by default -- not present\n            if modname in self.CUSTOM:\n                try:\n                    version = self.CUSTOM[modname]()\n                except Exception as exc:\n                    lgr.debug(\"Failed to deduce version of %s due to %s\"\n                              % (modname, exc_str(exc)))\n                    return None\n            else:\n                if module is None:\n                    if modname not in sys.modules:\n                        try:\n                            module = __import__(modname)\n                        except ImportError:\n                            lgr.debug(\"Module %s seems to be not present\" % modname)\n                            return None\n                    else:\n                        module = sys.modules[modname]\n                if module:\n                    version = self._deduce_version(module)\n            self._versions[modname] = version\n\n        return self._versions.get(modname, self.UNKNOWN)\n\n    def keys(self):\n        \"\"\"Return names of the known modules\"\"\"\n        return self._versions.keys()\n\n    def __contains__(self, item):\n        return item in self._versions\n\n    @property\n    def versions(self):\n        \"\"\"Return dictionary (copy) of versions\"\"\"\n        return self._versions.copy()\n\n    def dumps(self, indent=False, preamble=\"Versions:\"):\n        \"\"\"Return listing of versions as a string\n\n        Parameters\n        ----------\n        indent: bool or str, optional\n          If set would instruct on how to indent entries (if just True, ' '\n          is used). Otherwise returned in a single line\n        preamble: str, optional\n          What preamble to the listing to use\n        \"\"\"\n        if indent and (indent is True):\n            indent = ' '\n        items = [\"%s=%s\" % (k, self._versions[k]) for k in sorted(self._versions)]\n        out = \"%s\" % preamble\n        if indent:\n            out += (linesep + indent).join([''] + items) + linesep\n        else:\n            out += \" \" + ' '.join(items)\n        return out\n\n\nexternal_versions = ExternalVersions()\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:** Version Retrieval Fails Due to Name Collision Between Command-Line Tools and Python Modules

**Description:**
When attempting to retrieve the version of command-line tools, a name collision with Python modules causes the retrieval to fail, resulting in unexpected behavior.

**Example Buggy Code:**
```python
from datalad.support.external_versions import ExternalVersions

ev = ExternalVersions()
annex_version = ev['annex']  # Expected to retrieve git-annex version
print(annex_version > '6.20160101')
```

**Expected Behavior:**
The `ev['annex']` should successfully return the version string of the `git-annex` command-line tool, allowing for proper comparison with the expected version.

**Actual Behavior:**
Due to a naming collision with a Python module named `annex`, `ev['annex']` returns `None`. This leads to a `TypeError` when attempting to compare `None` with a string:
```
TypeError: '>' not supported between instances of 'NoneType' and 'str'
```
[/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/external_versions.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.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""Module to help maintain a registry of versions for external modules etc
"""
import sys
from os import linesep
from six import string_types

from distutils.version import StrictVersion, LooseVersion

from datalad.dochelpers import exc_str
from datalad.log import lgr


# To depict an unknown version, which can't be compared by mistake etc
class UnknownVersion:
    """For internal use
    """

    def __str__(self):
        return "UNKNOWN"

    def __cmp__(self, other):
        if other is self:
            return 0
        raise TypeError("UNKNOWN version is not comparable")


#
# Custom handlers
#

def _get_annex_version():
    """Return version of annex available"""
    from datalad.cmd import Runner
    return Runner().run('git annex version --raw'.split())[0]


class ExternalVersions(object):
    """Helper to figure out/use versions of the externals (modules, cmdline tools, etc).

    It maintains a dictionary of `distuil.version.StrictVersion`s to make
    comparisons easy.  If version string doesn't conform the StrictVersion
    LooseVersion will be used.  If version can't be deduced for the external,
    `UnknownVersion()` is assigned.  If external is not present (can't be
    imported, or custom check throws exception), None is returned without
    storing it, so later call will re-evaluate fully
    """

    UNKNOWN = UnknownVersion()

    CUSTOM = {
        'annex': _get_annex_version
    }

    def __init__(self):
        self._versions = {}

    @classmethod
    def _deduce_version(klass, module):
        version = None
        for attr in ('__version__', 'version'):
            if hasattr(module, attr):
                version = getattr(module, attr)
                break

        if isinstance(version, tuple) or isinstance(version, list):
            #  Generate string representation
            version = ".".join(str(x) for x in version)

        if version:
            try:
                return StrictVersion(version)
            except ValueError:
                # let's then go with Loose one
                return LooseVersion(version)
        else:
            return klass.UNKNOWN

    def __getitem__(self, module):
        # when ran straight in its source code -- fails to discover nipy's version.. TODO
        #if module == 'nipy':
        #    import pdb; pdb.set_trace()
        if not isinstance(module, string_types):
            modname = module.__name__
        else:
            modname = module
            module = None

        # Early returns None so we do not store prev result for  them
        # and allow users to install things at run time, so later check
        # doesn't pick it up from the _versions
        if modname not in self._versions:
            version = None   # by default -- not present
            if modname in self.CUSTOM:
                try:
                    version = self.CUSTOM[modname]()
                except Exception as exc:
                    lgr.debug("Failed to deduce version of %s due to %s"
                              % (modname, exc_str(exc)))
                    return None
            else:
                if module is None:
                    if modname not in sys.modules:
                        try:
                            module = __import__(modname)
                        except ImportError:
                            lgr.debug("Module %s seems to be not present" % modname)
                            return None
                    else:
                        module = sys.modules[modname]
                if module:
                    version = self._deduce_version(module)
            self._versions[modname] = version

        return self._versions.get(modname, self.UNKNOWN)

    def keys(self):
        """Return names of the known modules"""
        return self._versions.keys()

    def __contains__(self, item):
        return item in self._versions

    @property
    def versions(self):
        """Return dictionary (copy) of versions"""
        return self._versions.copy()

    def dumps(self, indent=False, preamble="Versions:"):
        """Return listing of versions as a string

        Parameters
        ----------
        indent: bool or str, optional
          If set would instruct on how to indent entries (if just True, ' '
          is used). Otherwise returned in a single line
        preamble: str, optional
          What preamble to the listing to use
        """
        if indent and (indent is True):
            indent = ' '
        items = ["%s=%s" % (k, self._versions[k]) for k in sorted(self._versions)]
        out = "%s" % preamble
        if indent:
            out += (linesep + indent).join([''] + items) + linesep
        else:
            out += " " + ' '.join(items)
        return out


external_versions = ExternalVersions()

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