{
    "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\"\"\"Test interface.utils\n\n\"\"\"\n\nfrom datalad.tests.utils import known_failure_direct_mode\n\nimport os\nimport logging\nfrom os.path import join as opj\nfrom os.path import exists\nfrom nose.tools import assert_raises, assert_equal\nfrom datalad.tests.utils import with_tempfile, assert_not_equal\nfrom datalad.tests.utils import assert_true\nfrom datalad.tests.utils import assert_in\nfrom datalad.tests.utils import assert_not_in\nfrom datalad.tests.utils import assert_dict_equal\nfrom datalad.tests.utils import with_tree\nfrom datalad.tests.utils import ok_clean_git\nfrom datalad.tests.utils import ok_\nfrom datalad.tests.utils import slow\nfrom datalad.utils import swallow_logs\nfrom datalad.distribution.dataset import Dataset\nfrom datalad.distribution.dataset import datasetmethod\nfrom datalad.distribution.dataset import EnsureDataset\nfrom datalad.support.param import Parameter\nfrom datalad.support.constraints import EnsureStr\nfrom datalad.support.constraints import EnsureNone\nfrom datalad.support.constraints import EnsureKeyChoice\n\nfrom ..base import Interface\nfrom ..utils import eval_results\nfrom ..utils import discover_dataset_trace_to_targets\nfrom datalad.interface.base import build_doc\nfrom ..utils import handle_dirty_dataset\n\n\n__docformat__ = 'restructuredtext'\nlgr = logging.getLogger('datalad.interface.tests.test_utils')\n_dirty_modes = ('fail', 'ignore', 'save-before')\n\n\ndef _check_all_clean(ds, state):\n    assert state is not None\n    for mode in _dirty_modes:\n        # nothing wrong, nothing saved\n        handle_dirty_dataset(ds, mode)\n        assert_equal(state, ds.repo.get_hexsha())\n\n\ndef _check_auto_save(ds, orig_state):\n    handle_dirty_dataset(ds, 'ignore')\n    assert_raises(RuntimeError, handle_dirty_dataset, ds, 'fail')\n    handle_dirty_dataset(ds, 'save-before')\n    state = ds.repo.get_hexsha()\n    assert_not_equal(orig_state, state)\n    _check_all_clean(ds, state)\n    return state\n\n\n@with_tempfile(mkdir=True)\ndef test_dirty(path):\n    for mode in _dirty_modes:\n        # does nothing without a dataset\n        handle_dirty_dataset(None, mode)\n    # placeholder, but not yet created\n    ds = Dataset(path)\n    # unknown mode\n    assert_raises(ValueError, handle_dirty_dataset, ds, 'MADEUP')\n    # not yet created is very dirty\n    assert_raises(RuntimeError, handle_dirty_dataset, ds, 'fail')\n    handle_dirty_dataset(ds, 'ignore')\n    assert_raises(RuntimeError, handle_dirty_dataset, ds, 'save-before')\n    # should yield a clean repo\n    ds.create()\n    orig_state = ds.repo.get_hexsha()\n    _check_all_clean(ds, orig_state)\n    # tainted: untracked\n    with open(opj(ds.path, 'something'), 'w') as f:\n        f.write('some')\n    # we don't want to auto-add untracked files by saving (anymore)\n    assert_raises(AssertionError, _check_auto_save, ds, orig_state)\n    # tainted: staged\n    ds.repo.add('something', git=True)\n    orig_state = _check_auto_save(ds, orig_state)\n    # tainted: submodule\n    # not added to super on purpose!\n    subds = ds.create('subds')\n    _check_all_clean(subds, subds.repo.get_hexsha())\n    ok_clean_git(ds.path)\n    # subdataset must be added as a submodule!\n    assert_equal(ds.subdatasets(result_xfm='relpaths'), ['subds'])\n\n\ndemo_hierarchy = {\n    'a': {\n        'aa': {\n            'file_aa': 'file_aa'}},\n    'b': {\n        'ba': {\n            'file_ba': 'file_ba'},\n        'bb': {\n            'bba': {\n                'bbaa': {\n                    'file_bbaa': 'file_bbaa'}},\n            'file_bb': 'file_bb'}},\n    'c': {\n        'ca': {\n            'file_ca': 'file_ca'},\n        'file_c': 'file_c'},\n    'd': {\n        'da': {\n            'file_da': 'file_da'},\n        'db': {\n            'file_db': 'file_db'},\n        'file_d': 'file_d'},\n}\n\n\ndef make_demo_hierarchy_datasets(path, tree, parent=None):\n    if parent is None:\n        parent = Dataset(path).create(force=True)\n    for node, items in tree.items():\n        if isinstance(items, dict):\n            node_path = opj(path, node)\n            nodeds = Dataset(node_path).create(force=True)\n            make_demo_hierarchy_datasets(node_path, items, parent=nodeds)\n    return parent\n\n\n@slow  # 74.4509s\n@with_tree(demo_hierarchy)\n@known_failure_direct_mode  #FIXME\ndef test_save_hierarchy(path):\n    # this test doesn't use API`remove` to avoid circularities\n    ds = make_demo_hierarchy_datasets(path, demo_hierarchy)\n    ds.add('.', recursive=True)\n    ok_clean_git(ds.path)\n    ds_bb = Dataset(opj(ds.path, 'b', 'bb'))\n    ds_bba = Dataset(opj(ds_bb.path, 'bba'))\n    ds_bbaa = Dataset(opj(ds_bba.path, 'bbaa'))\n    # introduce a change at the lowest level\n    ds_bbaa.repo.remove('file_bbaa')\n    for d in (ds, ds_bb, ds_bba, ds_bbaa):\n        ok_(d.repo.dirty)\n    # need to give file specifically, otherwise it will simply just preserve\n    # staged changes\n    ds_bb.save(path=opj(ds_bbaa.path, 'file_bbaa'))\n    # it has saved all changes in the subtrees spanned\n    # by the given datasets, but nothing else\n    for d in (ds_bb, ds_bba, ds_bbaa):\n        ok_clean_git(d.path)\n    ok_(ds.repo.dirty)\n    # now with two modified repos\n    d = Dataset(opj(ds.path, 'd'))\n    da = Dataset(opj(d.path, 'da'))\n    da.repo.remove('file_da')\n    db = Dataset(opj(d.path, 'db'))\n    db.repo.remove('file_db')\n    # generator\n    d.save(recursive=True)\n    for d in (d, da, db):\n        ok_clean_git(d.path)\n    ok_(ds.repo.dirty)\n    # and now with files all over the place and saving\n    # all the way to the root\n    aa = Dataset(opj(ds.path, 'a', 'aa'))\n    aa.repo.remove('file_aa')\n    ba = Dataset(opj(ds.path, 'b', 'ba'))\n    ba.repo.remove('file_ba')\n    bb = Dataset(opj(ds.path, 'b', 'bb'))\n    bb.repo.remove('file_bb')\n    c = Dataset(opj(ds.path, 'c'))\n    c.repo.remove('file_c')\n    ca = Dataset(opj(ds.path, 'c', 'ca'))\n    ca.repo.remove('file_ca')\n    d = Dataset(opj(ds.path, 'd'))\n    d.repo.remove('file_d')\n    ds.save(\n        # append trailing slashes to the path to indicate that we want to\n        # have the staged content in the dataset saved, rather than only the\n        # subdataset state in the respective superds.\n        # an alternative would have been to pass `save` annotated paths of\n        # type {'path': dspath, 'process_content': True} for each dataset\n        # in question, but here we want to test how this would most likely\n        # by used from cmdline\n        path=[opj(p, '')\n               for p in (aa.path, ba.path, bb.path, c.path, ca.path, d.path)],\n        super_datasets=True)\n\n\n# Note: class name needs to match module's name\n@build_doc\nclass TestUtils(Interface):\n    \"\"\"TestUtil's fake command\"\"\"\n\n    _params_ = dict(\n        number=Parameter(\n            args=(\"-n\", \"--number\",),\n            doc=\"\"\"It's a number\"\"\",\n            constraints=EnsureStr() | EnsureNone()),\n        dataset=Parameter(\n            args=(\"-d\", \"--dataset\"),\n            doc=\"\"\"\"specify the dataset to update.  If\n            no dataset is given, an attempt is made to identify the dataset\n            based on the input and/or the current working directory\"\"\",\n            constraints=EnsureDataset() | EnsureNone()),)\n\n    @staticmethod\n    @datasetmethod(name='fake_command')\n    @eval_results\n    def __call__(number, dataset=None):\n\n        for i in range(number):\n            # this dict will need to have the minimum info required by\n            # eval_results\n            yield {'path': 'some', 'status': 'ok', 'somekey': i, 'action': 'off'}\n\n\ndef test_eval_results_plus_build_doc():\n\n    # test docs\n\n    # docstring was build already:\n    with swallow_logs(new_level=logging.DEBUG) as cml:\n        TestUtils().__call__(1)\n        assert_not_in(\"Building doc for\", cml.out)\n    # docstring accessible both ways:\n    doc1 = Dataset.fake_command.__doc__\n    doc2 = TestUtils().__call__.__doc__\n\n    # docstring was built from Test_Util's definition:\n    assert_equal(doc1, doc2)\n    assert_in(\"TestUtil's fake command\", doc1)\n    assert_in(\"Parameters\", doc1)\n    assert_in(\"It's a number\", doc1)\n\n    # docstring also contains eval_result's parameters:\n    assert_in(\"result_filter\", doc1)\n    assert_in(\"return_type\", doc1)\n    assert_in(\"list\", doc1)\n    assert_in(\"None\", doc1)\n    assert_in(\"return value behavior\", doc1)\n    assert_in(\"dictionary is passed\", doc1)\n\n    # test eval_results is able to determine the call, a method of which it is\n    # decorating:\n    with swallow_logs(new_level=logging.DEBUG) as cml:\n        Dataset('/does/not/matter').fake_command(3)\n        assert_in(\"Determined class of decorated function: {}\"\n                  \"\".format(TestUtils().__class__), cml.out)\n\n    # test results:\n    result = TestUtils().__call__(2)\n    assert_equal(len(list(result)), 2)\n    result = Dataset('/does/not/matter').fake_command(3)\n    assert_equal(len(list(result)), 3)\n\n    # test signature:\n    from inspect import getargspec\n    assert_equal(getargspec(Dataset.fake_command)[0], ['number', 'dataset'])\n    assert_equal(getargspec(TestUtils.__call__)[0], ['number', 'dataset'])\n\n\ndef test_result_filter():\n    # ensure baseline without filtering\n    assert_equal(\n        [r['somekey'] for r in TestUtils().__call__(4)],\n        [0, 1, 2, 3])\n    # test two functionally equivalent ways to filter results\n    # 1. Constraint-based -- filter by exception\n    #    we have a full set of AND and OR operators for this\n    # 2. custom filer function -- filter by boolean return value\n    for filt in (\n            EnsureKeyChoice('somekey', (0, 2)),\n            lambda x: x['somekey'] in (0, 2)):\n        assert_equal(\n            [r['somekey'] for r in TestUtils().__call__(\n                4,\n                result_filter=filt)],\n            [0, 2])\n        # constraint returns full dict\n        assert_dict_equal(\n            TestUtils().__call__(\n                4,\n                result_filter=filt)[-1],\n            {'action': 'off', 'path': 'some', 'status': 'ok', 'somekey': 2})\n\n    # test more sophisticated filters that actually get to see the\n    # API call's kwargs\n    def greatfilter(res, **kwargs):\n        assert_equal(kwargs.get('dataset', 'bob'), 'awesome')\n        return True\n    TestUtils().__call__(4, dataset='awesome', result_filter=greatfilter)\n\n    def sadfilter(res, **kwargs):\n        assert_equal(kwargs.get('dataset', 'bob'), None)\n        return True\n    TestUtils().__call__(4, result_filter=sadfilter)\n\n\n@with_tree({k: v for k, v in demo_hierarchy.items() if k in ['a', 'd']})\n@with_tempfile(mkdir=True)\ndef test_discover_ds_trace(path, otherdir):\n    ds = make_demo_hierarchy_datasets(\n        path,\n        {k: v for k, v in demo_hierarchy.items() if k in ['a', 'd']})\n    a = opj(ds.path, 'a')\n    aa = opj(a, 'aa')\n    d = opj(ds.path, 'd')\n    db = opj(d, 'db')\n    # we have to check whether we get the correct hierarchy, as the test\n    # subject is also involved in this\n    assert_true(exists(opj(db, 'file_db')))\n    ds.add('.', recursive=True)\n    ok_clean_git(ds.path)\n    # now two datasets which are not available locally, but we\n    # know about them (e.g. from metadata)\n    dba = opj(db, 'sub', 'dba')\n    dbaa = opj(dba, 'subsub', 'dbaa')\n    for input, eds, goal in (\n            ([], None, {}),\n            ([ds.path], None, {}),\n            ([otherdir], None, {}),\n            ([opj(ds.path, 'nothere')], None, {}),\n            ([opj(d, 'nothere')], None, {}),\n            ([opj(db, 'nothere')], None, {}),\n            ([a], None,\n             {ds.path: set([a])}),\n            ([aa, a], None,\n             {ds.path: set([a]), a: set([aa])}),\n            ([db], None,\n             {ds.path: set([d]), d: set([db])}),\n            ([opj(db, 'file_db')], None,\n             {ds.path: set([d]), d: set([db])}),\n            # just a regular non-existing path\n            ([dba], None, {}),\n            # but if we inject this knowledge it must come back out\n            # as the child of the closest existing dataset\n            ([dba], [dba],\n             {ds.path: set([d]), d: set([db]), db: set([dba])}),\n            # regardless of the depth\n            ([dbaa], [dbaa],\n             {ds.path: set([d]), d: set([db]), db: set([dbaa])}),\n            ([dba, dbaa], [dba, dbaa],\n             {ds.path: set([d]), d: set([db]), db: set([dba, dbaa])}),\n            # we can simply add existing and non-existing datasets to the\n            # include list get the desired result\n            ([d, dba, dbaa], [d, dba, dbaa],\n             {ds.path: set([d]), d: set([db]), db: set([dba, dbaa])}),\n    ):\n        spec = {}\n        discover_dataset_trace_to_targets(ds.path, input, [], spec, includeds=eds)\n        assert_dict_equal(spec, goal)\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\"\"\"Test interface.utils\n\n\"\"\"\n\nfrom datalad.tests.utils import known_failure_direct_mode\n\nimport os\nimport logging\nfrom os.path import join as opj\nfrom os.path import exists\nfrom nose.tools import assert_raises, assert_equal\nfrom datalad.tests.utils import with_tempfile, assert_not_equal\nfrom datalad.tests.utils import assert_true\nfrom datalad.tests.utils import assert_in\nfrom datalad.tests.utils import assert_not_in\nfrom datalad.tests.utils import assert_dict_equal\nfrom datalad.tests.utils import with_tree\nfrom datalad.tests.utils import ok_clean_git\nfrom datalad.tests.utils import ok_\nfrom datalad.tests.utils import slow\nfrom datalad.utils import swallow_logs\nfrom datalad.distribution.dataset import Dataset\nfrom datalad.distribution.dataset import datasetmethod\nfrom datalad.distribution.dataset import EnsureDataset\nfrom datalad.support.param import Parameter\nfrom datalad.support.constraints import EnsureStr\nfrom datalad.support.constraints import EnsureNone\nfrom datalad.support.constraints import EnsureKeyChoice\n\nfrom ..base import Interface\nfrom ..utils import eval_results\nfrom ..utils import discover_dataset_trace_to_targets\nfrom datalad.interface.base import build_doc\nfrom ..utils import handle_dirty_dataset\n\n\n__docformat__ = 'restructuredtext'\nlgr = logging.getLogger('datalad.interface.tests.test_utils')\n_dirty_modes = ('fail', 'ignore', 'save-before')\n\n\ndef _check_all_clean(ds, state):\n    assert state is not None\n    for mode in _dirty_modes:\n        # nothing wrong, nothing saved\n        handle_dirty_dataset(ds, mode)\n        assert_equal(state, ds.repo.get_hexsha())\n\n\ndef _check_auto_save(ds, orig_state):\n    handle_dirty_dataset(ds, 'ignore')\n    assert_raises(RuntimeError, handle_dirty_dataset, ds, 'fail')\n    handle_dirty_dataset(ds, 'save-before')\n    state = ds.repo.get_hexsha()\n    assert_not_equal(orig_state, state)\n    _check_all_clean(ds, state)\n    return state\n\n\n@with_tempfile(mkdir=True)\ndef test_dirty(path):\n    for mode in _dirty_modes:\n        # does nothing without a dataset\n        handle_dirty_dataset(None, mode)\n    # placeholder, but not yet created\n    ds = Dataset(path)\n    # unknown mode\n    assert_raises(ValueError, handle_dirty_dataset, ds, 'MADEUP')\n    # not yet created is very dirty\n    assert_raises(RuntimeError, handle_dirty_dataset, ds, 'fail')\n    handle_dirty_dataset(ds, 'ignore')\n    assert_raises(RuntimeError, handle_dirty_dataset, ds, 'save-before')\n    # should yield a clean repo\n    ds.create()\n    orig_state = ds.repo.get_hexsha()\n    _check_all_clean(ds, orig_state)\n    # tainted: untracked\n    with open(opj(ds.path, 'something'), 'w') as f:\n        f.write('some')\n    # we don't want to auto-add untracked files by saving (anymore)\n    assert_raises(AssertionError, _check_auto_save, ds, orig_state)\n    # tainted: staged\n    ds.repo.add('something', git=True)\n    orig_state = _check_auto_save(ds, orig_state)\n    # tainted: submodule\n    # not added to super on purpose!\n    subds = ds.create('subds')\n    _check_all_clean(subds, subds.repo.get_hexsha())\n    ok_clean_git(ds.path)\n    # subdataset must be added as a submodule!\n    assert_equal(ds.subdatasets(result_xfm='relpaths'), ['subds'])\n\n\ndemo_hierarchy = {\n    'a': {\n        'aa': {\n            'file_aa': 'file_aa'}},\n    'b': {\n        'ba': {\n            'file_ba': 'file_ba'},\n        'bb': {\n            'bba': {\n                'bbaa': {\n                    'file_bbaa': 'file_bbaa'}},\n            'file_bb': 'file_bb'}},\n    'c': {\n        'ca': {\n            'file_ca': 'file_ca'},\n        'file_c': 'file_c'},\n    'd': {\n        'da': {\n            'file_da': 'file_da'},\n        'db': {\n            'file_db': 'file_db'},\n        'file_d': 'file_d'},\n}\n\n\ndef make_demo_hierarchy_datasets(path, tree, parent=None):\n    if parent is None:\n        parent = Dataset(path).create(force=True)\n    for node, items in tree.items():\n        if isinstance(items, dict):\n            node_path = opj(path, node)\n            nodeds = Dataset(node_path).create(force=True)\n            make_demo_hierarchy_datasets(node_path, items, parent=nodeds)\n    return parent\n\n\n@slow  # 74.4509s\n@with_tree(demo_hierarchy)\n@known_failure_direct_mode  #FIXME\ndef test_save_hierarchy(path):\n    # this test doesn't use API`remove` to avoid circularities\n    ds = make_demo_hierarchy_datasets(path, demo_hierarchy)\n    ds.add('.', recursive=True)\n    ok_clean_git(ds.path)\n    ds_bb = Dataset(opj(ds.path, 'b', 'bb'))\n    ds_bba = Dataset(opj(ds_bb.path, 'bba'))\n    ds_bbaa = Dataset(opj(ds_bba.path, 'bbaa'))\n    # introduce a change at the lowest level\n    ds_bbaa.repo.remove('file_bbaa')\n    for d in (ds, ds_bb, ds_bba, ds_bbaa):\n        ok_(d.repo.dirty)\n    # need to give file specifically, otherwise it will simply just preserve\n    # staged changes\n    ds_bb.save(path=opj(ds_bbaa.path, 'file_bbaa'))\n    # it has saved all changes in the subtrees spanned\n    # by the given datasets, but nothing else\n    for d in (ds_bb, ds_bba, ds_bbaa):\n        ok_clean_git(d.path)\n    ok_(ds.repo.dirty)\n    # now with two modified repos\n    d = Dataset(opj(ds.path, 'd'))\n    da = Dataset(opj(d.path, 'da'))\n    da.repo.remove('file_da')\n    db = Dataset(opj(d.path, 'db'))\n    db.repo.remove('file_db')\n    # generator\n    d.save(recursive=True)\n    for d in (d, da, db):\n        ok_clean_git(d.path)\n    ok_(ds.repo.dirty)\n    # and now with files all over the place and saving\n    # all the way to the root\n    aa = Dataset(opj(ds.path, 'a', 'aa'))\n    aa.repo.remove('file_aa')\n    ba = Dataset(opj(ds.path, 'b', 'ba'))\n    ba.repo.remove('file_ba')\n    bb = Dataset(opj(ds.path, 'b', 'bb'))\n    bb.repo.remove('file_bb')\n    c = Dataset(opj(ds.path, 'c'))\n    c.repo.remove('file_c')\n    ca = Dataset(opj(ds.path, 'c', 'ca'))\n    ca.repo.remove('file_ca')\n    d = Dataset(opj(ds.path, 'd'))\n    d.repo.remove('file_d')\n    ds.save(\n        # append trailing slashes to the path to indicate that we want to\n        # have the staged content in the dataset saved, rather than only the\n        # subdataset state in the respective superds.\n        # an alternative would have been to pass `save` annotated paths of\n        # type {'path': dspath, 'process_content': True} for each dataset\n        # in question, but here we want to test how this would most likely\n        # by used from cmdline\n        path=[opj(p, '')\n               for p in (aa.path, ba.path, bb.path, c.path, ca.path, d.path)],\n        super_datasets=True)\n\n\n# Note: class name needs to match module's name\n@build_doc\nclass TestUtils(Interface):\n    \"\"\"TestUtil's fake command\"\"\"\n\n    _params_ = dict(\n        number=Parameter(\n            args=(\"-n\", \"--number\",),\n            doc=\"\"\"It's a number\"\"\",\n            constraints=EnsureStr() | EnsureNone()),\n        dataset=Parameter(\n            args=(\"-d\", \"--dataset\"),\n            doc=\"\"\"\"specify the dataset to update.  If\n            no dataset is given, an attempt is made to identify the dataset\n            based on the input and/or the current working directory\"\"\",\n            constraints=EnsureDataset() | EnsureNone()),)\n\n    @staticmethod\n    @datasetmethod(name='fake_command')\n    @eval_results\n    def __call__(number, dataset=None):\n\n        for i in range(number):\n            # this dict will need to have the minimum info required by\n            # eval_results\n            yield {'path': 'some', 'status': 'ok', 'somekey': i, 'action': 'off'}\n\n\ndef test_eval_results_plus_build_doc():\n\n    # test docs\n\n    # docstring was build already:\n    with swallow_logs(new_level=logging.DEBUG) as cml:\n        TestUtils().__call__(1)\n        assert_not_in(\"Building doc for\", cml.out)\n    # docstring accessible both ways:\n    doc1 = Dataset.fake_command.__doc__\n    doc2 = TestUtils().__call__.__doc__\n\n    # docstring was built from Test_Util's definition:\n    assert_equal(doc1, doc2)\n    assert_in(\"TestUtil's fake command\", doc1)\n    assert_in(\"Parameters\", doc1)\n    assert_in(\"It's a number\", doc1)\n\n    # docstring also contains eval_result's parameters:\n    assert_in(\"result_filter\", doc1)\n    assert_in(\"return_type\", doc1)\n    assert_in(\"list\", doc1)\n    assert_in(\"None\", doc1)\n    assert_in(\"return value behavior\", doc1)\n    assert_in(\"dictionary is passed\", doc1)\n\n    # test eval_results is able to determine the call, a method of which it is\n    # decorating:\n    with swallow_logs(new_level=logging.DEBUG) as cml:\n        Dataset('/does/not/matter').fake_command(3)\n        assert_in(\"Determined class of decorated function: {}\"\n                  \"\".format(TestUtils().__class__), cml.out)\n\n    # test results:\n    result = TestUtils().__call__(2)\n    assert_equal(len(list(result)), 2)\n    result = Dataset('/does/not/matter').fake_command(3)\n    assert_equal(len(list(result)), 3)\n\n    # test absent side-effect of popping eval_defaults\n    kwargs = dict(return_type='list')\n    TestUtils().__call__(2, **kwargs)\n    assert_equal(list(kwargs), ['return_type'])\n\n    # test signature:\n    from inspect import getargspec\n    assert_equal(getargspec(Dataset.fake_command)[0], ['number', 'dataset'])\n    assert_equal(getargspec(TestUtils.__call__)[0], ['number', 'dataset'])\n\n\ndef test_result_filter():\n    # ensure baseline without filtering\n    assert_equal(\n        [r['somekey'] for r in TestUtils().__call__(4)],\n        [0, 1, 2, 3])\n    # test two functionally equivalent ways to filter results\n    # 1. Constraint-based -- filter by exception\n    #    we have a full set of AND and OR operators for this\n    # 2. custom filer function -- filter by boolean return value\n    for filt in (\n            EnsureKeyChoice('somekey', (0, 2)),\n            lambda x: x['somekey'] in (0, 2)):\n        assert_equal(\n            [r['somekey'] for r in TestUtils().__call__(\n                4,\n                result_filter=filt)],\n            [0, 2])\n        # constraint returns full dict\n        assert_dict_equal(\n            TestUtils().__call__(\n                4,\n                result_filter=filt)[-1],\n            {'action': 'off', 'path': 'some', 'status': 'ok', 'somekey': 2})\n\n    # test more sophisticated filters that actually get to see the\n    # API call's kwargs\n    def greatfilter(res, **kwargs):\n        assert_equal(kwargs.get('dataset', 'bob'), 'awesome')\n        return True\n    TestUtils().__call__(4, dataset='awesome', result_filter=greatfilter)\n\n    def sadfilter(res, **kwargs):\n        assert_equal(kwargs.get('dataset', 'bob'), None)\n        return True\n    TestUtils().__call__(4, result_filter=sadfilter)\n\n\n@with_tree({k: v for k, v in demo_hierarchy.items() if k in ['a', 'd']})\n@with_tempfile(mkdir=True)\ndef test_discover_ds_trace(path, otherdir):\n    ds = make_demo_hierarchy_datasets(\n        path,\n        {k: v for k, v in demo_hierarchy.items() if k in ['a', 'd']})\n    a = opj(ds.path, 'a')\n    aa = opj(a, 'aa')\n    d = opj(ds.path, 'd')\n    db = opj(d, 'db')\n    # we have to check whether we get the correct hierarchy, as the test\n    # subject is also involved in this\n    assert_true(exists(opj(db, 'file_db')))\n    ds.add('.', recursive=True)\n    ok_clean_git(ds.path)\n    # now two datasets which are not available locally, but we\n    # know about them (e.g. from metadata)\n    dba = opj(db, 'sub', 'dba')\n    dbaa = opj(dba, 'subsub', 'dbaa')\n    for input, eds, goal in (\n            ([], None, {}),\n            ([ds.path], None, {}),\n            ([otherdir], None, {}),\n            ([opj(ds.path, 'nothere')], None, {}),\n            ([opj(d, 'nothere')], None, {}),\n            ([opj(db, 'nothere')], None, {}),\n            ([a], None,\n             {ds.path: set([a])}),\n            ([aa, a], None,\n             {ds.path: set([a]), a: set([aa])}),\n            ([db], None,\n             {ds.path: set([d]), d: set([db])}),\n            ([opj(db, 'file_db')], None,\n             {ds.path: set([d]), d: set([db])}),\n            # just a regular non-existing path\n            ([dba], None, {}),\n            # but if we inject this knowledge it must come back out\n            # as the child of the closest existing dataset\n            ([dba], [dba],\n             {ds.path: set([d]), d: set([db]), db: set([dba])}),\n            # regardless of the depth\n            ([dbaa], [dbaa],\n             {ds.path: set([d]), d: set([db]), db: set([dbaa])}),\n            ([dba, dbaa], [dba, dbaa],\n             {ds.path: set([d]), d: set([db]), db: set([dba, dbaa])}),\n            # we can simply add existing and non-existing datasets to the\n            # include list get the desired result\n            ([d, dba, dbaa], [d, dba, dbaa],\n             {ds.path: set([d]), d: set([db]), db: set([dba, dbaa])}),\n    ):\n        spec = {}\n        discover_dataset_trace_to_targets(ds.path, input, [], spec, includeds=eds)\n        assert_dict_equal(spec, goal)\n",
            "header": {
                "file": {
                    "path": "datalad/interface/tests/test_utils.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "491636481",
                "new_commit_hash": "f2a42b380",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/datalad/interface/tests/test_utils.py"
            },
            "plus_file": {
                "path": "b/datalad/interface/tests/test_utils.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 263,
                            "length": 6
                        },
                        "new_range": {
                            "start": 263,
                            "length": 11
                        },
                        "section": "def test_eval_results_plus_build_doc():"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    result = Dataset('/does/not/matter').fake_command(3)",
                                "type": "context"
                            },
                            {
                                "content": "    assert_equal(len(list(result)), 3)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    # test absent side-effect of popping eval_defaults",
                                "type": "added"
                            },
                            {
                                "content": "    kwargs = dict(return_type='list')",
                                "type": "added"
                            },
                            {
                                "content": "    TestUtils().__call__(2, **kwargs)",
                                "type": "added"
                            },
                            {
                                "content": "    assert_equal(list(kwargs), ['return_type'])",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    # test signature:",
                                "type": "context"
                            },
                            {
                                "content": "    from inspect import getargspec",
                                "type": "context"
                            },
                            {
                                "content": "    assert_equal(getargspec(Dataset.fake_command)[0], ['number', 'dataset'])",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "datalad/interface/tests/test_utils.py",
                            "type": "function",
                            "name": "test_eval_results_plus_build_doc",
                            "content": "def test_eval_results_plus_build_doc():\n\n    # test docs\n\n    # docstring was build already:\n    with swallow_logs(new_level=logging.DEBUG) as cml:\n        TestUtils().__call__(1)\n        assert_not_in(\"Building doc for\", cml.out)\n    # docstring accessible both ways:\n    doc1 = Dataset.fake_command.__doc__\n    doc2 = TestUtils().__call__.__doc__\n\n    # docstring was built from Test_Util's definition:\n    assert_equal(doc1, doc2)\n    assert_in(\"TestUtil's fake command\", doc1)\n    assert_in(\"Parameters\", doc1)\n    assert_in(\"It's a number\", doc1)\n\n    # docstring also contains eval_result's parameters:\n    assert_in(\"result_filter\", doc1)\n    assert_in(\"return_type\", doc1)\n    assert_in(\"list\", doc1)\n    assert_in(\"None\", doc1)\n    assert_in(\"return value behavior\", doc1)\n    assert_in(\"dictionary is passed\", doc1)\n\n    # test eval_results is able to determine the call, a method of which it is\n    # decorating:\n    with swallow_logs(new_level=logging.DEBUG) as cml:\n        Dataset('/does/not/matter').fake_command(3)\n        assert_in(\"Determined class of decorated function: {}\"\n                  \"\".format(TestUtils().__class__), cml.out)\n\n    # test results:\n    result = TestUtils().__call__(2)\n    assert_equal(len(list(result)), 2)\n    result = Dataset('/does/not/matter').fake_command(3)\n    assert_equal(len(list(result)), 3)\n\n    # test absent side-effect of popping eval_defaults\n    kwargs = dict(return_type='list')\n    TestUtils().__call__(2, **kwargs)\n    assert_equal(list(kwargs), ['return_type'])\n\n    # test signature:\n    from inspect import getargspec\n    assert_equal(getargspec(Dataset.fake_command)[0], ['number', 'dataset'])\n    assert_equal(getargspec(TestUtils.__call__)[0], ['number', 'dataset'])",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 227,
                            "end_lineno": 274,
                            "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\"\"\"Interface utility functions\n\n\"\"\"\n\n__docformat__ = 'restructuredtext'\n\nimport inspect\nimport logging\nimport wrapt\nimport sys\nimport re\nimport shlex\nfrom os import curdir\nfrom os import pardir\nfrom os import listdir\nfrom os.path import join as opj\nfrom os.path import isdir\nfrom os.path import relpath\nfrom os.path import sep\nfrom os.path import split as psplit\nfrom itertools import chain\nfrom six import PY2\n\nimport json\n\n# avoid import from API to not get into circular imports\nfrom datalad.utils import with_pathsep as _with_sep  # TODO: RF whenever merge conflict is not upon us\nfrom datalad.utils import path_startswith\nfrom datalad.utils import path_is_subpath\nfrom datalad.utils import assure_unicode\nfrom datalad.support.gitrepo import GitRepo\nfrom datalad.support.exceptions import IncompleteResultsError\nfrom datalad import cfg as dlcfg\nfrom datalad.dochelpers import exc_str\n\n\nfrom datalad.support.constraints import Constraint\n\nfrom datalad.ui import ui\nimport datalad.support.ansi_colors as ac\n\nfrom datalad.interface.base import Interface\nfrom datalad.interface.base import default_logchannels\nfrom datalad.interface.base import get_allargs_as_kwargs\nfrom datalad.interface.common_opts import eval_params\nfrom datalad.interface.common_opts import eval_defaults\nfrom .results import known_result_xfms\n\n\nlgr = logging.getLogger('datalad.interface.utils')\n\n\ndef cls2cmdlinename(cls):\n    \"Return the cmdline command name from an Interface class\"\n    r = re.compile(r'([a-z0-9])([A-Z])')\n    return r.sub('\\\\1-\\\\2', cls.__name__).lower()\n\n\n# TODO remove\n# only `drop` and `uninstall` are still using this\ndef handle_dirty_dataset(ds, mode, msg=None):\n    \"\"\"Detect and treat unsaved changes as instructed by `mode`\n\n    Parameters\n    ----------\n    ds : Dataset or None\n      Dataset to be inspected. Does nothing if `None`.\n    mode : {'fail', 'ignore', 'save-before'}\n      How to act upon discovering unsaved changes.\n    msg : str or None\n      Custom message to use for a potential commit.\n\n    Returns\n    -------\n    None\n    \"\"\"\n    if ds is None:\n        # nothing to be handled\n        return\n    if msg is None:\n        msg = '[DATALAD] auto-saved changes'\n\n    # make sure that all pending changes (batched annex operations, etc.)\n    # are actually reflected in Git\n    if ds.repo:\n        ds.repo.precommit()\n\n    if mode == 'ignore':\n        return\n    elif mode == 'fail':\n        if not ds.repo or ds.repo.is_dirty(index=True,\n                                           untracked_files=True,\n                                           submodules=True):\n            raise RuntimeError('dataset {} has unsaved changes'.format(ds))\n    elif mode == 'save-before':\n        if not ds.is_installed():\n            raise RuntimeError('dataset {} is not yet installed'.format(ds))\n        from datalad.interface.save import Save\n        Save.__call__(dataset=ds, message=msg)\n    else:\n        raise ValueError(\"unknown if-dirty mode '{}'\".format(mode))\n\n\ndef get_tree_roots(paths):\n    \"\"\"Return common root paths for a set of paths\n\n    This function determines the smallest set of common root\n    paths and sorts all given paths under the respective\n    root.\n\n    Returns\n    -------\n    dict\n      paths by root\n    \"\"\"\n    paths_ws = [_with_sep(p) for p in paths]\n    # sort all paths under their potential roots\n    roots = {}\n    # start from the top to get all paths down the line\n    # and collate them into as few roots as possible\n    for s in sorted(paths_ws):\n        if any([s.startswith(r) for r in roots]):\n            # this path is already covered by a known root\n            continue\n        # find all sub paths\n        subs = [p for p in paths if p.startswith(s)]\n        roots[s.rstrip(sep)] = subs\n    return roots\n\n\n# TODO remove\n# only `remove` and `uninstall` use this, the uses path `path_is_subpath`\ndef path_is_under(values, path=None):\n    \"\"\"Whether a given path is a subdirectory of any of the given test values\n\n    Parameters\n    ----------\n    values : sequence or dict\n      Paths to be tested against. This can be a dictionary in which case\n      all values from all keys will be tested against.\n    path : path or None\n      Test path. If None is given, the process' working directory is\n      used.\n\n    Returns\n    -------\n    bool\n    \"\"\"\n    if path is None:\n        from datalad.utils import getpwd\n        path = getpwd()\n    if isinstance(values, dict):\n        values = chain(*values.values())\n    for p in values:\n        rpath = relpath(p, start=path)\n        if rpath == curdir \\\n                or rpath == pardir \\\n                or set(psplit(rpath)) == {pardir}:\n            # first match is enough\n            return True\n    return False\n\n\ndef discover_dataset_trace_to_targets(basepath, targetpaths, current_trace,\n                                      spec, includeds=None):\n    \"\"\"Discover the edges and nodes in a dataset tree to given target paths\n\n    Parameters\n    ----------\n    basepath : path\n      Path to a start or top-level dataset. Really has to be a path to a\n      dataset!\n    targetpaths : list(path)\n      Any non-zero number of paths that are termination points for the\n      search algorithm. Can be paths to datasets, directories, or files\n      (and any combination thereof).\n    current_trace : list\n      For a top-level call this should probably always be `[]`\n    spec : dict\n      `content_by_ds`-style dictionary that will receive information about the\n      discovered datasets. Specifically, for each discovered dataset there\n      will be in item with its path under the key (path) of the respective\n      superdataset.\n    includeds : sequence, optional\n      Any paths given are treated as existing subdatasets, regardless of\n      whether they can be found in the filesystem. Such subdatasets will appear\n      under the key of the closest existing dataset in the `spec`.\n\n    Returns\n    -------\n    None\n      Function calls itself recursively and populates `spec` dict in-place.\n      Keys are dataset paths, values are sets of subdataset paths\n    \"\"\"\n    # convert to set for faster lookup\n    includeds = includeds if isinstance(includeds, set) else \\\n        set() if includeds is None else set(includeds)\n    # this beast walks the directory tree from a given `basepath` until\n    # it discovers any of the given `targetpaths`\n    # if it finds one, it commits any accummulated trace of visited\n    # datasets on this edge to the spec\n    valid_repo = GitRepo.is_valid_repo(basepath)\n    if valid_repo:\n        # we are passing into a new dataset, extend the dataset trace\n        current_trace = current_trace + [basepath]\n    # this edge is not done, we need to try to reach any downstream\n    # dataset\n    undiscovered_ds = set(t for t in targetpaths) # if t != basepath)\n    # whether anything in this directory matched a targetpath\n    filematch = False\n    if isdir(basepath):\n        for p in listdir(basepath):\n            p = assure_unicode(opj(basepath, p))\n            if not isdir(p):\n                if p in targetpaths:\n                    filematch = True\n                # we cannot have anything below this one\n                continue\n            # OPT listdir might be large and we could have only few items\n            # in `targetpaths` -- so traverse only those in spec which have\n            # leading dir basepath\n            # filter targets matching this downward path\n            downward_targets = set(\n                t for t in targetpaths if path_startswith(t, p))\n            if not downward_targets:\n                continue\n            # remove the matching ones from the \"todo\" list\n            undiscovered_ds.difference_update(downward_targets)\n            # go one deeper\n            discover_dataset_trace_to_targets(\n                p, downward_targets, current_trace, spec,\n                includeds=includeds if not includeds else includeds.intersection(\n                    downward_targets))\n    undiscovered_ds = [t for t in undiscovered_ds\n                       if includeds and\n                          path_is_subpath(t, current_trace[-1]) and\n                          t in includeds]\n    if filematch or basepath in targetpaths or undiscovered_ds:\n        for i, p in enumerate(current_trace[:-1]):\n            # TODO RF prepare proper annotated path dicts\n            subds = spec.get(p, set())\n            subds.add(current_trace[i + 1])\n            spec[p] = subds\n        if undiscovered_ds:\n            spec[current_trace[-1]] = spec.get(current_trace[-1], set()).union(\n                undiscovered_ds)\n\n\ndef eval_results(func):\n    \"\"\"Decorator for return value evaluation of datalad commands.\n\n    Note, this decorator is only compatible with commands that return\n    status dict sequences!\n\n    Two basic modes of operation are supported: 1) \"generator mode\" that\n    `yields` individual results, and 2) \"list mode\" that returns a sequence of\n    results. The behavior can be selected via the kwarg `return_type`.\n    Default is \"list mode\".\n\n    This decorator implements common functionality for result rendering/output,\n    error detection/handling, and logging.\n\n    Result rendering/output can be triggered via the\n    `datalad.api.result-renderer` configuration variable, or the\n    `result_renderer` keyword argument of each decorated command. Supported\n    modes are: 'default' (one line per result with action, status, path,\n    and an optional message); 'json' (one object per result, like git-annex),\n    'json_pp' (like 'json', but pretty-printed spanning multiple lines),\n    'tailored' custom output formatting provided by each command\n    class (if any).\n\n    Error detection works by inspecting the `status` item of all result\n    dictionaries. Any occurrence of a status other than 'ok' or 'notneeded'\n    will cause an IncompleteResultsError exception to be raised that carries\n    the failed actions' status dictionaries in its `failed` attribute.\n\n    Status messages will be logged automatically, by default the following\n    association of result status and log channel will be used: 'ok' (debug),\n    'notneeded' (debug), 'impossible' (warning), 'error' (error).  Logger\n    instances included in the results are used to capture the origin of a\n    status report.\n\n    Parameters\n    ----------\n    func: function\n      __call__ method of a subclass of Interface,\n      i.e. a datalad command definition\n    \"\"\"\n\n    @wrapt.decorator\n    def eval_func(wrapped, instance, args, kwargs):\n        # for result filters and pre/post procedures\n        # we need to produce a dict with argname/argvalue pairs for all args\n        # incl. defaults and args given as positionals\n        allkwargs = get_allargs_as_kwargs(wrapped, args, kwargs)\n        # determine class, the __call__ method of which we are decorating:\n        # Ben: Note, that this is a bit dirty in PY2 and imposes restrictions on\n        # when and how to use eval_results as well as on how to name a command's\n        # module and class. As of now, we are inline with these requirements as\n        # far as I'm aware.\n        mod = sys.modules[wrapped.__module__]\n        if PY2:\n            # we rely on:\n            # - decorated function is method of a subclass of Interface\n            # - the name of the class matches the last part of the module's name\n            #   if converted to lower\n            # for example:\n            # ..../where/ever/mycommand.py:\n            # class MyCommand(Interface):\n            #     @eval_results\n            #     def __call__(..)\n            command_class_names = \\\n                [i for i in mod.__dict__\n                 if type(mod.__dict__[i]) == type and\n                 issubclass(mod.__dict__[i], Interface) and\n                 i.lower().startswith(wrapped.__module__.split('.')[-1].replace('datalad_', '').replace('_', ''))]\n            assert len(command_class_names) == 1, (command_class_names, mod.__name__)\n            command_class_name = command_class_names[0]\n        else:\n            command_class_name = wrapped.__qualname__.split('.')[-2]\n        _func_class = mod.__dict__[command_class_name]\n        lgr.debug(\"Determined class of decorated function: %s\", _func_class)\n\n        # retrieve common options from kwargs, and fall back on the command\n        # class attributes, or general defaults if needed\n        common_params = {\n            p_name: kwargs.pop(\n                p_name,\n                getattr(_func_class, p_name, eval_defaults[p_name]))\n            for p_name in eval_params}\n        # short cuts and configured setup for common options\n        on_failure = common_params['on_failure']\n        return_type = common_params['return_type']\n        # resolve string labels for transformers too\n        result_xfm = common_params['result_xfm']\n        if result_xfm in known_result_xfms:\n            result_xfm = known_result_xfms[result_xfm]\n        result_renderer = common_params['result_renderer']\n        # TODO remove this conditional branch entirely, done outside\n        if not result_renderer:\n            result_renderer = dlcfg.get('datalad.api.result-renderer', None)\n        # wrap the filter into a helper to be able to pass additional arguments\n        # if the filter supports it, but at the same time keep the required interface\n        # as minimal as possible. Also do this here, in order to avoid this test\n        # to be performed for each return value\n        result_filter = common_params['result_filter']\n        _result_filter = result_filter\n        if result_filter:\n            if isinstance(result_filter, Constraint):\n                _result_filter = result_filter.__call__\n            if (PY2 and inspect.getargspec(_result_filter).keywords) or \\\n                    (not PY2 and inspect.getfullargspec(_result_filter).varkw):\n\n                def _result_filter(res):\n                    return result_filter(res, **allkwargs)\n\n        def _get_procedure_specs(param_key=None, cfg_key=None, ds=None):\n            spec = common_params.get(param_key, None)\n            if spec is not None:\n                # this is already a list of lists\n                return spec\n\n            from datalad.distribution.dataset import Dataset\n            ds = ds if isinstance(ds, Dataset) else Dataset(ds) if ds else None\n            spec = (ds.config if ds and ds.is_installed()\n                    else dlcfg).get(cfg_key, None)\n            if spec is None:\n                return\n            elif not isinstance(spec, tuple):\n                spec = [spec]\n            return [shlex.split(s) for s in spec]\n\n        # query cfg for defaults\n        cmdline_name = cls2cmdlinename(_func_class)\n        dataset_arg = allkwargs.get('dataset', None)\n        proc_pre = _get_procedure_specs(\n            'proc_pre',\n            'datalad.{}.proc-pre'.format(cmdline_name),\n            ds=dataset_arg)\n        proc_post = _get_procedure_specs(\n            'proc_post',\n            'datalad.{}.proc-post'.format(cmdline_name),\n            ds=dataset_arg)\n\n        # this internal helper function actually drives the command\n        # generator-style, it may generate an exception if desired,\n        # on incomplete results\n        def generator_func(*_args, **_kwargs):\n            # flag whether to raise an exception\n            incomplete_results = []\n            # track what actions were performed how many times\n            action_summary = {}\n\n            if proc_pre and cmdline_name != 'run-procedure':\n                from datalad.interface.run_procedure import RunProcedure\n                for procspec in proc_pre:\n                    lgr.debug('Running configured pre-procedure %s', procspec)\n                    for r in _process_results(\n                            RunProcedure.__call__(\n                                procspec,\n                                dataset=dataset_arg,\n                                return_type='generator'),\n                            _func_class, action_summary,\n                            on_failure, incomplete_results,\n                            result_renderer, result_xfm, result_filter,\n                            **_kwargs):\n                        yield r\n\n            # if a custom summary is to be provided, collect the results\n            # of the command execution\n            results = []\n            do_custom_result_summary = result_renderer == 'tailored' \\\n                and hasattr(_func_class, 'custom_result_summary_renderer')\n\n            # process main results\n            for r in _process_results(\n                    wrapped(*_args, **_kwargs),\n                    _func_class, action_summary,\n                    on_failure, incomplete_results,\n                    result_renderer, result_xfm, _result_filter, **_kwargs):\n                yield r\n                # collect if summary is desired\n                if do_custom_result_summary:\n                    results.append(r)\n\n            if proc_post and cmdline_name != 'run-procedure':\n                from datalad.interface.run_procedure import RunProcedure\n                for procspec in proc_post:\n                    lgr.debug('Running configured post-procedure %s', procspec)\n                    for r in _process_results(\n                            RunProcedure.__call__(\n                                procspec,\n                                dataset=dataset_arg,\n                                return_type='generator'),\n                            _func_class, action_summary,\n                            on_failure, incomplete_results,\n                            result_renderer, result_xfm, result_filter,\n                            **_kwargs):\n                        yield r\n\n            # result summary before a potential exception\n            # custom first\n            if do_custom_result_summary:\n                _func_class.custom_result_summary_renderer(results)\n            elif result_renderer == 'default' and action_summary and \\\n                    sum(sum(s.values()) for s in action_summary.values()) > 1:\n                # give a summary in default mode, when there was more than one\n                # action performed\n                ui.message(\"action summary:\\n  {}\".format(\n                    '\\n  '.join('{} ({})'.format(\n                        act,\n                        ', '.join('{}: {}'.format(status, action_summary[act][status])\n                                  for status in sorted(action_summary[act])))\n                                for act in sorted(action_summary))))\n\n            if incomplete_results:\n                raise IncompleteResultsError(\n                    failed=incomplete_results,\n                    msg=\"Command did not complete successfully\")\n\n        if return_type == 'generator':\n            # hand over the generator\n            return generator_func(*args, **kwargs)\n        else:\n            @wrapt.decorator\n            def return_func(wrapped_, instance_, args_, kwargs_):\n                results = wrapped_(*args_, **kwargs_)\n                if inspect.isgenerator(results):\n                    # unwind generator if there is one, this actually runs\n                    # any processing\n                    results = list(results)\n                # render summaries\n                if not result_xfm and result_renderer == 'tailored':\n                    # cannot render transformed results\n                    if hasattr(_func_class, 'custom_result_summary_renderer'):\n                        _func_class.custom_result_summary_renderer(results)\n                if return_type == 'item-or-list' and \\\n                        len(results) < 2:\n                    return results[0] if results else None\n                else:\n                    return results\n\n            return return_func(generator_func)(*args, **kwargs)\n\n    return eval_func(func)\n\n\ndef default_result_renderer(res):\n    if res.get('status', None) != 'notneeded':\n        ui.message('{action}({status}): {path}{type}{msg}'.format(\n                action=ac.color_word(res['action'], ac.BOLD),\n                status=ac.color_status(res['status']),\n                path=relpath(res['path'],\n                             res['refds']) if res.get('refds', None) else res[\n                    'path'],\n                type=' ({})'.format(\n                        ac.color_word(res['type'], ac.MAGENTA)\n                ) if 'type' in res else '',\n                msg=' [{}]'.format(\n                        res['message'][0] % res['message'][1:]\n                        if isinstance(res['message'], tuple) else res[\n                            'message'])\n                if 'message' in res else ''))\n\n\ndef _process_results(\n        results, cmd_class,\n        action_summary, on_failure, incomplete_results,\n        result_renderer, result_xfm, result_filter, **kwargs):\n    # private helper pf @eval_results\n    # loop over results generated from some source and handle each\n    # of them according to the requested behavior (logging, rendering, ...)\n    for res in results:\n        if not res or 'action' not in res:\n            # XXX Yarik has to no clue on how to track the origin of the\n            # record to figure out WTF, so he just skips it\n            continue\n\n        if PY2:\n            for k, v in res.items():\n                if isinstance(v, unicode):\n                    res[k] = v.encode('utf-8')\n\n        actsum = action_summary.get(res['action'], {})\n        if res['status']:\n            actsum[res['status']] = actsum.get(res['status'], 0) + 1\n            action_summary[res['action']] = actsum\n        ## log message, if a logger was given\n        # remove logger instance from results, as it is no longer useful\n        # after logging was done, it isn't serializable, and generally\n        # pollutes the output\n        res_lgr = res.pop('logger', None)\n        if isinstance(res_lgr, logging.Logger):\n            # didn't get a particular log function, go with default\n            res_lgr = getattr(res_lgr, default_logchannels[res['status']])\n        if res_lgr and 'message' in res:\n            msg = res['message']\n            msgargs = None\n            if isinstance(msg, tuple):\n                msgargs = msg[1:]\n                msg = msg[0]\n            if 'path' in res:\n                msg = '{} [{}({})]'.format(\n                    msg, res['action'], res['path'])\n            if msgargs:\n                # support string expansion of logging to avoid runtime cost\n                res_lgr(msg, *msgargs)\n            else:\n                res_lgr(msg)\n        ## error handling\n        # looks for error status, and report at the end via\n        # an exception\n        if on_failure in ('continue', 'stop') \\\n                and res['status'] in ('impossible', 'error'):\n            incomplete_results.append(res)\n            if on_failure == 'stop':\n                # first fail -> that's it\n                # raise will happen after the loop\n                break\n        if result_filter:\n            try:\n                if not result_filter(res):\n                    raise ValueError('excluded by filter')\n            except ValueError as e:\n                lgr.debug('not reporting result (%s)', exc_str(e))\n                continue\n        ## output rendering\n        # TODO RF this in a simple callable that gets passed into this function\n        if result_renderer is None or result_renderer == 'disabled':\n            pass\n        elif result_renderer == 'default':\n            default_result_renderer(res)\n        elif result_renderer in ('json', 'json_pp'):\n            ui.message(json.dumps(\n                {k: v for k, v in res.items()\n                 if k not in ('message', 'logger')},\n                sort_keys=True,\n                indent=2 if result_renderer.endswith('_pp') else None,\n                default=lambda x: str(x)))\n        elif result_renderer == 'tailored':\n            if hasattr(cmd_class, 'custom_result_renderer'):\n                cmd_class.custom_result_renderer(res, **kwargs)\n        elif hasattr(result_renderer, '__call__'):\n            try:\n                result_renderer(res, **kwargs)\n            except Exception as e:\n                lgr.warn('Result rendering failed for: %s [%s]',\n                         res, exc_str(e))\n        else:\n            raise ValueError('unknown result renderer \"{}\"'.format(result_renderer))\n\n        if PY2:\n            for k, v in res.items():\n                if isinstance(v, str):\n                    res[k] = v.decode('utf-8')\n\n        if result_xfm:\n            res = result_xfm(res)\n            if res is None:\n                continue\n        yield res\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\"\"\"Interface utility functions\n\n\"\"\"\n\n__docformat__ = 'restructuredtext'\n\nimport inspect\nimport logging\nimport wrapt\nimport sys\nimport re\nimport shlex\nfrom os import curdir\nfrom os import pardir\nfrom os import listdir\nfrom os.path import join as opj\nfrom os.path import isdir\nfrom os.path import relpath\nfrom os.path import sep\nfrom os.path import split as psplit\nfrom itertools import chain\nfrom six import PY2\n\nimport json\n\n# avoid import from API to not get into circular imports\nfrom datalad.utils import with_pathsep as _with_sep  # TODO: RF whenever merge conflict is not upon us\nfrom datalad.utils import path_startswith\nfrom datalad.utils import path_is_subpath\nfrom datalad.utils import assure_unicode\nfrom datalad.support.gitrepo import GitRepo\nfrom datalad.support.exceptions import IncompleteResultsError\nfrom datalad import cfg as dlcfg\nfrom datalad.dochelpers import exc_str\n\n\nfrom datalad.support.constraints import Constraint\n\nfrom datalad.ui import ui\nimport datalad.support.ansi_colors as ac\n\nfrom datalad.interface.base import Interface\nfrom datalad.interface.base import default_logchannels\nfrom datalad.interface.base import get_allargs_as_kwargs\nfrom datalad.interface.common_opts import eval_params\nfrom datalad.interface.common_opts import eval_defaults\nfrom .results import known_result_xfms\n\n\nlgr = logging.getLogger('datalad.interface.utils')\n\n\ndef cls2cmdlinename(cls):\n    \"Return the cmdline command name from an Interface class\"\n    r = re.compile(r'([a-z0-9])([A-Z])')\n    return r.sub('\\\\1-\\\\2', cls.__name__).lower()\n\n\n# TODO remove\n# only `drop` and `uninstall` are still using this\ndef handle_dirty_dataset(ds, mode, msg=None):\n    \"\"\"Detect and treat unsaved changes as instructed by `mode`\n\n    Parameters\n    ----------\n    ds : Dataset or None\n      Dataset to be inspected. Does nothing if `None`.\n    mode : {'fail', 'ignore', 'save-before'}\n      How to act upon discovering unsaved changes.\n    msg : str or None\n      Custom message to use for a potential commit.\n\n    Returns\n    -------\n    None\n    \"\"\"\n    if ds is None:\n        # nothing to be handled\n        return\n    if msg is None:\n        msg = '[DATALAD] auto-saved changes'\n\n    # make sure that all pending changes (batched annex operations, etc.)\n    # are actually reflected in Git\n    if ds.repo:\n        ds.repo.precommit()\n\n    if mode == 'ignore':\n        return\n    elif mode == 'fail':\n        if not ds.repo or ds.repo.is_dirty(index=True,\n                                           untracked_files=True,\n                                           submodules=True):\n            raise RuntimeError('dataset {} has unsaved changes'.format(ds))\n    elif mode == 'save-before':\n        if not ds.is_installed():\n            raise RuntimeError('dataset {} is not yet installed'.format(ds))\n        from datalad.interface.save import Save\n        Save.__call__(dataset=ds, message=msg)\n    else:\n        raise ValueError(\"unknown if-dirty mode '{}'\".format(mode))\n\n\ndef get_tree_roots(paths):\n    \"\"\"Return common root paths for a set of paths\n\n    This function determines the smallest set of common root\n    paths and sorts all given paths under the respective\n    root.\n\n    Returns\n    -------\n    dict\n      paths by root\n    \"\"\"\n    paths_ws = [_with_sep(p) for p in paths]\n    # sort all paths under their potential roots\n    roots = {}\n    # start from the top to get all paths down the line\n    # and collate them into as few roots as possible\n    for s in sorted(paths_ws):\n        if any([s.startswith(r) for r in roots]):\n            # this path is already covered by a known root\n            continue\n        # find all sub paths\n        subs = [p for p in paths if p.startswith(s)]\n        roots[s.rstrip(sep)] = subs\n    return roots\n\n\n# TODO remove\n# only `remove` and `uninstall` use this, the uses path `path_is_subpath`\ndef path_is_under(values, path=None):\n    \"\"\"Whether a given path is a subdirectory of any of the given test values\n\n    Parameters\n    ----------\n    values : sequence or dict\n      Paths to be tested against. This can be a dictionary in which case\n      all values from all keys will be tested against.\n    path : path or None\n      Test path. If None is given, the process' working directory is\n      used.\n\n    Returns\n    -------\n    bool\n    \"\"\"\n    if path is None:\n        from datalad.utils import getpwd\n        path = getpwd()\n    if isinstance(values, dict):\n        values = chain(*values.values())\n    for p in values:\n        rpath = relpath(p, start=path)\n        if rpath == curdir \\\n                or rpath == pardir \\\n                or set(psplit(rpath)) == {pardir}:\n            # first match is enough\n            return True\n    return False\n\n\ndef discover_dataset_trace_to_targets(basepath, targetpaths, current_trace,\n                                      spec, includeds=None):\n    \"\"\"Discover the edges and nodes in a dataset tree to given target paths\n\n    Parameters\n    ----------\n    basepath : path\n      Path to a start or top-level dataset. Really has to be a path to a\n      dataset!\n    targetpaths : list(path)\n      Any non-zero number of paths that are termination points for the\n      search algorithm. Can be paths to datasets, directories, or files\n      (and any combination thereof).\n    current_trace : list\n      For a top-level call this should probably always be `[]`\n    spec : dict\n      `content_by_ds`-style dictionary that will receive information about the\n      discovered datasets. Specifically, for each discovered dataset there\n      will be in item with its path under the key (path) of the respective\n      superdataset.\n    includeds : sequence, optional\n      Any paths given are treated as existing subdatasets, regardless of\n      whether they can be found in the filesystem. Such subdatasets will appear\n      under the key of the closest existing dataset in the `spec`.\n\n    Returns\n    -------\n    None\n      Function calls itself recursively and populates `spec` dict in-place.\n      Keys are dataset paths, values are sets of subdataset paths\n    \"\"\"\n    # convert to set for faster lookup\n    includeds = includeds if isinstance(includeds, set) else \\\n        set() if includeds is None else set(includeds)\n    # this beast walks the directory tree from a given `basepath` until\n    # it discovers any of the given `targetpaths`\n    # if it finds one, it commits any accummulated trace of visited\n    # datasets on this edge to the spec\n    valid_repo = GitRepo.is_valid_repo(basepath)\n    if valid_repo:\n        # we are passing into a new dataset, extend the dataset trace\n        current_trace = current_trace + [basepath]\n    # this edge is not done, we need to try to reach any downstream\n    # dataset\n    undiscovered_ds = set(t for t in targetpaths) # if t != basepath)\n    # whether anything in this directory matched a targetpath\n    filematch = False\n    if isdir(basepath):\n        for p in listdir(basepath):\n            p = assure_unicode(opj(basepath, p))\n            if not isdir(p):\n                if p in targetpaths:\n                    filematch = True\n                # we cannot have anything below this one\n                continue\n            # OPT listdir might be large and we could have only few items\n            # in `targetpaths` -- so traverse only those in spec which have\n            # leading dir basepath\n            # filter targets matching this downward path\n            downward_targets = set(\n                t for t in targetpaths if path_startswith(t, p))\n            if not downward_targets:\n                continue\n            # remove the matching ones from the \"todo\" list\n            undiscovered_ds.difference_update(downward_targets)\n            # go one deeper\n            discover_dataset_trace_to_targets(\n                p, downward_targets, current_trace, spec,\n                includeds=includeds if not includeds else includeds.intersection(\n                    downward_targets))\n    undiscovered_ds = [t for t in undiscovered_ds\n                       if includeds and\n                          path_is_subpath(t, current_trace[-1]) and\n                          t in includeds]\n    if filematch or basepath in targetpaths or undiscovered_ds:\n        for i, p in enumerate(current_trace[:-1]):\n            # TODO RF prepare proper annotated path dicts\n            subds = spec.get(p, set())\n            subds.add(current_trace[i + 1])\n            spec[p] = subds\n        if undiscovered_ds:\n            spec[current_trace[-1]] = spec.get(current_trace[-1], set()).union(\n                undiscovered_ds)\n\n\ndef eval_results(func):\n    \"\"\"Decorator for return value evaluation of datalad commands.\n\n    Note, this decorator is only compatible with commands that return\n    status dict sequences!\n\n    Two basic modes of operation are supported: 1) \"generator mode\" that\n    `yields` individual results, and 2) \"list mode\" that returns a sequence of\n    results. The behavior can be selected via the kwarg `return_type`.\n    Default is \"list mode\".\n\n    This decorator implements common functionality for result rendering/output,\n    error detection/handling, and logging.\n\n    Result rendering/output can be triggered via the\n    `datalad.api.result-renderer` configuration variable, or the\n    `result_renderer` keyword argument of each decorated command. Supported\n    modes are: 'default' (one line per result with action, status, path,\n    and an optional message); 'json' (one object per result, like git-annex),\n    'json_pp' (like 'json', but pretty-printed spanning multiple lines),\n    'tailored' custom output formatting provided by each command\n    class (if any).\n\n    Error detection works by inspecting the `status` item of all result\n    dictionaries. Any occurrence of a status other than 'ok' or 'notneeded'\n    will cause an IncompleteResultsError exception to be raised that carries\n    the failed actions' status dictionaries in its `failed` attribute.\n\n    Status messages will be logged automatically, by default the following\n    association of result status and log channel will be used: 'ok' (debug),\n    'notneeded' (debug), 'impossible' (warning), 'error' (error).  Logger\n    instances included in the results are used to capture the origin of a\n    status report.\n\n    Parameters\n    ----------\n    func: function\n      __call__ method of a subclass of Interface,\n      i.e. a datalad command definition\n    \"\"\"\n\n    @wrapt.decorator\n    def eval_func(wrapped, instance, args, kwargs):\n        # for result filters and pre/post procedures\n        # we need to produce a dict with argname/argvalue pairs for all args\n        # incl. defaults and args given as positionals\n        allkwargs = get_allargs_as_kwargs(wrapped, args, kwargs)\n        # determine class, the __call__ method of which we are decorating:\n        # Ben: Note, that this is a bit dirty in PY2 and imposes restrictions on\n        # when and how to use eval_results as well as on how to name a command's\n        # module and class. As of now, we are inline with these requirements as\n        # far as I'm aware.\n        mod = sys.modules[wrapped.__module__]\n        if PY2:\n            # we rely on:\n            # - decorated function is method of a subclass of Interface\n            # - the name of the class matches the last part of the module's name\n            #   if converted to lower\n            # for example:\n            # ..../where/ever/mycommand.py:\n            # class MyCommand(Interface):\n            #     @eval_results\n            #     def __call__(..)\n            command_class_names = \\\n                [i for i in mod.__dict__\n                 if type(mod.__dict__[i]) == type and\n                 issubclass(mod.__dict__[i], Interface) and\n                 i.lower().startswith(wrapped.__module__.split('.')[-1].replace('datalad_', '').replace('_', ''))]\n            assert len(command_class_names) == 1, (command_class_names, mod.__name__)\n            command_class_name = command_class_names[0]\n        else:\n            command_class_name = wrapped.__qualname__.split('.')[-2]\n        _func_class = mod.__dict__[command_class_name]\n        lgr.debug(\"Determined class of decorated function: %s\", _func_class)\n\n        # retrieve common options from kwargs, and fall back on the command\n        # class attributes, or general defaults if needed\n        kwargs = kwargs.copy()  # we will pop, which might cause side-effect\n        common_params = {\n            p_name: kwargs.pop(\n                p_name,\n                getattr(_func_class, p_name, eval_defaults[p_name]))\n            for p_name in eval_params}\n        # short cuts and configured setup for common options\n        on_failure = common_params['on_failure']\n        return_type = common_params['return_type']\n        # resolve string labels for transformers too\n        result_xfm = common_params['result_xfm']\n        if result_xfm in known_result_xfms:\n            result_xfm = known_result_xfms[result_xfm]\n        result_renderer = common_params['result_renderer']\n        # TODO remove this conditional branch entirely, done outside\n        if not result_renderer:\n            result_renderer = dlcfg.get('datalad.api.result-renderer', None)\n        # wrap the filter into a helper to be able to pass additional arguments\n        # if the filter supports it, but at the same time keep the required interface\n        # as minimal as possible. Also do this here, in order to avoid this test\n        # to be performed for each return value\n        result_filter = common_params['result_filter']\n        _result_filter = result_filter\n        if result_filter:\n            if isinstance(result_filter, Constraint):\n                _result_filter = result_filter.__call__\n            if (PY2 and inspect.getargspec(_result_filter).keywords) or \\\n                    (not PY2 and inspect.getfullargspec(_result_filter).varkw):\n\n                def _result_filter(res):\n                    return result_filter(res, **allkwargs)\n\n        def _get_procedure_specs(param_key=None, cfg_key=None, ds=None):\n            spec = common_params.get(param_key, None)\n            if spec is not None:\n                # this is already a list of lists\n                return spec\n\n            from datalad.distribution.dataset import Dataset\n            ds = ds if isinstance(ds, Dataset) else Dataset(ds) if ds else None\n            spec = (ds.config if ds and ds.is_installed()\n                    else dlcfg).get(cfg_key, None)\n            if spec is None:\n                return\n            elif not isinstance(spec, tuple):\n                spec = [spec]\n            return [shlex.split(s) for s in spec]\n\n        # query cfg for defaults\n        cmdline_name = cls2cmdlinename(_func_class)\n        dataset_arg = allkwargs.get('dataset', None)\n        proc_pre = _get_procedure_specs(\n            'proc_pre',\n            'datalad.{}.proc-pre'.format(cmdline_name),\n            ds=dataset_arg)\n        proc_post = _get_procedure_specs(\n            'proc_post',\n            'datalad.{}.proc-post'.format(cmdline_name),\n            ds=dataset_arg)\n\n        # this internal helper function actually drives the command\n        # generator-style, it may generate an exception if desired,\n        # on incomplete results\n        def generator_func(*_args, **_kwargs):\n            # flag whether to raise an exception\n            incomplete_results = []\n            # track what actions were performed how many times\n            action_summary = {}\n\n            if proc_pre and cmdline_name != 'run-procedure':\n                from datalad.interface.run_procedure import RunProcedure\n                for procspec in proc_pre:\n                    lgr.debug('Running configured pre-procedure %s', procspec)\n                    for r in _process_results(\n                            RunProcedure.__call__(\n                                procspec,\n                                dataset=dataset_arg,\n                                return_type='generator'),\n                            _func_class, action_summary,\n                            on_failure, incomplete_results,\n                            result_renderer, result_xfm, result_filter,\n                            **_kwargs):\n                        yield r\n\n            # if a custom summary is to be provided, collect the results\n            # of the command execution\n            results = []\n            do_custom_result_summary = result_renderer == 'tailored' \\\n                and hasattr(_func_class, 'custom_result_summary_renderer')\n\n            # process main results\n            for r in _process_results(\n                    wrapped(*_args, **_kwargs),\n                    _func_class, action_summary,\n                    on_failure, incomplete_results,\n                    result_renderer, result_xfm, _result_filter, **_kwargs):\n                yield r\n                # collect if summary is desired\n                if do_custom_result_summary:\n                    results.append(r)\n\n            if proc_post and cmdline_name != 'run-procedure':\n                from datalad.interface.run_procedure import RunProcedure\n                for procspec in proc_post:\n                    lgr.debug('Running configured post-procedure %s', procspec)\n                    for r in _process_results(\n                            RunProcedure.__call__(\n                                procspec,\n                                dataset=dataset_arg,\n                                return_type='generator'),\n                            _func_class, action_summary,\n                            on_failure, incomplete_results,\n                            result_renderer, result_xfm, result_filter,\n                            **_kwargs):\n                        yield r\n\n            # result summary before a potential exception\n            # custom first\n            if do_custom_result_summary:\n                _func_class.custom_result_summary_renderer(results)\n            elif result_renderer == 'default' and action_summary and \\\n                    sum(sum(s.values()) for s in action_summary.values()) > 1:\n                # give a summary in default mode, when there was more than one\n                # action performed\n                ui.message(\"action summary:\\n  {}\".format(\n                    '\\n  '.join('{} ({})'.format(\n                        act,\n                        ', '.join('{}: {}'.format(status, action_summary[act][status])\n                                  for status in sorted(action_summary[act])))\n                                for act in sorted(action_summary))))\n\n            if incomplete_results:\n                raise IncompleteResultsError(\n                    failed=incomplete_results,\n                    msg=\"Command did not complete successfully\")\n\n        if return_type == 'generator':\n            # hand over the generator\n            return generator_func(*args, **kwargs)\n        else:\n            @wrapt.decorator\n            def return_func(wrapped_, instance_, args_, kwargs_):\n                results = wrapped_(*args_, **kwargs_)\n                if inspect.isgenerator(results):\n                    # unwind generator if there is one, this actually runs\n                    # any processing\n                    results = list(results)\n                # render summaries\n                if not result_xfm and result_renderer == 'tailored':\n                    # cannot render transformed results\n                    if hasattr(_func_class, 'custom_result_summary_renderer'):\n                        _func_class.custom_result_summary_renderer(results)\n                if return_type == 'item-or-list' and \\\n                        len(results) < 2:\n                    return results[0] if results else None\n                else:\n                    return results\n\n            return return_func(generator_func)(*args, **kwargs)\n\n    return eval_func(func)\n\n\ndef default_result_renderer(res):\n    if res.get('status', None) != 'notneeded':\n        ui.message('{action}({status}): {path}{type}{msg}'.format(\n                action=ac.color_word(res['action'], ac.BOLD),\n                status=ac.color_status(res['status']),\n                path=relpath(res['path'],\n                             res['refds']) if res.get('refds', None) else res[\n                    'path'],\n                type=' ({})'.format(\n                        ac.color_word(res['type'], ac.MAGENTA)\n                ) if 'type' in res else '',\n                msg=' [{}]'.format(\n                        res['message'][0] % res['message'][1:]\n                        if isinstance(res['message'], tuple) else res[\n                            'message'])\n                if 'message' in res else ''))\n\n\ndef _process_results(\n        results, cmd_class,\n        action_summary, on_failure, incomplete_results,\n        result_renderer, result_xfm, result_filter, **kwargs):\n    # private helper pf @eval_results\n    # loop over results generated from some source and handle each\n    # of them according to the requested behavior (logging, rendering, ...)\n    for res in results:\n        if not res or 'action' not in res:\n            # XXX Yarik has to no clue on how to track the origin of the\n            # record to figure out WTF, so he just skips it\n            continue\n\n        if PY2:\n            for k, v in res.items():\n                if isinstance(v, unicode):\n                    res[k] = v.encode('utf-8')\n\n        actsum = action_summary.get(res['action'], {})\n        if res['status']:\n            actsum[res['status']] = actsum.get(res['status'], 0) + 1\n            action_summary[res['action']] = actsum\n        ## log message, if a logger was given\n        # remove logger instance from results, as it is no longer useful\n        # after logging was done, it isn't serializable, and generally\n        # pollutes the output\n        res_lgr = res.pop('logger', None)\n        if isinstance(res_lgr, logging.Logger):\n            # didn't get a particular log function, go with default\n            res_lgr = getattr(res_lgr, default_logchannels[res['status']])\n        if res_lgr and 'message' in res:\n            msg = res['message']\n            msgargs = None\n            if isinstance(msg, tuple):\n                msgargs = msg[1:]\n                msg = msg[0]\n            if 'path' in res:\n                msg = '{} [{}({})]'.format(\n                    msg, res['action'], res['path'])\n            if msgargs:\n                # support string expansion of logging to avoid runtime cost\n                res_lgr(msg, *msgargs)\n            else:\n                res_lgr(msg)\n        ## error handling\n        # looks for error status, and report at the end via\n        # an exception\n        if on_failure in ('continue', 'stop') \\\n                and res['status'] in ('impossible', 'error'):\n            incomplete_results.append(res)\n            if on_failure == 'stop':\n                # first fail -> that's it\n                # raise will happen after the loop\n                break\n        if result_filter:\n            try:\n                if not result_filter(res):\n                    raise ValueError('excluded by filter')\n            except ValueError as e:\n                lgr.debug('not reporting result (%s)', exc_str(e))\n                continue\n        ## output rendering\n        # TODO RF this in a simple callable that gets passed into this function\n        if result_renderer is None or result_renderer == 'disabled':\n            pass\n        elif result_renderer == 'default':\n            default_result_renderer(res)\n        elif result_renderer in ('json', 'json_pp'):\n            ui.message(json.dumps(\n                {k: v for k, v in res.items()\n                 if k not in ('message', 'logger')},\n                sort_keys=True,\n                indent=2 if result_renderer.endswith('_pp') else None,\n                default=lambda x: str(x)))\n        elif result_renderer == 'tailored':\n            if hasattr(cmd_class, 'custom_result_renderer'):\n                cmd_class.custom_result_renderer(res, **kwargs)\n        elif hasattr(result_renderer, '__call__'):\n            try:\n                result_renderer(res, **kwargs)\n            except Exception as e:\n                lgr.warn('Result rendering failed for: %s [%s]',\n                         res, exc_str(e))\n        else:\n            raise ValueError('unknown result renderer \"{}\"'.format(result_renderer))\n\n        if PY2:\n            for k, v in res.items():\n                if isinstance(v, str):\n                    res[k] = v.decode('utf-8')\n\n        if result_xfm:\n            res = result_xfm(res)\n            if res is None:\n                continue\n        yield res\n",
            "header": {
                "file": {
                    "path": "datalad/interface/utils.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "6018cde70",
                "new_commit_hash": "b9801812f",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/datalad/interface/utils.py"
            },
            "plus_file": {
                "path": "b/datalad/interface/utils.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 331,
                            "length": 6
                        },
                        "new_range": {
                            "start": 331,
                            "length": 7
                        },
                        "section": "def eval_results(func):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        # retrieve common options from kwargs, and fall back on the command",
                                "type": "context"
                            },
                            {
                                "content": "        # class attributes, or general defaults if needed",
                                "type": "context"
                            },
                            {
                                "content": "        kwargs = kwargs.copy()  # we will pop, which might cause side-effect",
                                "type": "added"
                            },
                            {
                                "content": "        common_params = {",
                                "type": "context"
                            },
                            {
                                "content": "            p_name: kwargs.pop(",
                                "type": "context"
                            },
                            {
                                "content": "                p_name,",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "datalad/interface/utils.py",
                            "type": "function",
                            "name": "eval_results",
                            "content": "def eval_results(func):\n    \"\"\"Decorator for return value evaluation of datalad commands.\n\n    Note, this decorator is only compatible with commands that return\n    status dict sequences!\n\n    Two basic modes of operation are supported: 1) \"generator mode\" that\n    `yields` individual results, and 2) \"list mode\" that returns a sequence of\n    results. The behavior can be selected via the kwarg `return_type`.\n    Default is \"list mode\".\n\n    This decorator implements common functionality for result rendering/output,\n    error detection/handling, and logging.\n\n    Result rendering/output can be triggered via the\n    `datalad.api.result-renderer` configuration variable, or the\n    `result_renderer` keyword argument of each decorated command. Supported\n    modes are: 'default' (one line per result with action, status, path,\n    and an optional message); 'json' (one object per result, like git-annex),\n    'json_pp' (like 'json', but pretty-printed spanning multiple lines),\n    'tailored' custom output formatting provided by each command\n    class (if any).\n\n    Error detection works by inspecting the `status` item of all result\n    dictionaries. Any occurrence of a status other than 'ok' or 'notneeded'\n    will cause an IncompleteResultsError exception to be raised that carries\n    the failed actions' status dictionaries in its `failed` attribute.\n\n    Status messages will be logged automatically, by default the following\n    association of result status and log channel will be used: 'ok' (debug),\n    'notneeded' (debug), 'impossible' (warning), 'error' (error).  Logger\n    instances included in the results are used to capture the origin of a\n    status report.\n\n    Parameters\n    ----------\n    func: function\n      __call__ method of a subclass of Interface,\n      i.e. a datalad command definition\n    \"\"\"\n\n    @wrapt.decorator\n    def eval_func(wrapped, instance, args, kwargs):\n        # for result filters and pre/post procedures\n        # we need to produce a dict with argname/argvalue pairs for all args\n        # incl. defaults and args given as positionals\n        allkwargs = get_allargs_as_kwargs(wrapped, args, kwargs)\n        # determine class, the __call__ method of which we are decorating:\n        # Ben: Note, that this is a bit dirty in PY2 and imposes restrictions on\n        # when and how to use eval_results as well as on how to name a command's\n        # module and class. As of now, we are inline with these requirements as\n        # far as I'm aware.\n        mod = sys.modules[wrapped.__module__]\n        if PY2:\n            # we rely on:\n            # - decorated function is method of a subclass of Interface\n            # - the name of the class matches the last part of the module's name\n            #   if converted to lower\n            # for example:\n            # ..../where/ever/mycommand.py:\n            # class MyCommand(Interface):\n            #     @eval_results\n            #     def __call__(..)\n            command_class_names = \\\n                [i for i in mod.__dict__\n                 if type(mod.__dict__[i]) == type and\n                 issubclass(mod.__dict__[i], Interface) and\n                 i.lower().startswith(wrapped.__module__.split('.')[-1].replace('datalad_', '').replace('_', ''))]\n            assert len(command_class_names) == 1, (command_class_names, mod.__name__)\n            command_class_name = command_class_names[0]\n        else:\n            command_class_name = wrapped.__qualname__.split('.')[-2]\n        _func_class = mod.__dict__[command_class_name]\n        lgr.debug(\"Determined class of decorated function: %s\", _func_class)\n\n        # retrieve common options from kwargs, and fall back on the command\n        # class attributes, or general defaults if needed\n        kwargs = kwargs.copy()  # we will pop, which might cause side-effect\n        common_params = {\n            p_name: kwargs.pop(\n                p_name,\n                getattr(_func_class, p_name, eval_defaults[p_name]))\n            for p_name in eval_params}\n        # short cuts and configured setup for common options\n        on_failure = common_params['on_failure']\n        return_type = common_params['return_type']\n        # resolve string labels for transformers too\n        result_xfm = common_params['result_xfm']\n        if result_xfm in known_result_xfms:\n            result_xfm = known_result_xfms[result_xfm]\n        result_renderer = common_params['result_renderer']\n        # TODO remove this conditional branch entirely, done outside\n        if not result_renderer:\n            result_renderer = dlcfg.get('datalad.api.result-renderer', None)\n        # wrap the filter into a helper to be able to pass additional arguments\n        # if the filter supports it, but at the same time keep the required interface\n        # as minimal as possible. Also do this here, in order to avoid this test\n        # to be performed for each return value\n        result_filter = common_params['result_filter']\n        _result_filter = result_filter\n        if result_filter:\n            if isinstance(result_filter, Constraint):\n                _result_filter = result_filter.__call__\n            if (PY2 and inspect.getargspec(_result_filter).keywords) or \\\n                    (not PY2 and inspect.getfullargspec(_result_filter).varkw):\n\n                def _result_filter(res):\n                    return result_filter(res, **allkwargs)\n\n        def _get_procedure_specs(param_key=None, cfg_key=None, ds=None):\n            spec = common_params.get(param_key, None)\n            if spec is not None:\n                # this is already a list of lists\n                return spec\n\n            from datalad.distribution.dataset import Dataset\n            ds = ds if isinstance(ds, Dataset) else Dataset(ds) if ds else None\n            spec = (ds.config if ds and ds.is_installed()\n                    else dlcfg).get(cfg_key, None)\n            if spec is None:\n                return\n            elif not isinstance(spec, tuple):\n                spec = [spec]\n            return [shlex.split(s) for s in spec]\n\n        # query cfg for defaults\n        cmdline_name = cls2cmdlinename(_func_class)\n        dataset_arg = allkwargs.get('dataset', None)\n        proc_pre = _get_procedure_specs(\n            'proc_pre',\n            'datalad.{}.proc-pre'.format(cmdline_name),\n            ds=dataset_arg)\n        proc_post = _get_procedure_specs(\n            'proc_post',\n            'datalad.{}.proc-post'.format(cmdline_name),\n            ds=dataset_arg)\n\n        # this internal helper function actually drives the command\n        # generator-style, it may generate an exception if desired,\n        # on incomplete results\n        def generator_func(*_args, **_kwargs):\n            # flag whether to raise an exception\n            incomplete_results = []\n            # track what actions were performed how many times\n            action_summary = {}\n\n            if proc_pre and cmdline_name != 'run-procedure':\n                from datalad.interface.run_procedure import RunProcedure\n                for procspec in proc_pre:\n                    lgr.debug('Running configured pre-procedure %s', procspec)\n                    for r in _process_results(\n                            RunProcedure.__call__(\n                                procspec,\n                                dataset=dataset_arg,\n                                return_type='generator'),\n                            _func_class, action_summary,\n                            on_failure, incomplete_results,\n                            result_renderer, result_xfm, result_filter,\n                            **_kwargs):\n                        yield r\n\n            # if a custom summary is to be provided, collect the results\n            # of the command execution\n            results = []\n            do_custom_result_summary = result_renderer == 'tailored' \\\n                and hasattr(_func_class, 'custom_result_summary_renderer')\n\n            # process main results\n            for r in _process_results(\n                    wrapped(*_args, **_kwargs),\n                    _func_class, action_summary,\n                    on_failure, incomplete_results,\n                    result_renderer, result_xfm, _result_filter, **_kwargs):\n                yield r\n                # collect if summary is desired\n                if do_custom_result_summary:\n                    results.append(r)\n\n            if proc_post and cmdline_name != 'run-procedure':\n                from datalad.interface.run_procedure import RunProcedure\n                for procspec in proc_post:\n                    lgr.debug('Running configured post-procedure %s', procspec)\n                    for r in _process_results(\n                            RunProcedure.__call__(\n                                procspec,\n                                dataset=dataset_arg,\n                                return_type='generator'),\n                            _func_class, action_summary,\n                            on_failure, incomplete_results,\n                            result_renderer, result_xfm, result_filter,\n                            **_kwargs):\n                        yield r\n\n            # result summary before a potential exception\n            # custom first\n            if do_custom_result_summary:\n                _func_class.custom_result_summary_renderer(results)\n            elif result_renderer == 'default' and action_summary and \\\n                    sum(sum(s.values()) for s in action_summary.values()) > 1:\n                # give a summary in default mode, when there was more than one\n                # action performed\n                ui.message(\"action summary:\\n  {}\".format(\n                    '\\n  '.join('{} ({})'.format(\n                        act,\n                        ', '.join('{}: {}'.format(status, action_summary[act][status])\n                                  for status in sorted(action_summary[act])))\n                                for act in sorted(action_summary))))\n\n            if incomplete_results:\n                raise IncompleteResultsError(\n                    failed=incomplete_results,\n                    msg=\"Command did not complete successfully\")\n\n        if return_type == 'generator':\n            # hand over the generator\n            return generator_func(*args, **kwargs)\n        else:\n            @wrapt.decorator\n            def return_func(wrapped_, instance_, args_, kwargs_):\n                results = wrapped_(*args_, **kwargs_)\n                if inspect.isgenerator(results):\n                    # unwind generator if there is one, this actually runs\n                    # any processing\n                    results = list(results)\n                # render summaries\n                if not result_xfm and result_renderer == 'tailored':\n                    # cannot render transformed results\n                    if hasattr(_func_class, 'custom_result_summary_renderer'):\n                        _func_class.custom_result_summary_renderer(results)\n                if return_type == 'item-or-list' and \\\n                        len(results) < 2:\n                    return results[0] if results else None\n                else:\n                    return results\n\n            return return_func(generator_func)(*args, **kwargs)\n\n    return eval_func(func)",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 257,
                            "end_lineno": 494,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "71d543ecd848698f62174cc2f7572952b7277982^",
    "new_commit_hash": "71d543ecd848698f62174cc2f7572952b7277982",
    "commit_message": "BF: do not cause a side-effect on kwargs in @eval_results (#3249)\n\nMerge pull request #3249 from yarikoptic/bf-eval-results-sideeffect",
    "commit_date": "2019-03-19T13:30:25-04:00",
    "metadata": {}
}
{
    "repo_name": "datalad",
    "new_commit_hash": "71d543ecd848698f62174cc2f7572952b7277982",
    "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\"\"\"Test interface.utils\n\n\"\"\"\n\nfrom datalad.tests.utils import known_failure_direct_mode\n\nimport os\nimport logging\nfrom os.path import join as opj\nfrom os.path import exists\nfrom nose.tools import assert_raises, assert_equal\nfrom datalad.tests.utils import with_tempfile, assert_not_equal\nfrom datalad.tests.utils import assert_true\nfrom datalad.tests.utils import assert_in\nfrom datalad.tests.utils import assert_not_in\nfrom datalad.tests.utils import assert_dict_equal\nfrom datalad.tests.utils import with_tree\nfrom datalad.tests.utils import ok_clean_git\nfrom datalad.tests.utils import ok_\nfrom datalad.tests.utils import slow\nfrom datalad.utils import swallow_logs\nfrom datalad.distribution.dataset import Dataset\nfrom datalad.distribution.dataset import datasetmethod\nfrom datalad.distribution.dataset import EnsureDataset\nfrom datalad.support.param import Parameter\nfrom datalad.support.constraints import EnsureStr\nfrom datalad.support.constraints import EnsureNone\nfrom datalad.support.constraints import EnsureKeyChoice\n\nfrom datalad.interface.base import Interface\nfrom datalad.interface.utils import eval_results\nfrom datalad.interface.utils import discover_dataset_trace_to_targets\nfrom datalad.interface.base import build_doc\nfrom datalad.interface.utils import handle_dirty_dataset\n\n\n__docformat__ = 'restructuredtext'\nlgr = logging.getLogger('datalad.interface.tests.test_utils')\n_dirty_modes = ('fail', 'ignore', 'save-before')\n\n\ndef _check_all_clean(ds, state):\n    assert state is not None\n    for mode in _dirty_modes:\n        # nothing wrong, nothing saved\n        handle_dirty_dataset(ds, mode)\n        assert_equal(state, ds.repo.get_hexsha())\n\n\ndef _check_auto_save(ds, orig_state):\n    handle_dirty_dataset(ds, 'ignore')\n    assert_raises(RuntimeError, handle_dirty_dataset, ds, 'fail')\n    handle_dirty_dataset(ds, 'save-before')\n    state = ds.repo.get_hexsha()\n    assert_not_equal(orig_state, state)\n    _check_all_clean(ds, state)\n    return state\n\n\n@with_tempfile(mkdir=True)\ndef test_dirty(path):\n    for mode in _dirty_modes:\n        # does nothing without a dataset\n        handle_dirty_dataset(None, mode)\n    # placeholder, but not yet created\n    ds = Dataset(path)\n    # unknown mode\n    assert_raises(ValueError, handle_dirty_dataset, ds, 'MADEUP')\n    # not yet created is very dirty\n    assert_raises(RuntimeError, handle_dirty_dataset, ds, 'fail')\n    handle_dirty_dataset(ds, 'ignore')\n    assert_raises(RuntimeError, handle_dirty_dataset, ds, 'save-before')\n    # should yield a clean repo\n    ds.create()\n    orig_state = ds.repo.get_hexsha()\n    _check_all_clean(ds, orig_state)\n    # tainted: untracked\n    with open(opj(ds.path, 'something'), 'w') as f:\n        f.write('some')\n    # we don't want to auto-add untracked files by saving (anymore)\n    assert_raises(AssertionError, _check_auto_save, ds, orig_state)\n    # tainted: staged\n    ds.repo.add('something', git=True)\n    orig_state = _check_auto_save(ds, orig_state)\n    # tainted: submodule\n    # not added to super on purpose!\n    subds = ds.create('subds')\n    _check_all_clean(subds, subds.repo.get_hexsha())\n    ok_clean_git(ds.path)\n    # subdataset must be added as a submodule!\n    assert_equal(ds.subdatasets(result_xfm='relpaths'), ['subds'])\n\n\ndemo_hierarchy = {\n    'a': {\n        'aa': {\n            'file_aa': 'file_aa'}},\n    'b': {\n        'ba': {\n            'file_ba': 'file_ba'},\n        'bb': {\n            'bba': {\n                'bbaa': {\n                    'file_bbaa': 'file_bbaa'}},\n            'file_bb': 'file_bb'}},\n    'c': {\n        'ca': {\n            'file_ca': 'file_ca'},\n        'file_c': 'file_c'},\n    'd': {\n        'da': {\n            'file_da': 'file_da'},\n        'db': {\n            'file_db': 'file_db'},\n        'file_d': 'file_d'},\n}\n\n\ndef make_demo_hierarchy_datasets(path, tree, parent=None):\n    if parent is None:\n        parent = Dataset(path).create(force=True)\n    for node, items in tree.items():\n        if isinstance(items, dict):\n            node_path = opj(path, node)\n            nodeds = Dataset(node_path).create(force=True)\n            make_demo_hierarchy_datasets(node_path, items, parent=nodeds)\n    return parent\n\n\n@slow  # 74.4509s\n@with_tree(demo_hierarchy)\n@known_failure_direct_mode  #FIXME\ndef test_save_hierarchy(path):\n    # this test doesn't use API`remove` to avoid circularities\n    ds = make_demo_hierarchy_datasets(path, demo_hierarchy)\n    ds.add('.', recursive=True)\n    ok_clean_git(ds.path)\n    ds_bb = Dataset(opj(ds.path, 'b', 'bb'))\n    ds_bba = Dataset(opj(ds_bb.path, 'bba'))\n    ds_bbaa = Dataset(opj(ds_bba.path, 'bbaa'))\n    # introduce a change at the lowest level\n    ds_bbaa.repo.remove('file_bbaa')\n    for d in (ds, ds_bb, ds_bba, ds_bbaa):\n        ok_(d.repo.dirty)\n    # need to give file specifically, otherwise it will simply just preserve\n    # staged changes\n    ds_bb.save(path=opj(ds_bbaa.path, 'file_bbaa'))\n    # it has saved all changes in the subtrees spanned\n    # by the given datasets, but nothing else\n    for d in (ds_bb, ds_bba, ds_bbaa):\n        ok_clean_git(d.path)\n    ok_(ds.repo.dirty)\n    # now with two modified repos\n    d = Dataset(opj(ds.path, 'd'))\n    da = Dataset(opj(d.path, 'da'))\n    da.repo.remove('file_da')\n    db = Dataset(opj(d.path, 'db'))\n    db.repo.remove('file_db')\n    # generator\n    d.save(recursive=True)\n    for d in (d, da, db):\n        ok_clean_git(d.path)\n    ok_(ds.repo.dirty)\n    # and now with files all over the place and saving\n    # all the way to the root\n    aa = Dataset(opj(ds.path, 'a', 'aa'))\n    aa.repo.remove('file_aa')\n    ba = Dataset(opj(ds.path, 'b', 'ba'))\n    ba.repo.remove('file_ba')\n    bb = Dataset(opj(ds.path, 'b', 'bb'))\n    bb.repo.remove('file_bb')\n    c = Dataset(opj(ds.path, 'c'))\n    c.repo.remove('file_c')\n    ca = Dataset(opj(ds.path, 'c', 'ca'))\n    ca.repo.remove('file_ca')\n    d = Dataset(opj(ds.path, 'd'))\n    d.repo.remove('file_d')\n    ds.save(\n        # append trailing slashes to the path to indicate that we want to\n        # have the staged content in the dataset saved, rather than only the\n        # subdataset state in the respective superds.\n        # an alternative would have been to pass `save` annotated paths of\n        # type {'path': dspath, 'process_content': True} for each dataset\n        # in question, but here we want to test how this would most likely\n        # by used from cmdline\n        path=[opj(p, '')\n               for p in (aa.path, ba.path, bb.path, c.path, ca.path, d.path)],\n        super_datasets=True)\n\n\n# Note: class name needs to match module's name\n@build_doc\nclass TestUtils(Interface):\n    \"\"\"TestUtil's fake command\"\"\"\n\n    _params_ = dict(\n        number=Parameter(\n            args=(\"-n\", \"--number\",),\n            doc=\"\"\"It's a number\"\"\",\n            constraints=EnsureStr() | EnsureNone()),\n        dataset=Parameter(\n            args=(\"-d\", \"--dataset\"),\n            doc=\"\"\"\"specify the dataset to update.  If\n            no dataset is given, an attempt is made to identify the dataset\n            based on the input and/or the current working directory\"\"\",\n            constraints=EnsureDataset() | EnsureNone()),)\n\n    @staticmethod\n    @datasetmethod(name='fake_command')\n    @eval_results\n    def __call__(number, dataset=None):\n\n        for i in range(number):\n            # this dict will need to have the minimum info required by\n            # eval_results\n            yield {'path': 'some', 'status': 'ok', 'somekey': i, 'action': 'off'}\n\n\ndef test_eval_results_plus_build_doc():\n\n    # test docs\n\n    # docstring was build already:\n    with swallow_logs(new_level=logging.DEBUG) as cml:\n        TestUtils().__call__(1)\n        assert_not_in(\"Building doc for\", cml.out)\n    # docstring accessible both ways:\n    doc1 = Dataset.fake_command.__doc__\n    doc2 = TestUtils().__call__.__doc__\n\n    # docstring was built from Test_Util's definition:\n    assert_equal(doc1, doc2)\n    assert_in(\"TestUtil's fake command\", doc1)\n    assert_in(\"Parameters\", doc1)\n    assert_in(\"It's a number\", doc1)\n\n    # docstring also contains eval_result's parameters:\n    assert_in(\"result_filter\", doc1)\n    assert_in(\"return_type\", doc1)\n    assert_in(\"list\", doc1)\n    assert_in(\"None\", doc1)\n    assert_in(\"return value behavior\", doc1)\n    assert_in(\"dictionary is passed\", doc1)\n\n    # test eval_results is able to determine the call, a method of which it is\n    # decorating:\n    with swallow_logs(new_level=logging.DEBUG) as cml:\n        Dataset('/does/not/matter').fake_command(3)\n        assert_in(\"Determined class of decorated function: {}\"\n                  \"\".format(TestUtils().__class__), cml.out)\n\n    # test results:\n    result = TestUtils().__call__(2)\n    assert_equal(len(list(result)), 2)\n    result = Dataset('/does/not/matter').fake_command(3)\n    assert_equal(len(list(result)), 3)\n\n    # test absent side-effect of popping eval_defaults\n    kwargs = dict(return_type='list')\n    TestUtils().__call__(2, **kwargs)\n    assert_equal(list(kwargs), ['return_type'])\n\n    # test signature:\n    from inspect import getargspec\n    assert_equal(getargspec(Dataset.fake_command)[0], ['number', 'dataset'])\n    assert_equal(getargspec(TestUtils.__call__)[0], ['number', 'dataset'])\n\n\ndef test_result_filter():\n    # ensure baseline without filtering\n    assert_equal(\n        [r['somekey'] for r in TestUtils().__call__(4)],\n        [0, 1, 2, 3])\n    # test two functionally equivalent ways to filter results\n    # 1. Constraint-based -- filter by exception\n    #    we have a full set of AND and OR operators for this\n    # 2. custom filer function -- filter by boolean return value\n    for filt in (\n            EnsureKeyChoice('somekey', (0, 2)),\n            lambda x: x['somekey'] in (0, 2)):\n        assert_equal(\n            [r['somekey'] for r in TestUtils().__call__(\n                4,\n                result_filter=filt)],\n            [0, 2])\n        # constraint returns full dict\n        assert_dict_equal(\n            TestUtils().__call__(\n                4,\n                result_filter=filt)[-1],\n            {'action': 'off', 'path': 'some', 'status': 'ok', 'somekey': 2})\n\n    # test more sophisticated filters that actually get to see the\n    # API call's kwargs\n    def greatfilter(res, **kwargs):\n        assert_equal(kwargs.get('dataset', 'bob'), 'awesome')\n        return True\n    TestUtils().__call__(4, dataset='awesome', result_filter=greatfilter)\n\n    def sadfilter(res, **kwargs):\n        assert_equal(kwargs.get('dataset', 'bob'), None)\n        return True\n    TestUtils().__call__(4, result_filter=sadfilter)\n\n\n@with_tree({k: v for k, v in demo_hierarchy.items() if k in ['a', 'd']})\n@with_tempfile(mkdir=True)\ndef test_discover_ds_trace(path, otherdir):\n    ds = make_demo_hierarchy_datasets(\n        path,\n        {k: v for k, v in demo_hierarchy.items() if k in ['a', 'd']})\n    a = opj(ds.path, 'a')\n    aa = opj(a, 'aa')\n    d = opj(ds.path, 'd')\n    db = opj(d, 'db')\n    # we have to check whether we get the correct hierarchy, as the test\n    # subject is also involved in this\n    assert_true(exists(opj(db, 'file_db')))\n    ds.add('.', recursive=True)\n    ok_clean_git(ds.path)\n    # now two datasets which are not available locally, but we\n    # know about them (e.g. from metadata)\n    dba = opj(db, 'sub', 'dba')\n    dbaa = opj(dba, 'subsub', 'dbaa')\n    for input, eds, goal in (\n            ([], None, {}),\n            ([ds.path], None, {}),\n            ([otherdir], None, {}),\n            ([opj(ds.path, 'nothere')], None, {}),\n            ([opj(d, 'nothere')], None, {}),\n            ([opj(db, 'nothere')], None, {}),\n            ([a], None,\n             {ds.path: set([a])}),\n            ([aa, a], None,\n             {ds.path: set([a]), a: set([aa])}),\n            ([db], None,\n             {ds.path: set([d]), d: set([db])}),\n            ([opj(db, 'file_db')], None,\n             {ds.path: set([d]), d: set([db])}),\n            # just a regular non-existing path\n            ([dba], None, {}),\n            # but if we inject this knowledge it must come back out\n            # as the child of the closest existing dataset\n            ([dba], [dba],\n             {ds.path: set([d]), d: set([db]), db: set([dba])}),\n            # regardless of the depth\n            ([dbaa], [dbaa],\n             {ds.path: set([d]), d: set([db]), db: set([dbaa])}),\n            ([dba, dbaa], [dba, dbaa],\n             {ds.path: set([d]), d: set([db]), db: set([dba, dbaa])}),\n            # we can simply add existing and non-existing datasets to the\n            # include list get the desired result\n            ([d, dba, dbaa], [d, dba, dbaa],\n             {ds.path: set([d]), d: set([db]), db: set([dba, dbaa])}),\n    ):\n        spec = {}\n        discover_dataset_trace_to_targets(ds.path, input, [], spec, includeds=eds)\n        assert_dict_equal(spec, goal)\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.11.3.dev80\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 20ms\nInstalled 25 packages in 4.72s\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/.tmpyoFHaf/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/.tmpyoFHaf/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/.tmpyoFHaf/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/.tmpyoFHaf/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/.tmpyoFHaf/lib/python3.9/site-packages/setuptools/build_meta.py\", line 320, in run_setup\n    exec(code, locals())\n  File \"<string>\", line 51, 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/.tmpebHDUU/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/.tmpebHDUU/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/.tmpebHDUU/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/.tmpebHDUU/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/.tmpebHDUU/lib/python3.9/site-packages/setuptools/build_meta.py\", line 320, in run_setup\n    exec(code, locals())\n  File \"<string>\", line 51, 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_71d543ecd848698f62174cc2f7572952b7277982/datalad/__init__.py\", line 43, in <module>\n    from datalad.cmd import GitRunner\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_71d543ecd848698f62174cc2f7572952b7277982/datalad/cmd.py\", line 32, in <module>\n    from .support import path as op\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_71d543ecd848698f62174cc2f7572952b7277982/datalad/support/path.py\", line 21, in <module>\n    from ..utils import (\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_71d543ecd848698f62174cc2f7572952b7277982/datalad/utils.py\", line 26, in <module>\n    import wrapt\nModuleNotFoundError: No module named 'wrapt'\nUsing CPython 3.7.9\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 26 packages in 183ms\nInstalled 26 packages in 4.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 60 packages in 2.16s\nPrepared 1 package in 1.03s\nInstalled 53 packages in 36ms\n + appdirs==1.4.4\n + beautifulsoup4==4.12.3\n + boto==2.49.0\n + certifi==2024.12.14\n + cffi==1.15.1\n + chardet==5.2.0\n + charset-normalizer==3.4.1\n + citeproc-py==0.6.0\n + cryptography==44.0.0\n + datalad==0.11.3 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_71d543ecd848698f62174cc2f7572952b7277982)\n + deprecated==1.2.15\n + duecredit==0.9.3\n + exifread==3.0.0\n + gitdb==4.0.12\n + gitpython==3.1.43\n + httpretty==1.1.4\n + humanize==4.6.0\n + idna==3.10\n + importlib-resources==5.12.0\n + iso8601==2.1.0\n + jaraco-classes==3.2.3\n + jeepney==0.8.0\n + jsmin==3.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==1.0.5\n + multidict==6.0.5\n + mutagen==1.47.0\n + nose==1.3.7\n + patool==1.12\n + pillow==9.5.0\n + pycparser==2.21\n + pygithub==2.3.0\n + pyjwt==2.8.0\n + pynacl==1.5.0\n + pyperclip==1.9.0\n + python-xmp-toolkit==2.0.2\n + pyyaml==6.0.1\n + requests==2.31.0\n + requests-ftp==0.3.1\n + secretstorage==3.3.3\n + simplejson==3.19.3\n + smmap==5.0.2\n + soupsieve==2.4.1\n + tqdm==4.67.1\n + urllib3==2.0.7\n + vcrpy==4.3.0\n + whoosh==2.7.4\n + wrapt==1.16.0\n + yarl==1.9.4\nResolved 94 packages in 193ms\nInstalled 31 packages in 141ms\n + alabaster==0.7.13\n + asv==0.6.4\n + asv-runner==0.2.1\n + babel==2.14.0\n + build==1.1.1\n + distlib==0.3.9\n + docutils==0.19\n + filelock==3.12.2\n + imagesize==1.4.1\n + jinja2==3.1.5\n + json5==0.9.16\n + markupsafe==2.1.5\n + nose-timer==1.0.1\n + platformdirs==4.0.0\n + psutil==6.1.1\n + pygments==2.17.2\n + pympler==1.1\n + pypandoc==1.14\n + pyproject-hooks==1.2.0\n + snowballstemmer==2.2.0\n + sphinx==5.3.0\n + sphinx-rtd-theme==2.0.0\n + sphinxcontrib-applehelp==1.0.2\n + sphinxcontrib-devhelp==1.0.2\n + sphinxcontrib-htmlhelp==2.0.0\n + sphinxcontrib-jquery==4.1\n + sphinxcontrib-jsmath==1.0.1\n + sphinxcontrib-qthelp==1.0.3\n + sphinxcontrib-serializinghtml==1.1.5\n + tabulate==0.9.0\n + virtualenv==20.26.6\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_71d543ecd848698f62174cc2f7572952b7277982\nplugins: cov-4.1.0\ncollected 5 items\n\nr2e_tests/test_1.py FF..E                                                [100%]\n\n==================================== ERRORS ====================================\n___________________ ERROR at setup of test_discover_ds_trace ___________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_71d543ecd848698f62174cc2f7572952b7277982/r2e_tests/test_1.py, line 314\n  @with_tree({k: v for k, v in demo_hierarchy.items() if k in ['a', 'd']})\n  @with_tempfile(mkdir=True)\n  def test_discover_ds_trace(path, otherdir):\nE       fixture 'otherdir' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_71d543ecd848698f62174cc2f7572952b7277982/r2e_tests/test_1.py:314\n=================================== FAILURES ===================================\n__________________________________ test_dirty __________________________________\n\narg = (), kw = {'path': '/tmp/tmp-page2annexrrsny4p4'}\nfilename = '/tmp/datalad_temp_test_dirtyzu9n5tgp'\n\n    @wraps(t)\n    def newfunc(*arg, **kw):\n        with make_tempfile(wrapped=t, **tkwargs) as filename:\n>           return t(*(arg + (filename,)), **kw)\nE           TypeError: test_dirty() got multiple values for argument 'path'\n\ndatalad/tests/utils.py:615: TypeError\n_____________________________ test_save_hierarchy ______________________________\n\narg = (), kw = {'path': '/tmp/tmp-page2annexokxnnyf3'}\ntkwargs_ = {'prefix': 'datalad_temp_tree_test_save_hierarchy'}\nd = '/tmp/datalad_temp_tree_test_save_hierarchyv2scqosb'\n\n    @wraps(t)\n    def newfunc(*arg, **kw):\n        tkwargs_ = get_tempfile_kwargs(tkwargs, prefix=\"tree\", wrapped=t)\n        d = tempfile.mkdtemp(**tkwargs_)\n        create_tree(d, tree, archives_leading_dir=archives_leading_dir)\n        try:\n>           return t(*(arg + (d,)), **kw)\nE           TypeError: test_save_hierarchy() got multiple values for argument 'path'\n\ndatalad/tests/utils.py:442: TypeError\n==================================== PASSES ====================================\n_______________________ test_eval_results_plus_build_doc _______________________\n----------------------------- Captured stderr call -----------------------------\n[DEBUG] Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'> \n[DEBUG] Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'> \n[DEBUG] Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'> \n------------------------------ Captured log call -------------------------------\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\n______________________________ test_result_filter ______________________________\n----------------------------- Captured stderr call -----------------------------\n[DEBUG] Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'> \n[DEBUG] Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'> \n[DEBUG] not reporting result (value is not one of (0, 2) [constraints.py:__call__:266]) \n[DEBUG] not reporting result (value is not one of (0, 2) [constraints.py:__call__:266]) \n[DEBUG] Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'> \n[DEBUG] not reporting result (value is not one of (0, 2) [constraints.py:__call__:266]) \n[DEBUG] not reporting result (value is not one of (0, 2) [constraints.py:__call__:266]) \n[DEBUG] Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'> \n[DEBUG] not reporting result (excluded by filter [utils.py:_process_results:572]) \n[DEBUG] not reporting result (excluded by filter [utils.py:_process_results:572]) \n[DEBUG] Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'> \n[DEBUG] not reporting result (excluded by filter [utils.py:_process_results:572]) \n[DEBUG] not reporting result (excluded by filter [utils.py:_process_results:572]) \n[DEBUG] Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'> \n[DEBUG] Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'> \n------------------------------ Captured log call -------------------------------\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\nDEBUG    datalad.interface.utils:utils.py:574 not reporting result (value is not one of (0, 2) [constraints.py:__call__:266])\nDEBUG    datalad.interface.utils:utils.py:574 not reporting result (value is not one of (0, 2) [constraints.py:__call__:266])\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\nDEBUG    datalad.interface.utils:utils.py:574 not reporting result (value is not one of (0, 2) [constraints.py:__call__:266])\nDEBUG    datalad.interface.utils:utils.py:574 not reporting result (value is not one of (0, 2) [constraints.py:__call__:266])\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\nDEBUG    datalad.interface.utils:utils.py:574 not reporting result (excluded by filter [utils.py:_process_results:572])\nDEBUG    datalad.interface.utils:utils.py:574 not reporting result (excluded by filter [utils.py:_process_results:572])\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\nDEBUG    datalad.interface.utils:utils.py:574 not reporting result (excluded by filter [utils.py:_process_results:572])\nDEBUG    datalad.interface.utils:utils.py:574 not reporting result (excluded by filter [utils.py:_process_results:572])\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::test_eval_results_plus_build_doc\nPASSED r2e_tests/test_1.py::test_result_filter\nERROR r2e_tests/test_1.py::test_discover_ds_trace\nFAILED r2e_tests/test_1.py::test_dirty - TypeError: test_dirty() got multiple...\nFAILED r2e_tests/test_1.py::test_save_hierarchy - TypeError: test_save_hierar...\n===================== 2 failed, 2 passed, 1 error in 0.82s =====================\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_71d543ecd848698f62174cc2f7572952b7277982\nplugins: cov-4.1.0\ncollected 5 items\n\nr2e_tests/test_1.py FFF.E                                                [100%]\n\n==================================== ERRORS ====================================\n___________________ ERROR at setup of test_discover_ds_trace ___________________\nfile /home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_71d543ecd848698f62174cc2f7572952b7277982/r2e_tests/test_1.py, line 314\n  @with_tree({k: v for k, v in demo_hierarchy.items() if k in ['a', 'd']})\n  @with_tempfile(mkdir=True)\n  def test_discover_ds_trace(path, otherdir):\nE       fixture 'otherdir' not found\n>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, path, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, setup_git_config, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n>       use 'pytest --fixtures [testpath]' for help on them.\n\n/home/gcpuser/buckets/local_repoeval_bucket/repos/datalad_71d543ecd848698f62174cc2f7572952b7277982/r2e_tests/test_1.py:314\n=================================== FAILURES ===================================\n__________________________________ test_dirty __________________________________\n\narg = (), kw = {'path': '/tmp/tmp-page2annexmjjzxzld'}\nfilename = '/tmp/datalad_temp_test_dirty511f0j0v'\n\n    @wraps(t)\n    def newfunc(*arg, **kw):\n        with make_tempfile(wrapped=t, **tkwargs) as filename:\n>           return t(*(arg + (filename,)), **kw)\nE           TypeError: test_dirty() got multiple values for argument 'path'\n\ndatalad/tests/utils.py:615: TypeError\n_____________________________ test_save_hierarchy ______________________________\n\narg = (), kw = {'path': '/tmp/tmp-page2annexxnq5w5tl'}\ntkwargs_ = {'prefix': 'datalad_temp_tree_test_save_hierarchy'}\nd = '/tmp/datalad_temp_tree_test_save_hierarchy39lde90k'\n\n    @wraps(t)\n    def newfunc(*arg, **kw):\n        tkwargs_ = get_tempfile_kwargs(tkwargs, prefix=\"tree\", wrapped=t)\n        d = tempfile.mkdtemp(**tkwargs_)\n        create_tree(d, tree, archives_leading_dir=archives_leading_dir)\n        try:\n>           return t(*(arg + (d,)), **kw)\nE           TypeError: test_save_hierarchy() got multiple values for argument 'path'\n\ndatalad/tests/utils.py:442: TypeError\n_______________________ test_eval_results_plus_build_doc _______________________\n\n    def test_eval_results_plus_build_doc():\n    \n        # test docs\n    \n        # docstring was build already:\n        with swallow_logs(new_level=logging.DEBUG) as cml:\n            TestUtils().__call__(1)\n            assert_not_in(\"Building doc for\", cml.out)\n        # docstring accessible both ways:\n        doc1 = Dataset.fake_command.__doc__\n        doc2 = TestUtils().__call__.__doc__\n    \n        # docstring was built from Test_Util's definition:\n        assert_equal(doc1, doc2)\n        assert_in(\"TestUtil's fake command\", doc1)\n        assert_in(\"Parameters\", doc1)\n        assert_in(\"It's a number\", doc1)\n    \n        # docstring also contains eval_result's parameters:\n        assert_in(\"result_filter\", doc1)\n        assert_in(\"return_type\", doc1)\n        assert_in(\"list\", doc1)\n        assert_in(\"None\", doc1)\n        assert_in(\"return value behavior\", doc1)\n        assert_in(\"dictionary is passed\", doc1)\n    \n        # test eval_results is able to determine the call, a method of which it is\n        # decorating:\n        with swallow_logs(new_level=logging.DEBUG) as cml:\n            Dataset('/does/not/matter').fake_command(3)\n            assert_in(\"Determined class of decorated function: {}\"\n                      \"\".format(TestUtils().__class__), cml.out)\n    \n        # test results:\n        result = TestUtils().__call__(2)\n        assert_equal(len(list(result)), 2)\n        result = Dataset('/does/not/matter').fake_command(3)\n        assert_equal(len(list(result)), 3)\n    \n        # test absent side-effect of popping eval_defaults\n        kwargs = dict(return_type='list')\n        TestUtils().__call__(2, **kwargs)\n>       assert_equal(list(kwargs), ['return_type'])\n\nr2e_tests/test_1.py:269: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/unittest/case.py:852: in assertEqual\n    assertion_func(first, second, msg=msg)\n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/unittest/case.py:1058: in assertListEqual\n    self.assertSequenceEqual(list1, list2, msg, seq_type=list)\n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/unittest/case.py:1040: in assertSequenceEqual\n    self.fail(msg)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <nose.tools.trivial.Dummy testMethod=nop>\nmsg = \"Lists differ: [] != ['return_type']\\n\\nSecond list contains 1 additional elements.\\nFirst extra element 0:\\n'return_type'\\n\\n- []\\n+ ['return_type']\"\n\n    def fail(self, msg=None):\n        \"\"\"Fail immediately, with the given message.\"\"\"\n>       raise self.failureException(msg)\nE       AssertionError: Lists differ: [] != ['return_type']\nE       \nE       Second list contains 1 additional elements.\nE       First extra element 0:\nE       'return_type'\nE       \nE       - []\nE       + ['return_type']\n\n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/unittest/case.py:693: AssertionError\n----------------------------- Captured stderr call -----------------------------\n[DEBUG] Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'> \n[DEBUG] Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'> \n[DEBUG] Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'> \n------------------------------ Captured log call -------------------------------\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\n==================================== PASSES ====================================\n______________________________ test_result_filter ______________________________\n----------------------------- Captured stderr call -----------------------------\n[DEBUG] Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'> \n[DEBUG] Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'> \n[DEBUG] not reporting result (value is not one of (0, 2) [constraints.py:__call__:266]) \n[DEBUG] not reporting result (value is not one of (0, 2) [constraints.py:__call__:266]) \n[DEBUG] Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'> \n[DEBUG] not reporting result (value is not one of (0, 2) [constraints.py:__call__:266]) \n[DEBUG] not reporting result (value is not one of (0, 2) [constraints.py:__call__:266]) \n[DEBUG] Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'> \n[DEBUG] not reporting result (excluded by filter [utils.py:_process_results:571]) \n[DEBUG] not reporting result (excluded by filter [utils.py:_process_results:571]) \n[DEBUG] Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'> \n[DEBUG] not reporting result (excluded by filter [utils.py:_process_results:571]) \n[DEBUG] not reporting result (excluded by filter [utils.py:_process_results:571]) \n[DEBUG] Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'> \n[DEBUG] Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'> \n------------------------------ Captured log call -------------------------------\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\nDEBUG    datalad.interface.utils:utils.py:573 not reporting result (value is not one of (0, 2) [constraints.py:__call__:266])\nDEBUG    datalad.interface.utils:utils.py:573 not reporting result (value is not one of (0, 2) [constraints.py:__call__:266])\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\nDEBUG    datalad.interface.utils:utils.py:573 not reporting result (value is not one of (0, 2) [constraints.py:__call__:266])\nDEBUG    datalad.interface.utils:utils.py:573 not reporting result (value is not one of (0, 2) [constraints.py:__call__:266])\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\nDEBUG    datalad.interface.utils:utils.py:573 not reporting result (excluded by filter [utils.py:_process_results:571])\nDEBUG    datalad.interface.utils:utils.py:573 not reporting result (excluded by filter [utils.py:_process_results:571])\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\nDEBUG    datalad.interface.utils:utils.py:573 not reporting result (excluded by filter [utils.py:_process_results:571])\nDEBUG    datalad.interface.utils:utils.py:573 not reporting result (excluded by filter [utils.py:_process_results:571])\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\nDEBUG    datalad.interface.utils:utils.py:330 Determined class of decorated function: <class 'r2e_tests.test_1.TestUtils'>\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::test_result_filter\nERROR r2e_tests/test_1.py::test_discover_ds_trace\nFAILED r2e_tests/test_1.py::test_dirty - TypeError: test_dirty() got multiple...\nFAILED r2e_tests/test_1.py::test_save_hierarchy - TypeError: test_save_hierar...\nFAILED r2e_tests/test_1.py::test_eval_results_plus_build_doc - AssertionError...\n===================== 3 failed, 1 passed, 1 error in 0.65s =====================\n",
    "old_commit_res_stderr": ""
}
datalad/interface/tests/test_utils.py datalad/interface/utils.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Unexpected Modification of `kwargs` When Using `@eval_results` Decorator

**Description**
When using the `@eval_results` decorator on a function, the original `kwargs` are unexpectedly modified. This side-effect occurs because the decorator alters the `kwargs` by popping certain keys, which leads to unintended behavior in subsequent code that relies on the original `kwargs`.

**Example Code:**
```python
@eval_results
def sample_function(number, dataset, **kwargs):
    # Function implementation
    pass

# Original kwargs
kwargs = {'return_type': 'list'}

# Calling the decorated function
sample_function(2, Dataset('/example/path'), **kwargs)

# After the call, kwargs is unexpectedly modified
print(kwargs)  # Expected: {'return_type': 'list'}
               # Actual: {}
```

**Expected Behavior**
The `kwargs` passed to the decorated function should remain unchanged after the function call. Modifying `kwargs` within the decorator should not affect the original dictionary outside the function.

**Actual Behavior**
After invoking the decorated function, the original `kwargs` dictionary is altered by removing keys that were popped inside the decorator. This unintended modification leads to discrepancies in the expected values of `kwargs`, causing tests that rely on the original `kwargs` to fail.

[/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/interface/utils.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.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""Interface utility functions

"""

__docformat__ = 'restructuredtext'

import inspect
import logging
import wrapt
import sys
import re
import shlex
from os import curdir
from os import pardir
from os import listdir
from os.path import join as opj
from os.path import isdir
from os.path import relpath
from os.path import sep
from os.path import split as psplit
from itertools import chain
from six import PY2

import json

# avoid import from API to not get into circular imports
from datalad.utils import with_pathsep as _with_sep  # TODO: RF whenever merge conflict is not upon us
from datalad.utils import path_startswith
from datalad.utils import path_is_subpath
from datalad.utils import assure_unicode
from datalad.support.gitrepo import GitRepo
from datalad.support.exceptions import IncompleteResultsError
from datalad import cfg as dlcfg
from datalad.dochelpers import exc_str


from datalad.support.constraints import Constraint

from datalad.ui import ui
import datalad.support.ansi_colors as ac

from datalad.interface.base import Interface
from datalad.interface.base import default_logchannels
from datalad.interface.base import get_allargs_as_kwargs
from datalad.interface.common_opts import eval_params
from datalad.interface.common_opts import eval_defaults
from .results import known_result_xfms


lgr = logging.getLogger('datalad.interface.utils')


def cls2cmdlinename(cls):
    "Return the cmdline command name from an Interface class"
    r = re.compile(r'([a-z0-9])([A-Z])')
    return r.sub('\\1-\\2', cls.__name__).lower()


# TODO remove
# only `drop` and `uninstall` are still using this
def handle_dirty_dataset(ds, mode, msg=None):
    """Detect and treat unsaved changes as instructed by `mode`

    Parameters
    ----------
    ds : Dataset or None
      Dataset to be inspected. Does nothing if `None`.
    mode : {'fail', 'ignore', 'save-before'}
      How to act upon discovering unsaved changes.
    msg : str or None
      Custom message to use for a potential commit.

    Returns
    -------
    None
    """
    if ds is None:
        # nothing to be handled
        return
    if msg is None:
        msg = '[DATALAD] auto-saved changes'

    # make sure that all pending changes (batched annex operations, etc.)
    # are actually reflected in Git
    if ds.repo:
        ds.repo.precommit()

    if mode == 'ignore':
        return
    elif mode == 'fail':
        if not ds.repo or ds.repo.is_dirty(index=True,
                                           untracked_files=True,
                                           submodules=True):
            raise RuntimeError('dataset {} has unsaved changes'.format(ds))
    elif mode == 'save-before':
        if not ds.is_installed():
            raise RuntimeError('dataset {} is not yet installed'.format(ds))
        from datalad.interface.save import Save
        Save.__call__(dataset=ds, message=msg)
    else:
        raise ValueError("unknown if-dirty mode '{}'".format(mode))


def get_tree_roots(paths):
    """Return common root paths for a set of paths

    This function determines the smallest set of common root
    paths and sorts all given paths under the respective
    root.

    Returns
    -------
    dict
      paths by root
    """
    paths_ws = [_with_sep(p) for p in paths]
    # sort all paths under their potential roots
    roots = {}
    # start from the top to get all paths down the line
    # and collate them into as few roots as possible
    for s in sorted(paths_ws):
        if any([s.startswith(r) for r in roots]):
            # this path is already covered by a known root
            continue
        # find all sub paths
        subs = [p for p in paths if p.startswith(s)]
        roots[s.rstrip(sep)] = subs
    return roots


# TODO remove
# only `remove` and `uninstall` use this, the uses path `path_is_subpath`
def path_is_under(values, path=None):
    """Whether a given path is a subdirectory of any of the given test values

    Parameters
    ----------
    values : sequence or dict
      Paths to be tested against. This can be a dictionary in which case
      all values from all keys will be tested against.
    path : path or None
      Test path. If None is given, the process' working directory is
      used.

    Returns
    -------
    bool
    """
    if path is None:
        from datalad.utils import getpwd
        path = getpwd()
    if isinstance(values, dict):
        values = chain(*values.values())
    for p in values:
        rpath = relpath(p, start=path)
        if rpath == curdir \
                or rpath == pardir \
                or set(psplit(rpath)) == {pardir}:
            # first match is enough
            return True
    return False


def discover_dataset_trace_to_targets(basepath, targetpaths, current_trace,
                                      spec, includeds=None):
    """Discover the edges and nodes in a dataset tree to given target paths

    Parameters
    ----------
    basepath : path
      Path to a start or top-level dataset. Really has to be a path to a
      dataset!
    targetpaths : list(path)
      Any non-zero number of paths that are termination points for the
      search algorithm. Can be paths to datasets, directories, or files
      (and any combination thereof).
    current_trace : list
      For a top-level call this should probably always be `[]`
    spec : dict
      `content_by_ds`-style dictionary that will receive information about the
      discovered datasets. Specifically, for each discovered dataset there
      will be in item with its path under the key (path) of the respective
      superdataset.
    includeds : sequence, optional
      Any paths given are treated as existing subdatasets, regardless of
      whether they can be found in the filesystem. Such subdatasets will appear
      under the key of the closest existing dataset in the `spec`.

    Returns
    -------
    None
      Function calls itself recursively and populates `spec` dict in-place.
      Keys are dataset paths, values are sets of subdataset paths
    """
    # convert to set for faster lookup
    includeds = includeds if isinstance(includeds, set) else \
        set() if includeds is None else set(includeds)
    # this beast walks the directory tree from a given `basepath` until
    # it discovers any of the given `targetpaths`
    # if it finds one, it commits any accummulated trace of visited
    # datasets on this edge to the spec
    valid_repo = GitRepo.is_valid_repo(basepath)
    if valid_repo:
        # we are passing into a new dataset, extend the dataset trace
        current_trace = current_trace + [basepath]
    # this edge is not done, we need to try to reach any downstream
    # dataset
    undiscovered_ds = set(t for t in targetpaths) # if t != basepath)
    # whether anything in this directory matched a targetpath
    filematch = False
    if isdir(basepath):
        for p in listdir(basepath):
            p = assure_unicode(opj(basepath, p))
            if not isdir(p):
                if p in targetpaths:
                    filematch = True
                # we cannot have anything below this one
                continue
            # OPT listdir might be large and we could have only few items
            # in `targetpaths` -- so traverse only those in spec which have
            # leading dir basepath
            # filter targets matching this downward path
            downward_targets = set(
                t for t in targetpaths if path_startswith(t, p))
            if not downward_targets:
                continue
            # remove the matching ones from the "todo" list
            undiscovered_ds.difference_update(downward_targets)
            # go one deeper
            discover_dataset_trace_to_targets(
                p, downward_targets, current_trace, spec,
                includeds=includeds if not includeds else includeds.intersection(
                    downward_targets))
    undiscovered_ds = [t for t in undiscovered_ds
                       if includeds and
                          path_is_subpath(t, current_trace[-1]) and
                          t in includeds]
    if filematch or basepath in targetpaths or undiscovered_ds:
        for i, p in enumerate(current_trace[:-1]):
            # TODO RF prepare proper annotated path dicts
            subds = spec.get(p, set())
            subds.add(current_trace[i + 1])
            spec[p] = subds
        if undiscovered_ds:
            spec[current_trace[-1]] = spec.get(current_trace[-1], set()).union(
                undiscovered_ds)


def eval_results(func):
    """Decorator for return value evaluation of datalad commands.

    Note, this decorator is only compatible with commands that return
    status dict sequences!

    Two basic modes of operation are supported: 1) "generator mode" that
    `yields` individual results, and 2) "list mode" that returns a sequence of
    results. The behavior can be selected via the kwarg `return_type`.
    Default is "list mode".

    This decorator implements common functionality for result rendering/output,
    error detection/handling, and logging.

    Result rendering/output can be triggered via the
    `datalad.api.result-renderer` configuration variable, or the
    `result_renderer` keyword argument of each decorated command. Supported
    modes are: 'default' (one line per result with action, status, path,
    and an optional message); 'json' (one object per result, like git-annex),
    'json_pp' (like 'json', but pretty-printed spanning multiple lines),
    'tailored' custom output formatting provided by each command
    class (if any).

    Error detection works by inspecting the `status` item of all result
    dictionaries. Any occurrence of a status other than 'ok' or 'notneeded'
    will cause an IncompleteResultsError exception to be raised that carries
    the failed actions' status dictionaries in its `failed` attribute.

    Status messages will be logged automatically, by default the following
    association of result status and log channel will be used: 'ok' (debug),
    'notneeded' (debug), 'impossible' (warning), 'error' (error).  Logger
    instances included in the results are used to capture the origin of a
    status report.

    Parameters
    ----------
    func: function
      __call__ method of a subclass of Interface,
      i.e. a datalad command definition
    """

    @wrapt.decorator
    def eval_func(wrapped, instance, args, kwargs):
        # for result filters and pre/post procedures
        # we need to produce a dict with argname/argvalue pairs for all args
        # incl. defaults and args given as positionals
        allkwargs = get_allargs_as_kwargs(wrapped, args, kwargs)
        # determine class, the __call__ method of which we are decorating:
        # Ben: Note, that this is a bit dirty in PY2 and imposes restrictions on
        # when and how to use eval_results as well as on how to name a command's
        # module and class. As of now, we are inline with these requirements as
        # far as I'm aware.
        mod = sys.modules[wrapped.__module__]
        if PY2:
            # we rely on:
            # - decorated function is method of a subclass of Interface
            # - the name of the class matches the last part of the module's name
            #   if converted to lower
            # for example:
            # ..../where/ever/mycommand.py:
            # class MyCommand(Interface):
            #     @eval_results
            #     def __call__(..)
            command_class_names = \
                [i for i in mod.__dict__
                 if type(mod.__dict__[i]) == type and
                 issubclass(mod.__dict__[i], Interface) and
                 i.lower().startswith(wrapped.__module__.split('.')[-1].replace('datalad_', '').replace('_', ''))]
            assert len(command_class_names) == 1, (command_class_names, mod.__name__)
            command_class_name = command_class_names[0]
        else:
            command_class_name = wrapped.__qualname__.split('.')[-2]
        _func_class = mod.__dict__[command_class_name]
        lgr.debug("Determined class of decorated function: %s", _func_class)

        # retrieve common options from kwargs, and fall back on the command
        # class attributes, or general defaults if needed
        common_params = {
            p_name: kwargs.pop(
                p_name,
                getattr(_func_class, p_name, eval_defaults[p_name]))
            for p_name in eval_params}
        # short cuts and configured setup for common options
        on_failure = common_params['on_failure']
        return_type = common_params['return_type']
        # resolve string labels for transformers too
        result_xfm = common_params['result_xfm']
        if result_xfm in known_result_xfms:
            result_xfm = known_result_xfms[result_xfm]
        result_renderer = common_params['result_renderer']
        # TODO remove this conditional branch entirely, done outside
        if not result_renderer:
            result_renderer = dlcfg.get('datalad.api.result-renderer', None)
        # wrap the filter into a helper to be able to pass additional arguments
        # if the filter supports it, but at the same time keep the required interface
        # as minimal as possible. Also do this here, in order to avoid this test
        # to be performed for each return value
        result_filter = common_params['result_filter']
        _result_filter = result_filter
        if result_filter:
            if isinstance(result_filter, Constraint):
                _result_filter = result_filter.__call__
            if (PY2 and inspect.getargspec(_result_filter).keywords) or \
                    (not PY2 and inspect.getfullargspec(_result_filter).varkw):

                def _result_filter(res):
                    return result_filter(res, **allkwargs)

        def _get_procedure_specs(param_key=None, cfg_key=None, ds=None):
            spec = common_params.get(param_key, None)
            if spec is not None:
                # this is already a list of lists
                return spec

            from datalad.distribution.dataset import Dataset
            ds = ds if isinstance(ds, Dataset) else Dataset(ds) if ds else None
            spec = (ds.config if ds and ds.is_installed()
                    else dlcfg).get(cfg_key, None)
            if spec is None:
                return
            elif not isinstance(spec, tuple):
                spec = [spec]
            return [shlex.split(s) for s in spec]

        # query cfg for defaults
        cmdline_name = cls2cmdlinename(_func_class)
        dataset_arg = allkwargs.get('dataset', None)
        proc_pre = _get_procedure_specs(
            'proc_pre',
            'datalad.{}.proc-pre'.format(cmdline_name),
            ds=dataset_arg)
        proc_post = _get_procedure_specs(
            'proc_post',
            'datalad.{}.proc-post'.format(cmdline_name),
            ds=dataset_arg)

        # this internal helper function actually drives the command
        # generator-style, it may generate an exception if desired,
        # on incomplete results
        def generator_func(*_args, **_kwargs):
            # flag whether to raise an exception
            incomplete_results = []
            # track what actions were performed how many times
            action_summary = {}

            if proc_pre and cmdline_name != 'run-procedure':
                from datalad.interface.run_procedure import RunProcedure
                for procspec in proc_pre:
                    lgr.debug('Running configured pre-procedure %s', procspec)
                    for r in _process_results(
                            RunProcedure.__call__(
                                procspec,
                                dataset=dataset_arg,
                                return_type='generator'),
                            _func_class, action_summary,
                            on_failure, incomplete_results,
                            result_renderer, result_xfm, result_filter,
                            **_kwargs):
                        yield r

            # if a custom summary is to be provided, collect the results
            # of the command execution
            results = []
            do_custom_result_summary = result_renderer == 'tailored' \
                and hasattr(_func_class, 'custom_result_summary_renderer')

            # process main results
            for r in _process_results(
                    wrapped(*_args, **_kwargs),
                    _func_class, action_summary,
                    on_failure, incomplete_results,
                    result_renderer, result_xfm, _result_filter, **_kwargs):
                yield r
                # collect if summary is desired
                if do_custom_result_summary:
                    results.append(r)

            if proc_post and cmdline_name != 'run-procedure':
                from datalad.interface.run_procedure import RunProcedure
                for procspec in proc_post:
                    lgr.debug('Running configured post-procedure %s', procspec)
                    for r in _process_results(
                            RunProcedure.__call__(
                                procspec,
                                dataset=dataset_arg,
                                return_type='generator'),
                            _func_class, action_summary,
                            on_failure, incomplete_results,
                            result_renderer, result_xfm, result_filter,
                            **_kwargs):
                        yield r

            # result summary before a potential exception
            # custom first
            if do_custom_result_summary:
                _func_class.custom_result_summary_renderer(results)
            elif result_renderer == 'default' and action_summary and \
                    sum(sum(s.values()) for s in action_summary.values()) > 1:
                # give a summary in default mode, when there was more than one
                # action performed
                ui.message("action summary:\n  {}".format(
                    '\n  '.join('{} ({})'.format(
                        act,
                        ', '.join('{}: {}'.format(status, action_summary[act][status])
                                  for status in sorted(action_summary[act])))
                                for act in sorted(action_summary))))

            if incomplete_results:
                raise IncompleteResultsError(
                    failed=incomplete_results,
                    msg="Command did not complete successfully")

        if return_type == 'generator':
            # hand over the generator
            return generator_func(*args, **kwargs)
        else:
            @wrapt.decorator
            def return_func(wrapped_, instance_, args_, kwargs_):
                results = wrapped_(*args_, **kwargs_)
                if inspect.isgenerator(results):
                    # unwind generator if there is one, this actually runs
                    # any processing
                    results = list(results)
                # render summaries
                if not result_xfm and result_renderer == 'tailored':
                    # cannot render transformed results
                    if hasattr(_func_class, 'custom_result_summary_renderer'):
                        _func_class.custom_result_summary_renderer(results)
                if return_type == 'item-or-list' and \
                        len(results) < 2:
                    return results[0] if results else None
                else:
                    return results

            return return_func(generator_func)(*args, **kwargs)

    return eval_func(func)


def default_result_renderer(res):
    if res.get('status', None) != 'notneeded':
        ui.message('{action}({status}): {path}{type}{msg}'.format(
                action=ac.color_word(res['action'], ac.BOLD),
                status=ac.color_status(res['status']),
                path=relpath(res['path'],
                             res['refds']) if res.get('refds', None) else res[
                    'path'],
                type=' ({})'.format(
                        ac.color_word(res['type'], ac.MAGENTA)
                ) if 'type' in res else '',
                msg=' [{}]'.format(
                        res['message'][0] % res['message'][1:]
                        if isinstance(res['message'], tuple) else res[
                            'message'])
                if 'message' in res else ''))


def _process_results(
        results, cmd_class,
        action_summary, on_failure, incomplete_results,
        result_renderer, result_xfm, result_filter, **kwargs):
    # private helper pf @eval_results
    # loop over results generated from some source and handle each
    # of them according to the requested behavior (logging, rendering, ...)
    for res in results:
        if not res or 'action' not in res:
            # XXX Yarik has to no clue on how to track the origin of the
            # record to figure out WTF, so he just skips it
            continue

        if PY2:
            for k, v in res.items():
                if isinstance(v, unicode):
                    res[k] = v.encode('utf-8')

        actsum = action_summary.get(res['action'], {})
        if res['status']:
            actsum[res['status']] = actsum.get(res['status'], 0) + 1
            action_summary[res['action']] = actsum
        ## log message, if a logger was given
        # remove logger instance from results, as it is no longer useful
        # after logging was done, it isn't serializable, and generally
        # pollutes the output
        res_lgr = res.pop('logger', None)
        if isinstance(res_lgr, logging.Logger):
            # didn't get a particular log function, go with default
            res_lgr = getattr(res_lgr, default_logchannels[res['status']])
        if res_lgr and 'message' in res:
            msg = res['message']
            msgargs = None
            if isinstance(msg, tuple):
                msgargs = msg[1:]
                msg = msg[0]
            if 'path' in res:
                msg = '{} [{}({})]'.format(
                    msg, res['action'], res['path'])
            if msgargs:
                # support string expansion of logging to avoid runtime cost
                res_lgr(msg, *msgargs)
            else:
                res_lgr(msg)
        ## error handling
        # looks for error status, and report at the end via
        # an exception
        if on_failure in ('continue', 'stop') \
                and res['status'] in ('impossible', 'error'):
            incomplete_results.append(res)
            if on_failure == 'stop':
                # first fail -> that's it
                # raise will happen after the loop
                break
        if result_filter:
            try:
                if not result_filter(res):
                    raise ValueError('excluded by filter')
            except ValueError as e:
                lgr.debug('not reporting result (%s)', exc_str(e))
                continue
        ## output rendering
        # TODO RF this in a simple callable that gets passed into this function
        if result_renderer is None or result_renderer == 'disabled':
            pass
        elif result_renderer == 'default':
            default_result_renderer(res)
        elif result_renderer in ('json', 'json_pp'):
            ui.message(json.dumps(
                {k: v for k, v in res.items()
                 if k not in ('message', 'logger')},
                sort_keys=True,
                indent=2 if result_renderer.endswith('_pp') else None,
                default=lambda x: str(x)))
        elif result_renderer == 'tailored':
            if hasattr(cmd_class, 'custom_result_renderer'):
                cmd_class.custom_result_renderer(res, **kwargs)
        elif hasattr(result_renderer, '__call__'):
            try:
                result_renderer(res, **kwargs)
            except Exception as e:
                lgr.warn('Result rendering failed for: %s [%s]',
                         res, exc_str(e))
        else:
            raise ValueError('unknown result renderer "{}"'.format(result_renderer))

        if PY2:
            for k, v in res.items():
                if isinstance(v, str):
                    res[k] = v.decode('utf-8')

        if result_xfm:
            res = result_xfm(res)
            if res is None:
                continue
        yield res

```
--- 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:** Unexpected Modification of `kwargs` When Using `@eval_results` Decorator

**Description**
When using the `@eval_results` decorator on a function, the original `kwargs` are unexpectedly modified. This side-effect occurs because the decorator alters the `kwargs` by popping certain keys, which leads to unintended behavior in subsequent code that relies on the original `kwargs`.

**Example Code:**
```python
@eval_results
def sample_function(number, dataset, **kwargs):
    # Function implementation
    pass

# Original kwargs
kwargs = {'return_type': 'list'}

# Calling the decorated function
sample_function(2, Dataset('/example/path'), **kwargs)

# After the call, kwargs is unexpectedly modified
print(kwargs)  # Expected: {'return_type': 'list'}
               # Actual: {}
```

**Expected Behavior**
The `kwargs` passed to the decorated function should remain unchanged after the function call. Modifying `kwargs` within the decorator should not affect the original dictionary outside the function.

**Actual Behavior**
After invoking the decorated function, the original `kwargs` dictionary is altered by removing keys that were popped inside the decorator. This unintended modification leads to discrepancies in the expected values of `kwargs`, causing tests that rely on the original `kwargs` to fail.

[/ISSUE]
{
    "test_eval_results_plus_build_doc": "PASSED",
    "test_result_filter": "PASSED",
    "test_discover_ds_trace": "ERROR",
    "test_dirty": "FAILED",
    "test_save_hierarchy": "FAILED"
}
diff --git a/datalad/interface/utils.py b/datalad/interface/utils.py
index 6018cde70..b9801812f 100644
--- a/datalad/interface/utils.py
+++ b/datalad/interface/utils.py
@@ -331,6 +331,7 @@ def eval_results(func):
 
         # retrieve common options from kwargs, and fall back on the command
         # class attributes, or general defaults if needed
+        kwargs = kwargs.copy()  # we will pop, which might cause side-effect
         common_params = {
             p_name: kwargs.pop(
                 p_name,
 

{"datalad/interface/utils.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\"\"\"Interface utility functions\n\n\"\"\"\n\n__docformat__ = 'restructuredtext'\n\nimport inspect\nimport logging\nimport wrapt\nimport sys\nimport re\nimport shlex\nfrom os import curdir\nfrom os import pardir\nfrom os import listdir\nfrom os.path import join as opj\nfrom os.path import isdir\nfrom os.path import relpath\nfrom os.path import sep\nfrom os.path import split as psplit\nfrom itertools import chain\nfrom six import PY2\n\nimport json\n\n# avoid import from API to not get into circular imports\nfrom datalad.utils import with_pathsep as _with_sep  # TODO: RF whenever merge conflict is not upon us\nfrom datalad.utils import path_startswith\nfrom datalad.utils import path_is_subpath\nfrom datalad.utils import assure_unicode\nfrom datalad.support.gitrepo import GitRepo\nfrom datalad.support.exceptions import IncompleteResultsError\nfrom datalad import cfg as dlcfg\nfrom datalad.dochelpers import exc_str\n\n\nfrom datalad.support.constraints import Constraint\n\nfrom datalad.ui import ui\nimport datalad.support.ansi_colors as ac\n\nfrom datalad.interface.base import Interface\nfrom datalad.interface.base import default_logchannels\nfrom datalad.interface.base import get_allargs_as_kwargs\nfrom datalad.interface.common_opts import eval_params\nfrom datalad.interface.common_opts import eval_defaults\nfrom .results import known_result_xfms\n\n\nlgr = logging.getLogger('datalad.interface.utils')\n\n\ndef cls2cmdlinename(cls):\n    \"Return the cmdline command name from an Interface class\"\n    r = re.compile(r'([a-z0-9])([A-Z])')\n    return r.sub('\\\\1-\\\\2', cls.__name__).lower()\n\n\n# TODO remove\n# only `drop` and `uninstall` are still using this\ndef handle_dirty_dataset(ds, mode, msg=None):\n    \"\"\"Detect and treat unsaved changes as instructed by `mode`\n\n    Parameters\n    ----------\n    ds : Dataset or None\n      Dataset to be inspected. Does nothing if `None`.\n    mode : {'fail', 'ignore', 'save-before'}\n      How to act upon discovering unsaved changes.\n    msg : str or None\n      Custom message to use for a potential commit.\n\n    Returns\n    -------\n    None\n    \"\"\"\n    if ds is None:\n        # nothing to be handled\n        return\n    if msg is None:\n        msg = '[DATALAD] auto-saved changes'\n\n    # make sure that all pending changes (batched annex operations, etc.)\n    # are actually reflected in Git\n    if ds.repo:\n        ds.repo.precommit()\n\n    if mode == 'ignore':\n        return\n    elif mode == 'fail':\n        if not ds.repo or ds.repo.is_dirty(index=True,\n                                           untracked_files=True,\n                                           submodules=True):\n            raise RuntimeError('dataset {} has unsaved changes'.format(ds))\n    elif mode == 'save-before':\n        if not ds.is_installed():\n            raise RuntimeError('dataset {} is not yet installed'.format(ds))\n        from datalad.interface.save import Save\n        Save.__call__(dataset=ds, message=msg)\n    else:\n        raise ValueError(\"unknown if-dirty mode '{}'\".format(mode))\n\n\ndef get_tree_roots(paths):\n    \"\"\"Return common root paths for a set of paths\n\n    This function determines the smallest set of common root\n    paths and sorts all given paths under the respective\n    root.\n\n    Returns\n    -------\n    dict\n      paths by root\n    \"\"\"\n    paths_ws = [_with_sep(p) for p in paths]\n    # sort all paths under their potential roots\n    roots = {}\n    # start from the top to get all paths down the line\n    # and collate them into as few roots as possible\n    for s in sorted(paths_ws):\n        if any([s.startswith(r) for r in roots]):\n            # this path is already covered by a known root\n            continue\n        # find all sub paths\n        subs = [p for p in paths if p.startswith(s)]\n        roots[s.rstrip(sep)] = subs\n    return roots\n\n\n# TODO remove\n# only `remove` and `uninstall` use this, the uses path `path_is_subpath`\ndef path_is_under(values, path=None):\n    \"\"\"Whether a given path is a subdirectory of any of the given test values\n\n    Parameters\n    ----------\n    values : sequence or dict\n      Paths to be tested against. This can be a dictionary in which case\n      all values from all keys will be tested against.\n    path : path or None\n      Test path. If None is given, the process' working directory is\n      used.\n\n    Returns\n    -------\n    bool\n    \"\"\"\n    if path is None:\n        from datalad.utils import getpwd\n        path = getpwd()\n    if isinstance(values, dict):\n        values = chain(*values.values())\n    for p in values:\n        rpath = relpath(p, start=path)\n        if rpath == curdir \\\n                or rpath == pardir \\\n                or set(psplit(rpath)) == {pardir}:\n            # first match is enough\n            return True\n    return False\n\n\ndef discover_dataset_trace_to_targets(basepath, targetpaths, current_trace,\n                                      spec, includeds=None):\n    \"\"\"Discover the edges and nodes in a dataset tree to given target paths\n\n    Parameters\n    ----------\n    basepath : path\n      Path to a start or top-level dataset. Really has to be a path to a\n      dataset!\n    targetpaths : list(path)\n      Any non-zero number of paths that are termination points for the\n      search algorithm. Can be paths to datasets, directories, or files\n      (and any combination thereof).\n    current_trace : list\n      For a top-level call this should probably always be `[]`\n    spec : dict\n      `content_by_ds`-style dictionary that will receive information about the\n      discovered datasets. Specifically, for each discovered dataset there\n      will be in item with its path under the key (path) of the respective\n      superdataset.\n    includeds : sequence, optional\n      Any paths given are treated as existing subdatasets, regardless of\n      whether they can be found in the filesystem. Such subdatasets will appear\n      under the key of the closest existing dataset in the `spec`.\n\n    Returns\n    -------\n    None\n      Function calls itself recursively and populates `spec` dict in-place.\n      Keys are dataset paths, values are sets of subdataset paths\n    \"\"\"\n    # convert to set for faster lookup\n    includeds = includeds if isinstance(includeds, set) else \\\n        set() if includeds is None else set(includeds)\n    # this beast walks the directory tree from a given `basepath` until\n    # it discovers any of the given `targetpaths`\n    # if it finds one, it commits any accummulated trace of visited\n    # datasets on this edge to the spec\n    valid_repo = GitRepo.is_valid_repo(basepath)\n    if valid_repo:\n        # we are passing into a new dataset, extend the dataset trace\n        current_trace = current_trace + [basepath]\n    # this edge is not done, we need to try to reach any downstream\n    # dataset\n    undiscovered_ds = set(t for t in targetpaths) # if t != basepath)\n    # whether anything in this directory matched a targetpath\n    filematch = False\n    if isdir(basepath):\n        for p in listdir(basepath):\n            p = assure_unicode(opj(basepath, p))\n            if not isdir(p):\n                if p in targetpaths:\n                    filematch = True\n                # we cannot have anything below this one\n                continue\n            # OPT listdir might be large and we could have only few items\n            # in `targetpaths` -- so traverse only those in spec which have\n            # leading dir basepath\n            # filter targets matching this downward path\n            downward_targets = set(\n                t for t in targetpaths if path_startswith(t, p))\n            if not downward_targets:\n                continue\n            # remove the matching ones from the \"todo\" list\n            undiscovered_ds.difference_update(downward_targets)\n            # go one deeper\n            discover_dataset_trace_to_targets(\n                p, downward_targets, current_trace, spec,\n                includeds=includeds if not includeds else includeds.intersection(\n                    downward_targets))\n    undiscovered_ds = [t for t in undiscovered_ds\n                       if includeds and\n                          path_is_subpath(t, current_trace[-1]) and\n                          t in includeds]\n    if filematch or basepath in targetpaths or undiscovered_ds:\n        for i, p in enumerate(current_trace[:-1]):\n            # TODO RF prepare proper annotated path dicts\n            subds = spec.get(p, set())\n            subds.add(current_trace[i + 1])\n            spec[p] = subds\n        if undiscovered_ds:\n            spec[current_trace[-1]] = spec.get(current_trace[-1], set()).union(\n                undiscovered_ds)\n\n\ndef eval_results(func):\n    \"\"\"Decorator for return value evaluation of datalad commands.\n\n    Note, this decorator is only compatible with commands that return\n    status dict sequences!\n\n    Two basic modes of operation are supported: 1) \"generator mode\" that\n    `yields` individual results, and 2) \"list mode\" that returns a sequence of\n    results. The behavior can be selected via the kwarg `return_type`.\n    Default is \"list mode\".\n\n    This decorator implements common functionality for result rendering/output,\n    error detection/handling, and logging.\n\n    Result rendering/output can be triggered via the\n    `datalad.api.result-renderer` configuration variable, or the\n    `result_renderer` keyword argument of each decorated command. Supported\n    modes are: 'default' (one line per result with action, status, path,\n    and an optional message); 'json' (one object per result, like git-annex),\n    'json_pp' (like 'json', but pretty-printed spanning multiple lines),\n    'tailored' custom output formatting provided by each command\n    class (if any).\n\n    Error detection works by inspecting the `status` item of all result\n    dictionaries. Any occurrence of a status other than 'ok' or 'notneeded'\n    will cause an IncompleteResultsError exception to be raised that carries\n    the failed actions' status dictionaries in its `failed` attribute.\n\n    Status messages will be logged automatically, by default the following\n    association of result status and log channel will be used: 'ok' (debug),\n    'notneeded' (debug), 'impossible' (warning), 'error' (error).  Logger\n    instances included in the results are used to capture the origin of a\n    status report.\n\n    Parameters\n    ----------\n    func: function\n      __call__ method of a subclass of Interface,\n      i.e. a datalad command definition\n    \"\"\"\n\n    @wrapt.decorator\n    def eval_func(wrapped, instance, args, kwargs):\n        # for result filters and pre/post procedures\n        # we need to produce a dict with argname/argvalue pairs for all args\n        # incl. defaults and args given as positionals\n        allkwargs = get_allargs_as_kwargs(wrapped, args, kwargs)\n        # determine class, the __call__ method of which we are decorating:\n        # Ben: Note, that this is a bit dirty in PY2 and imposes restrictions on\n        # when and how to use eval_results as well as on how to name a command's\n        # module and class. As of now, we are inline with these requirements as\n        # far as I'm aware.\n        mod = sys.modules[wrapped.__module__]\n        if PY2:\n            # we rely on:\n            # - decorated function is method of a subclass of Interface\n            # - the name of the class matches the last part of the module's name\n            #   if converted to lower\n            # for example:\n            # ..../where/ever/mycommand.py:\n            # class MyCommand(Interface):\n            #     @eval_results\n            #     def __call__(..)\n            command_class_names = \\\n                [i for i in mod.__dict__\n                 if type(mod.__dict__[i]) == type and\n                 issubclass(mod.__dict__[i], Interface) and\n                 i.lower().startswith(wrapped.__module__.split('.')[-1].replace('datalad_', '').replace('_', ''))]\n            assert len(command_class_names) == 1, (command_class_names, mod.__name__)\n            command_class_name = command_class_names[0]\n        else:\n            command_class_name = wrapped.__qualname__.split('.')[-2]\n        _func_class = mod.__dict__[command_class_name]\n        lgr.debug(\"Determined class of decorated function: %s\", _func_class)\n\n        # retrieve common options from kwargs, and fall back on the command\n        # class attributes, or general defaults if needed\n        common_params = {\n            p_name: kwargs.pop(\n                p_name,\n                getattr(_func_class, p_name, eval_defaults[p_name]))\n            for p_name in eval_params}\n        # short cuts and configured setup for common options\n        on_failure = common_params['on_failure']\n        return_type = common_params['return_type']\n        # resolve string labels for transformers too\n        result_xfm = common_params['result_xfm']\n        if result_xfm in known_result_xfms:\n            result_xfm = known_result_xfms[result_xfm]\n        result_renderer = common_params['result_renderer']\n        # TODO remove this conditional branch entirely, done outside\n        if not result_renderer:\n            result_renderer = dlcfg.get('datalad.api.result-renderer', None)\n        # wrap the filter into a helper to be able to pass additional arguments\n        # if the filter supports it, but at the same time keep the required interface\n        # as minimal as possible. Also do this here, in order to avoid this test\n        # to be performed for each return value\n        result_filter = common_params['result_filter']\n        _result_filter = result_filter\n        if result_filter:\n            if isinstance(result_filter, Constraint):\n                _result_filter = result_filter.__call__\n            if (PY2 and inspect.getargspec(_result_filter).keywords) or \\\n                    (not PY2 and inspect.getfullargspec(_result_filter).varkw):\n\n                def _result_filter(res):\n                    return result_filter(res, **allkwargs)\n\n        def _get_procedure_specs(param_key=None, cfg_key=None, ds=None):\n            spec = common_params.get(param_key, None)\n            if spec is not None:\n                # this is already a list of lists\n                return spec\n\n            from datalad.distribution.dataset import Dataset\n            ds = ds if isinstance(ds, Dataset) else Dataset(ds) if ds else None\n            spec = (ds.config if ds and ds.is_installed()\n                    else dlcfg).get(cfg_key, None)\n            if spec is None:\n                return\n            elif not isinstance(spec, tuple):\n                spec = [spec]\n            return [shlex.split(s) for s in spec]\n\n        # query cfg for defaults\n        cmdline_name = cls2cmdlinename(_func_class)\n        dataset_arg = allkwargs.get('dataset', None)\n        proc_pre = _get_procedure_specs(\n            'proc_pre',\n            'datalad.{}.proc-pre'.format(cmdline_name),\n            ds=dataset_arg)\n        proc_post = _get_procedure_specs(\n            'proc_post',\n            'datalad.{}.proc-post'.format(cmdline_name),\n            ds=dataset_arg)\n\n        # this internal helper function actually drives the command\n        # generator-style, it may generate an exception if desired,\n        # on incomplete results\n        def generator_func(*_args, **_kwargs):\n            # flag whether to raise an exception\n            incomplete_results = []\n            # track what actions were performed how many times\n            action_summary = {}\n\n            if proc_pre and cmdline_name != 'run-procedure':\n                from datalad.interface.run_procedure import RunProcedure\n                for procspec in proc_pre:\n                    lgr.debug('Running configured pre-procedure %s', procspec)\n                    for r in _process_results(\n                            RunProcedure.__call__(\n                                procspec,\n                                dataset=dataset_arg,\n                                return_type='generator'),\n                            _func_class, action_summary,\n                            on_failure, incomplete_results,\n                            result_renderer, result_xfm, result_filter,\n                            **_kwargs):\n                        yield r\n\n            # if a custom summary is to be provided, collect the results\n            # of the command execution\n            results = []\n            do_custom_result_summary = result_renderer == 'tailored' \\\n                and hasattr(_func_class, 'custom_result_summary_renderer')\n\n            # process main results\n            for r in _process_results(\n                    wrapped(*_args, **_kwargs),\n                    _func_class, action_summary,\n                    on_failure, incomplete_results,\n                    result_renderer, result_xfm, _result_filter, **_kwargs):\n                yield r\n                # collect if summary is desired\n                if do_custom_result_summary:\n                    results.append(r)\n\n            if proc_post and cmdline_name != 'run-procedure':\n                from datalad.interface.run_procedure import RunProcedure\n                for procspec in proc_post:\n                    lgr.debug('Running configured post-procedure %s', procspec)\n                    for r in _process_results(\n                            RunProcedure.__call__(\n                                procspec,\n                                dataset=dataset_arg,\n                                return_type='generator'),\n                            _func_class, action_summary,\n                            on_failure, incomplete_results,\n                            result_renderer, result_xfm, result_filter,\n                            **_kwargs):\n                        yield r\n\n            # result summary before a potential exception\n            # custom first\n            if do_custom_result_summary:\n                _func_class.custom_result_summary_renderer(results)\n            elif result_renderer == 'default' and action_summary and \\\n                    sum(sum(s.values()) for s in action_summary.values()) > 1:\n                # give a summary in default mode, when there was more than one\n                # action performed\n                ui.message(\"action summary:\\n  {}\".format(\n                    '\\n  '.join('{} ({})'.format(\n                        act,\n                        ', '.join('{}: {}'.format(status, action_summary[act][status])\n                                  for status in sorted(action_summary[act])))\n                                for act in sorted(action_summary))))\n\n            if incomplete_results:\n                raise IncompleteResultsError(\n                    failed=incomplete_results,\n                    msg=\"Command did not complete successfully\")\n\n        if return_type == 'generator':\n            # hand over the generator\n            return generator_func(*args, **kwargs)\n        else:\n            @wrapt.decorator\n            def return_func(wrapped_, instance_, args_, kwargs_):\n                results = wrapped_(*args_, **kwargs_)\n                if inspect.isgenerator(results):\n                    # unwind generator if there is one, this actually runs\n                    # any processing\n                    results = list(results)\n                # render summaries\n                if not result_xfm and result_renderer == 'tailored':\n                    # cannot render transformed results\n                    if hasattr(_func_class, 'custom_result_summary_renderer'):\n                        _func_class.custom_result_summary_renderer(results)\n                if return_type == 'item-or-list' and \\\n                        len(results) < 2:\n                    return results[0] if results else None\n                else:\n                    return results\n\n            return return_func(generator_func)(*args, **kwargs)\n\n    return eval_func(func)\n\n\ndef default_result_renderer(res):\n    if res.get('status', None) != 'notneeded':\n        ui.message('{action}({status}): {path}{type}{msg}'.format(\n                action=ac.color_word(res['action'], ac.BOLD),\n                status=ac.color_status(res['status']),\n                path=relpath(res['path'],\n                             res['refds']) if res.get('refds', None) else res[\n                    'path'],\n                type=' ({})'.format(\n                        ac.color_word(res['type'], ac.MAGENTA)\n                ) if 'type' in res else '',\n                msg=' [{}]'.format(\n                        res['message'][0] % res['message'][1:]\n                        if isinstance(res['message'], tuple) else res[\n                            'message'])\n                if 'message' in res else ''))\n\n\ndef _process_results(\n        results, cmd_class,\n        action_summary, on_failure, incomplete_results,\n        result_renderer, result_xfm, result_filter, **kwargs):\n    # private helper pf @eval_results\n    # loop over results generated from some source and handle each\n    # of them according to the requested behavior (logging, rendering, ...)\n    for res in results:\n        if not res or 'action' not in res:\n            # XXX Yarik has to no clue on how to track the origin of the\n            # record to figure out WTF, so he just skips it\n            continue\n\n        if PY2:\n            for k, v in res.items():\n                if isinstance(v, unicode):\n                    res[k] = v.encode('utf-8')\n\n        actsum = action_summary.get(res['action'], {})\n        if res['status']:\n            actsum[res['status']] = actsum.get(res['status'], 0) + 1\n            action_summary[res['action']] = actsum\n        ## log message, if a logger was given\n        # remove logger instance from results, as it is no longer useful\n        # after logging was done, it isn't serializable, and generally\n        # pollutes the output\n        res_lgr = res.pop('logger', None)\n        if isinstance(res_lgr, logging.Logger):\n            # didn't get a particular log function, go with default\n            res_lgr = getattr(res_lgr, default_logchannels[res['status']])\n        if res_lgr and 'message' in res:\n            msg = res['message']\n            msgargs = None\n            if isinstance(msg, tuple):\n                msgargs = msg[1:]\n                msg = msg[0]\n            if 'path' in res:\n                msg = '{} [{}({})]'.format(\n                    msg, res['action'], res['path'])\n            if msgargs:\n                # support string expansion of logging to avoid runtime cost\n                res_lgr(msg, *msgargs)\n            else:\n                res_lgr(msg)\n        ## error handling\n        # looks for error status, and report at the end via\n        # an exception\n        if on_failure in ('continue', 'stop') \\\n                and res['status'] in ('impossible', 'error'):\n            incomplete_results.append(res)\n            if on_failure == 'stop':\n                # first fail -> that's it\n                # raise will happen after the loop\n                break\n        if result_filter:\n            try:\n                if not result_filter(res):\n                    raise ValueError('excluded by filter')\n            except ValueError as e:\n                lgr.debug('not reporting result (%s)', exc_str(e))\n                continue\n        ## output rendering\n        # TODO RF this in a simple callable that gets passed into this function\n        if result_renderer is None or result_renderer == 'disabled':\n            pass\n        elif result_renderer == 'default':\n            default_result_renderer(res)\n        elif result_renderer in ('json', 'json_pp'):\n            ui.message(json.dumps(\n                {k: v for k, v in res.items()\n                 if k not in ('message', 'logger')},\n                sort_keys=True,\n                indent=2 if result_renderer.endswith('_pp') else None,\n                default=lambda x: str(x)))\n        elif result_renderer == 'tailored':\n            if hasattr(cmd_class, 'custom_result_renderer'):\n                cmd_class.custom_result_renderer(res, **kwargs)\n        elif hasattr(result_renderer, '__call__'):\n            try:\n                result_renderer(res, **kwargs)\n            except Exception as e:\n                lgr.warn('Result rendering failed for: %s [%s]',\n                         res, exc_str(e))\n        else:\n            raise ValueError('unknown result renderer \"{}\"'.format(result_renderer))\n\n        if PY2:\n            for k, v in res.items():\n                if isinstance(v, str):\n                    res[k] = v.decode('utf-8')\n\n        if result_xfm:\n            res = result_xfm(res)\n            if res is None:\n                continue\n        yield res\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:** Unexpected Modification of `kwargs` When Using `@eval_results` Decorator

**Description**
When using the `@eval_results` decorator on a function, the original `kwargs` are unexpectedly modified. This side-effect occurs because the decorator alters the `kwargs` by popping certain keys, which leads to unintended behavior in subsequent code that relies on the original `kwargs`.

**Example Code:**
```python
@eval_results
def sample_function(number, dataset, **kwargs):
    # Function implementation
    pass

# Original kwargs
kwargs = {'return_type': 'list'}

# Calling the decorated function
sample_function(2, Dataset('/example/path'), **kwargs)

# After the call, kwargs is unexpectedly modified
print(kwargs)  # Expected: {'return_type': 'list'}
               # Actual: {}
```

**Expected Behavior**
The `kwargs` passed to the decorated function should remain unchanged after the function call. Modifying `kwargs` within the decorator should not affect the original dictionary outside the function.

**Actual Behavior**
After invoking the decorated function, the original `kwargs` dictionary is altered by removing keys that were popped inside the decorator. This unintended modification leads to discrepancies in the expected values of `kwargs`, causing tests that rely on the original `kwargs` to fail.

[/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/interface/utils.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.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""Interface utility functions

"""

__docformat__ = 'restructuredtext'

import inspect
import logging
import wrapt
import sys
import re
import shlex
from os import curdir
from os import pardir
from os import listdir
from os.path import join as opj
from os.path import isdir
from os.path import relpath
from os.path import sep
from os.path import split as psplit
from itertools import chain
from six import PY2

import json

# avoid import from API to not get into circular imports
from datalad.utils import with_pathsep as _with_sep  # TODO: RF whenever merge conflict is not upon us
from datalad.utils import path_startswith
from datalad.utils import path_is_subpath
from datalad.utils import assure_unicode
from datalad.support.gitrepo import GitRepo
from datalad.support.exceptions import IncompleteResultsError
from datalad import cfg as dlcfg
from datalad.dochelpers import exc_str


from datalad.support.constraints import Constraint

from datalad.ui import ui
import datalad.support.ansi_colors as ac

from datalad.interface.base import Interface
from datalad.interface.base import default_logchannels
from datalad.interface.base import get_allargs_as_kwargs
from datalad.interface.common_opts import eval_params
from datalad.interface.common_opts import eval_defaults
from .results import known_result_xfms


lgr = logging.getLogger('datalad.interface.utils')


def cls2cmdlinename(cls):
    "Return the cmdline command name from an Interface class"
    r = re.compile(r'([a-z0-9])([A-Z])')
    return r.sub('\\1-\\2', cls.__name__).lower()


# TODO remove
# only `drop` and `uninstall` are still using this
def handle_dirty_dataset(ds, mode, msg=None):
    """Detect and treat unsaved changes as instructed by `mode`

    Parameters
    ----------
    ds : Dataset or None
      Dataset to be inspected. Does nothing if `None`.
    mode : {'fail', 'ignore', 'save-before'}
      How to act upon discovering unsaved changes.
    msg : str or None
      Custom message to use for a potential commit.

    Returns
    -------
    None
    """
    if ds is None:
        # nothing to be handled
        return
    if msg is None:
        msg = '[DATALAD] auto-saved changes'

    # make sure that all pending changes (batched annex operations, etc.)
    # are actually reflected in Git
    if ds.repo:
        ds.repo.precommit()

    if mode == 'ignore':
        return
    elif mode == 'fail':
        if not ds.repo or ds.repo.is_dirty(index=True,
                                           untracked_files=True,
                                           submodules=True):
            raise RuntimeError('dataset {} has unsaved changes'.format(ds))
    elif mode == 'save-before':
        if not ds.is_installed():
            raise RuntimeError('dataset {} is not yet installed'.format(ds))
        from datalad.interface.save import Save
        Save.__call__(dataset=ds, message=msg)
    else:
        raise ValueError("unknown if-dirty mode '{}'".format(mode))


def get_tree_roots(paths):
    """Return common root paths for a set of paths

    This function determines the smallest set of common root
    paths and sorts all given paths under the respective
    root.

    Returns
    -------
    dict
      paths by root
    """
    paths_ws = [_with_sep(p) for p in paths]
    # sort all paths under their potential roots
    roots = {}
    # start from the top to get all paths down the line
    # and collate them into as few roots as possible
    for s in sorted(paths_ws):
        if any([s.startswith(r) for r in roots]):
            # this path is already covered by a known root
            continue
        # find all sub paths
        subs = [p for p in paths if p.startswith(s)]
        roots[s.rstrip(sep)] = subs
    return roots


# TODO remove
# only `remove` and `uninstall` use this, the uses path `path_is_subpath`
def path_is_under(values, path=None):
    """Whether a given path is a subdirectory of any of the given test values

    Parameters
    ----------
    values : sequence or dict
      Paths to be tested against. This can be a dictionary in which case
      all values from all keys will be tested against.
    path : path or None
      Test path. If None is given, the process' working directory is
      used.

    Returns
    -------
    bool
    """
    if path is None:
        from datalad.utils import getpwd
        path = getpwd()
    if isinstance(values, dict):
        values = chain(*values.values())
    for p in values:
        rpath = relpath(p, start=path)
        if rpath == curdir \
                or rpath == pardir \
                or set(psplit(rpath)) == {pardir}:
            # first match is enough
            return True
    return False


def discover_dataset_trace_to_targets(basepath, targetpaths, current_trace,
                                      spec, includeds=None):
    """Discover the edges and nodes in a dataset tree to given target paths

    Parameters
    ----------
    basepath : path
      Path to a start or top-level dataset. Really has to be a path to a
      dataset!
    targetpaths : list(path)
      Any non-zero number of paths that are termination points for the
      search algorithm. Can be paths to datasets, directories, or files
      (and any combination thereof).
    current_trace : list
      For a top-level call this should probably always be `[]`
    spec : dict
      `content_by_ds`-style dictionary that will receive information about the
      discovered datasets. Specifically, for each discovered dataset there
      will be in item with its path under the key (path) of the respective
      superdataset.
    includeds : sequence, optional
      Any paths given are treated as existing subdatasets, regardless of
      whether they can be found in the filesystem. Such subdatasets will appear
      under the key of the closest existing dataset in the `spec`.

    Returns
    -------
    None
      Function calls itself recursively and populates `spec` dict in-place.
      Keys are dataset paths, values are sets of subdataset paths
    """
    # convert to set for faster lookup
    includeds = includeds if isinstance(includeds, set) else \
        set() if includeds is None else set(includeds)
    # this beast walks the directory tree from a given `basepath` until
    # it discovers any of the given `targetpaths`
    # if it finds one, it commits any accummulated trace of visited
    # datasets on this edge to the spec
    valid_repo = GitRepo.is_valid_repo(basepath)
    if valid_repo:
        # we are passing into a new dataset, extend the dataset trace
        current_trace = current_trace + [basepath]
    # this edge is not done, we need to try to reach any downstream
    # dataset
    undiscovered_ds = set(t for t in targetpaths) # if t != basepath)
    # whether anything in this directory matched a targetpath
    filematch = False
    if isdir(basepath):
        for p in listdir(basepath):
            p = assure_unicode(opj(basepath, p))
            if not isdir(p):
                if p in targetpaths:
                    filematch = True
                # we cannot have anything below this one
                continue
            # OPT listdir might be large and we could have only few items
            # in `targetpaths` -- so traverse only those in spec which have
            # leading dir basepath
            # filter targets matching this downward path
            downward_targets = set(
                t for t in targetpaths if path_startswith(t, p))
            if not downward_targets:
                continue
            # remove the matching ones from the "todo" list
            undiscovered_ds.difference_update(downward_targets)
            # go one deeper
            discover_dataset_trace_to_targets(
                p, downward_targets, current_trace, spec,
                includeds=includeds if not includeds else includeds.intersection(
                    downward_targets))
    undiscovered_ds = [t for t in undiscovered_ds
                       if includeds and
                          path_is_subpath(t, current_trace[-1]) and
                          t in includeds]
    if filematch or basepath in targetpaths or undiscovered_ds:
        for i, p in enumerate(current_trace[:-1]):
            # TODO RF prepare proper annotated path dicts
            subds = spec.get(p, set())
            subds.add(current_trace[i + 1])
            spec[p] = subds
        if undiscovered_ds:
            spec[current_trace[-1]] = spec.get(current_trace[-1], set()).union(
                undiscovered_ds)


def eval_results(func):
    """Decorator for return value evaluation of datalad commands.

    Note, this decorator is only compatible with commands that return
    status dict sequences!

    Two basic modes of operation are supported: 1) "generator mode" that
    `yields` individual results, and 2) "list mode" that returns a sequence of
    results. The behavior can be selected via the kwarg `return_type`.
    Default is "list mode".

    This decorator implements common functionality for result rendering/output,
    error detection/handling, and logging.

    Result rendering/output can be triggered via the
    `datalad.api.result-renderer` configuration variable, or the
    `result_renderer` keyword argument of each decorated command. Supported
    modes are: 'default' (one line per result with action, status, path,
    and an optional message); 'json' (one object per result, like git-annex),
    'json_pp' (like 'json', but pretty-printed spanning multiple lines),
    'tailored' custom output formatting provided by each command
    class (if any).

    Error detection works by inspecting the `status` item of all result
    dictionaries. Any occurrence of a status other than 'ok' or 'notneeded'
    will cause an IncompleteResultsError exception to be raised that carries
    the failed actions' status dictionaries in its `failed` attribute.

    Status messages will be logged automatically, by default the following
    association of result status and log channel will be used: 'ok' (debug),
    'notneeded' (debug), 'impossible' (warning), 'error' (error).  Logger
    instances included in the results are used to capture the origin of a
    status report.

    Parameters
    ----------
    func: function
      __call__ method of a subclass of Interface,
      i.e. a datalad command definition
    """

    @wrapt.decorator
    def eval_func(wrapped, instance, args, kwargs):
        # for result filters and pre/post procedures
        # we need to produce a dict with argname/argvalue pairs for all args
        # incl. defaults and args given as positionals
        allkwargs = get_allargs_as_kwargs(wrapped, args, kwargs)
        # determine class, the __call__ method of which we are decorating:
        # Ben: Note, that this is a bit dirty in PY2 and imposes restrictions on
        # when and how to use eval_results as well as on how to name a command's
        # module and class. As of now, we are inline with these requirements as
        # far as I'm aware.
        mod = sys.modules[wrapped.__module__]
        if PY2:
            # we rely on:
            # - decorated function is method of a subclass of Interface
            # - the name of the class matches the last part of the module's name
            #   if converted to lower
            # for example:
            # ..../where/ever/mycommand.py:
            # class MyCommand(Interface):
            #     @eval_results
            #     def __call__(..)
            command_class_names = \
                [i for i in mod.__dict__
                 if type(mod.__dict__[i]) == type and
                 issubclass(mod.__dict__[i], Interface) and
                 i.lower().startswith(wrapped.__module__.split('.')[-1].replace('datalad_', '').replace('_', ''))]
            assert len(command_class_names) == 1, (command_class_names, mod.__name__)
            command_class_name = command_class_names[0]
        else:
            command_class_name = wrapped.__qualname__.split('.')[-2]
        _func_class = mod.__dict__[command_class_name]
        lgr.debug("Determined class of decorated function: %s", _func_class)

        # retrieve common options from kwargs, and fall back on the command
        # class attributes, or general defaults if needed
        common_params = {
            p_name: kwargs.pop(
                p_name,
                getattr(_func_class, p_name, eval_defaults[p_name]))
            for p_name in eval_params}
        # short cuts and configured setup for common options
        on_failure = common_params['on_failure']
        return_type = common_params['return_type']
        # resolve string labels for transformers too
        result_xfm = common_params['result_xfm']
        if result_xfm in known_result_xfms:
            result_xfm = known_result_xfms[result_xfm]
        result_renderer = common_params['result_renderer']
        # TODO remove this conditional branch entirely, done outside
        if not result_renderer:
            result_renderer = dlcfg.get('datalad.api.result-renderer', None)
        # wrap the filter into a helper to be able to pass additional arguments
        # if the filter supports it, but at the same time keep the required interface
        # as minimal as possible. Also do this here, in order to avoid this test
        # to be performed for each return value
        result_filter = common_params['result_filter']
        _result_filter = result_filter
        if result_filter:
            if isinstance(result_filter, Constraint):
                _result_filter = result_filter.__call__
            if (PY2 and inspect.getargspec(_result_filter).keywords) or \
                    (not PY2 and inspect.getfullargspec(_result_filter).varkw):

                def _result_filter(res):
                    return result_filter(res, **allkwargs)

        def _get_procedure_specs(param_key=None, cfg_key=None, ds=None):
            spec = common_params.get(param_key, None)
            if spec is not None:
                # this is already a list of lists
                return spec

            from datalad.distribution.dataset import Dataset
            ds = ds if isinstance(ds, Dataset) else Dataset(ds) if ds else None
            spec = (ds.config if ds and ds.is_installed()
                    else dlcfg).get(cfg_key, None)
            if spec is None:
                return
            elif not isinstance(spec, tuple):
                spec = [spec]
            return [shlex.split(s) for s in spec]

        # query cfg for defaults
        cmdline_name = cls2cmdlinename(_func_class)
        dataset_arg = allkwargs.get('dataset', None)
        proc_pre = _get_procedure_specs(
            'proc_pre',
            'datalad.{}.proc-pre'.format(cmdline_name),
            ds=dataset_arg)
        proc_post = _get_procedure_specs(
            'proc_post',
            'datalad.{}.proc-post'.format(cmdline_name),
            ds=dataset_arg)

        # this internal helper function actually drives the command
        # generator-style, it may generate an exception if desired,
        # on incomplete results
        def generator_func(*_args, **_kwargs):
            # flag whether to raise an exception
            incomplete_results = []
            # track what actions were performed how many times
            action_summary = {}

            if proc_pre and cmdline_name != 'run-procedure':
                from datalad.interface.run_procedure import RunProcedure
                for procspec in proc_pre:
                    lgr.debug('Running configured pre-procedure %s', procspec)
                    for r in _process_results(
                            RunProcedure.__call__(
                                procspec,
                                dataset=dataset_arg,
                                return_type='generator'),
                            _func_class, action_summary,
                            on_failure, incomplete_results,
                            result_renderer, result_xfm, result_filter,
                            **_kwargs):
                        yield r

            # if a custom summary is to be provided, collect the results
            # of the command execution
            results = []
            do_custom_result_summary = result_renderer == 'tailored' \
                and hasattr(_func_class, 'custom_result_summary_renderer')

            # process main results
            for r in _process_results(
                    wrapped(*_args, **_kwargs),
                    _func_class, action_summary,
                    on_failure, incomplete_results,
                    result_renderer, result_xfm, _result_filter, **_kwargs):
                yield r
                # collect if summary is desired
                if do_custom_result_summary:
                    results.append(r)

            if proc_post and cmdline_name != 'run-procedure':
                from datalad.interface.run_procedure import RunProcedure
                for procspec in proc_post:
                    lgr.debug('Running configured post-procedure %s', procspec)
                    for r in _process_results(
                            RunProcedure.__call__(
                                procspec,
                                dataset=dataset_arg,
                                return_type='generator'),
                            _func_class, action_summary,
                            on_failure, incomplete_results,
                            result_renderer, result_xfm, result_filter,
                            **_kwargs):
                        yield r

            # result summary before a potential exception
            # custom first
            if do_custom_result_summary:
                _func_class.custom_result_summary_renderer(results)
            elif result_renderer == 'default' and action_summary and \
                    sum(sum(s.values()) for s in action_summary.values()) > 1:
                # give a summary in default mode, when there was more than one
                # action performed
                ui.message("action summary:\n  {}".format(
                    '\n  '.join('{} ({})'.format(
                        act,
                        ', '.join('{}: {}'.format(status, action_summary[act][status])
                                  for status in sorted(action_summary[act])))
                                for act in sorted(action_summary))))

            if incomplete_results:
                raise IncompleteResultsError(
                    failed=incomplete_results,
                    msg="Command did not complete successfully")

        if return_type == 'generator':
            # hand over the generator
            return generator_func(*args, **kwargs)
        else:
            @wrapt.decorator
            def return_func(wrapped_, instance_, args_, kwargs_):
                results = wrapped_(*args_, **kwargs_)
                if inspect.isgenerator(results):
                    # unwind generator if there is one, this actually runs
                    # any processing
                    results = list(results)
                # render summaries
                if not result_xfm and result_renderer == 'tailored':
                    # cannot render transformed results
                    if hasattr(_func_class, 'custom_result_summary_renderer'):
                        _func_class.custom_result_summary_renderer(results)
                if return_type == 'item-or-list' and \
                        len(results) < 2:
                    return results[0] if results else None
                else:
                    return results

            return return_func(generator_func)(*args, **kwargs)

    return eval_func(func)


def default_result_renderer(res):
    if res.get('status', None) != 'notneeded':
        ui.message('{action}({status}): {path}{type}{msg}'.format(
                action=ac.color_word(res['action'], ac.BOLD),
                status=ac.color_status(res['status']),
                path=relpath(res['path'],
                             res['refds']) if res.get('refds', None) else res[
                    'path'],
                type=' ({})'.format(
                        ac.color_word(res['type'], ac.MAGENTA)
                ) if 'type' in res else '',
                msg=' [{}]'.format(
                        res['message'][0] % res['message'][1:]
                        if isinstance(res['message'], tuple) else res[
                            'message'])
                if 'message' in res else ''))


def _process_results(
        results, cmd_class,
        action_summary, on_failure, incomplete_results,
        result_renderer, result_xfm, result_filter, **kwargs):
    # private helper pf @eval_results
    # loop over results generated from some source and handle each
    # of them according to the requested behavior (logging, rendering, ...)
    for res in results:
        if not res or 'action' not in res:
            # XXX Yarik has to no clue on how to track the origin of the
            # record to figure out WTF, so he just skips it
            continue

        if PY2:
            for k, v in res.items():
                if isinstance(v, unicode):
                    res[k] = v.encode('utf-8')

        actsum = action_summary.get(res['action'], {})
        if res['status']:
            actsum[res['status']] = actsum.get(res['status'], 0) + 1
            action_summary[res['action']] = actsum
        ## log message, if a logger was given
        # remove logger instance from results, as it is no longer useful
        # after logging was done, it isn't serializable, and generally
        # pollutes the output
        res_lgr = res.pop('logger', None)
        if isinstance(res_lgr, logging.Logger):
            # didn't get a particular log function, go with default
            res_lgr = getattr(res_lgr, default_logchannels[res['status']])
        if res_lgr and 'message' in res:
            msg = res['message']
            msgargs = None
            if isinstance(msg, tuple):
                msgargs = msg[1:]
                msg = msg[0]
            if 'path' in res:
                msg = '{} [{}({})]'.format(
                    msg, res['action'], res['path'])
            if msgargs:
                # support string expansion of logging to avoid runtime cost
                res_lgr(msg, *msgargs)
            else:
                res_lgr(msg)
        ## error handling
        # looks for error status, and report at the end via
        # an exception
        if on_failure in ('continue', 'stop') \
                and res['status'] in ('impossible', 'error'):
            incomplete_results.append(res)
            if on_failure == 'stop':
                # first fail -> that's it
                # raise will happen after the loop
                break
        if result_filter:
            try:
                if not result_filter(res):
                    raise ValueError('excluded by filter')
            except ValueError as e:
                lgr.debug('not reporting result (%s)', exc_str(e))
                continue
        ## output rendering
        # TODO RF this in a simple callable that gets passed into this function
        if result_renderer is None or result_renderer == 'disabled':
            pass
        elif result_renderer == 'default':
            default_result_renderer(res)
        elif result_renderer in ('json', 'json_pp'):
            ui.message(json.dumps(
                {k: v for k, v in res.items()
                 if k not in ('message', 'logger')},
                sort_keys=True,
                indent=2 if result_renderer.endswith('_pp') else None,
                default=lambda x: str(x)))
        elif result_renderer == 'tailored':
            if hasattr(cmd_class, 'custom_result_renderer'):
                cmd_class.custom_result_renderer(res, **kwargs)
        elif hasattr(result_renderer, '__call__'):
            try:
                result_renderer(res, **kwargs)
            except Exception as e:
                lgr.warn('Result rendering failed for: %s [%s]',
                         res, exc_str(e))
        else:
            raise ValueError('unknown result renderer "{}"'.format(result_renderer))

        if PY2:
            for k, v in res.items():
                if isinstance(v, str):
                    res[k] = v.decode('utf-8')

        if result_xfm:
            res = result_xfm(res)
            if res is None:
                continue
        yield res

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