We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Ensure current working directory is on the python path with insights-run
`insights-run` can't invoke arbitrary scripts because it doesn't include the current working directory in the python path like `python -m insights` does.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `insights/__init__.py`
Content:
```
1 from __future__ import print_function
2 import logging
3 import pkgutil
4 import os
5 import yaml
6 from .core import Scannable, LogFileOutput, Parser, IniConfigFile  # noqa: F401
7 from .core import FileListing, LegacyItemAccess, SysconfigOptions  # noqa: F401
8 from .core import YAMLParser, JSONParser, XMLParser, CommandParser  # noqa: F401
9 from .core import AttributeDict  # noqa: F401
10 from .core import Syslog  # noqa: F401
11 from .core.archives import COMPRESSION_TYPES, extract  # noqa: F401
12 from .core import dr  # noqa: F401
13 from .core.context import ClusterArchiveContext, HostContext, HostArchiveContext  # noqa: F401
14 from .core.dr import SkipComponent  # noqa: F401
15 from .core.hydration import create_context
16 from .core.plugins import combiner, fact, metadata, parser, rule  # noqa: F401
17 from .core.plugins import datasource, condition, incident  # noqa: F401
18 from .core.plugins import make_response, make_metadata, make_fingerprint  # noqa: F401
19 from .core.plugins import make_pass, make_fail  # noqa: F401
20 from .core.filters import add_filter, apply_filters, get_filters  # noqa: F401
21 from .formats import get_formatter
22 from .parsers import get_active_lines  # noqa: F401
23 from .util import defaults  # noqa: F401
24 
25 log = logging.getLogger(__name__)
26 
27 
28 package_info = dict((k, None) for k in ["RELEASE", "COMMIT", "VERSION", "NAME"])
29 
30 
31 for name in package_info:
32     package_info[name] = pkgutil.get_data(__name__, name).strip().decode("utf-8")
33 
34 
35 def get_nvr():
36     return "{0}-{1}-{2}".format(package_info["NAME"],
37                                 package_info["VERSION"],
38                                 package_info["RELEASE"])
39 
40 
41 RULES_STATUS = {}
42 """
43 Mapping of dictionaries containing nvr and commitid for each rule repo included
44 in this instance
45 
46 {"rule_repo_1": {"version": nvr(), "commit": sha1}}
47 """
48 
49 
50 def add_status(name, nvr, commit):
51     """
52     Rule repositories should call this method in their package __init__ to
53     register their version information.
54     """
55     RULES_STATUS[name] = {"version": nvr, "commit": commit}
56 
57 
58 def process_dir(broker, root, graph, context, use_pandas=False):
59     ctx = create_context(root, context)
60     log.debug("Processing %s with %s" % (root, ctx))
61 
62     if isinstance(ctx, ClusterArchiveContext):
63         from .core.cluster import process_cluster
64         archives = [f for f in ctx.all_files if f.endswith(COMPRESSION_TYPES)]
65         return process_cluster(archives, use_pandas=use_pandas, broker=broker)
66 
67     broker[ctx.__class__] = ctx
68     broker = dr.run(graph, broker=broker)
69     return broker
70 
71 
72 def _run(broker, graph=None, root=None, context=None, use_pandas=False):
73     """
74     run is a general interface that is meant for stand alone scripts to use
75     when executing insights components.
76 
77     Args:
78         root (str): None will causes a host collection in which command and
79             file specs are run. A directory or archive path will cause
80             collection from the directory or archive, and only file type specs
81             or those that depend on `insights.core.context.HostArchiveContext`
82             will execute.
83         component (function or class): The component to execute. Will only execute
84             the component and its dependency graph. If None, all components with
85             met dependencies will execute.
86 
87     Returns:
88         broker: object containing the result of the evaluation.
89     """
90 
91     if not root:
92         context = context or HostContext
93         broker[context] = context()
94         return dr.run(graph, broker=broker)
95 
96     if os.path.isdir(root):
97         return process_dir(broker, root, graph, context, use_pandas)
98     else:
99         with extract(root) as ex:
100             return process_dir(broker, ex.tmp_dir, graph, context, use_pandas)
101 
102 
103 def apply_configs(configs):
104     """
105     Configures components. They can be enabled or disabled, have timeouts set
106     if applicable, and have metadata customized. Valid keys are name, enabled,
107     metadata, and timeout.
108 
109     Args:
110         configs (list): a list of dictionaries with the following keys:
111             name, enabled, metadata, and timeout. All keys are optional except
112             name.
113 
114             name is the prefix or exact name of any loaded component. Any
115             component starting with name will have the associated configuration
116             applied.
117 
118             enabled is whether the matching components will execute even if
119             their dependencies are met. Defaults to True.
120 
121             timeout sets the class level timeout attribute of any component so
122             long as the attribute already exists.
123 
124             metadata is any dictionary that you want to attach to the
125             component. The dictionary can be retrieved by the component at
126             runtime.
127     """
128     delegate_keys = sorted(dr.DELEGATES, key=dr.get_name)
129     for comp_cfg in configs:
130         name = comp_cfg["name"]
131         for c in delegate_keys:
132             delegate = dr.DELEGATES[c]
133             cname = dr.get_name(c)
134             if cname.startswith(name):
135                 dr.ENABLED[c] = comp_cfg.get("enabled", True)
136                 delegate.metadata.update(comp_cfg.get("metadata", {}))
137                 for k, v in delegate.metadata.items():
138                     if hasattr(c, k):
139                         setattr(c, k, v)
140                 if hasattr(c, "timeout"):
141                     c.timeout = comp_cfg.get("timeout", c.timeout)
142             if cname == name:
143                 break
144 
145 
146 def _load_context(path):
147     if path is None:
148         return
149 
150     if "." not in path:
151         path = ".".join(["insights.core.context", path])
152     return dr.get_component(path)
153 
154 
155 def run(component=None, root=None, print_summary=False,
156         context=None, use_pandas=False,
157         print_component=None):
158 
159     from .core import dr
160     dr.load_components("insights.specs.default")
161     dr.load_components("insights.specs.insights_archive")
162     dr.load_components("insights.specs.sos_archive")
163     dr.load_components("insights.specs.jdr_archive")
164 
165     args = None
166     formatter = None
167     if print_summary:
168         import argparse
169         import logging
170         p = argparse.ArgumentParser(add_help=False)
171         p.add_argument("archive", nargs="?", help="Archive or directory to analyze.")
172         p.add_argument("-p", "--plugins", default="", help="Comma-separated list without spaces of package(s) or module(s) containing plugins.")
173         p.add_argument("-c", "--config", help="Configure components.")
174         p.add_argument("-v", "--verbose", help="Verbose output.", action="store_true")
175         p.add_argument("-f", "--format", help="Output format.", default="insights.formats.text")
176         p.add_argument("-D", "--debug", help="Verbose debug output.", action="store_true")
177         p.add_argument("--context", help="Execution Context. Defaults to HostContext if an archive isn't passed.")
178         p.add_argument("--pandas", action="store_true", help="Use pandas dataframes with cluster rules.")
179 
180         class Args(object):
181             pass
182 
183         args = Args()
184         p.parse_known_args(namespace=args)
185         p = argparse.ArgumentParser(parents=[p])
186         args.format = "insights.formats._json" if args.format == "json" else args.format
187         args.format = "insights.formats._yaml" if args.format == "yaml" else args.format
188         fmt = args.format if "." in args.format else "insights.formats." + args.format
189         Formatter = dr.get_component(fmt)
190         if not Formatter:
191             dr.load_components(fmt, continue_on_error=False)
192             Formatter = get_formatter(fmt)
193         Formatter.configure(p)
194         p.parse_args(namespace=args)
195         formatter = Formatter(args)
196 
197         logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO if args.verbose else logging.ERROR)
198         context = _load_context(args.context) or context
199         use_pandas = args.pandas or use_pandas
200 
201         root = args.archive or root
202         if root:
203             root = os.path.realpath(root)
204 
205         plugins = []
206         if args.plugins:
207             for path in args.plugins.split(","):
208                 path = path.strip()
209                 if path.endswith(".py"):
210                     path, _ = os.path.splitext(path)
211                 path = path.rstrip("/").replace("/", ".")
212                 plugins.append(path)
213 
214         for p in plugins:
215             dr.load_components(p, continue_on_error=False)
216 
217         if args.config:
218             with open(args.config) as f:
219                 apply_configs(yaml.load(f))
220 
221         if component is None:
222             component = []
223             plugins = tuple(plugins)
224             for c in dr.DELEGATES:
225                 if c.__module__.startswith(plugins):
226                     component.append(c)
227 
228     if component:
229         if not isinstance(component, (list, set)):
230             component = [component]
231         graph = {}
232         for c in component:
233             graph.update(dr.get_dependency_graph(c))
234     else:
235         graph = dr.COMPONENTS[dr.GROUPS.single]
236 
237     broker = dr.Broker()
238 
239     if formatter:
240         formatter.preprocess(broker)
241         broker = _run(broker, graph, root, context=context, use_pandas=use_pandas)
242         formatter.postprocess(broker)
243     elif print_component:
244         broker = _run(broker, graph, root, context=context, use_pandas=use_pandas)
245         broker.print_component(print_component)
246     else:
247         broker = _run(broker, graph, root, context=context, use_pandas=use_pandas)
248 
249     return broker
250 
251 
252 def main():
253     run(print_summary=True)
254 
255 
256 if __name__ == "__main__":
257     main()
258
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/insights/__init__.py b/insights/__init__.py
--- a/insights/__init__.py
+++ b/insights/__init__.py
@@ -2,6 +2,7 @@
 import logging
 import pkgutil
 import os
+import sys
 import yaml
 from .core import Scannable, LogFileOutput, Parser, IniConfigFile  # noqa: F401
 from .core import FileListing, LegacyItemAccess, SysconfigOptions  # noqa: F401
@@ -250,6 +251,8 @@
 
 
 def main():
+    if "" not in sys.path:
+        sys.path.insert(0, "")
     run(print_summary=True)

{"golden_diff": "diff --git a/insights/__init__.py b/insights/__init__.py\n--- a/insights/__init__.py\n+++ b/insights/__init__.py\n@@ -2,6 +2,7 @@\n import logging\n import pkgutil\n import os\n+import sys\n import yaml\n from .core import Scannable, LogFileOutput, Parser, IniConfigFile  # noqa: F401\n from .core import FileListing, LegacyItemAccess, SysconfigOptions  # noqa: F401\n@@ -250,6 +251,8 @@\n \n \n def main():\n+    if \"\" not in sys.path:\n+        sys.path.insert(0, \"\")\n     run(print_summary=True)\n", "issue": "Ensure current working directory is on the python path with insights-run\n`insights-run` can't invoke arbitrary scripts because it doesn't include the current working directory in the python path like `python -m insights` does.\n", "before_files": [{"content": "from __future__ import print_function\nimport logging\nimport pkgutil\nimport os\nimport yaml\nfrom .core import Scannable, LogFileOutput, Parser, IniConfigFile  # noqa: F401\nfrom .core import FileListing, LegacyItemAccess, SysconfigOptions  # noqa: F401\nfrom .core import YAMLParser, JSONParser, XMLParser, CommandParser  # noqa: F401\nfrom .core import AttributeDict  # noqa: F401\nfrom .core import Syslog  # noqa: F401\nfrom .core.archives import COMPRESSION_TYPES, extract  # noqa: F401\nfrom .core import dr  # noqa: F401\nfrom .core.context import ClusterArchiveContext, HostContext, HostArchiveContext  # noqa: F401\nfrom .core.dr import SkipComponent  # noqa: F401\nfrom .core.hydration import create_context\nfrom .core.plugins import combiner, fact, metadata, parser, rule  # noqa: F401\nfrom .core.plugins import datasource, condition, incident  # noqa: F401\nfrom .core.plugins import make_response, make_metadata, make_fingerprint  # noqa: F401\nfrom .core.plugins import make_pass, make_fail  # noqa: F401\nfrom .core.filters import add_filter, apply_filters, get_filters  # noqa: F401\nfrom .formats import get_formatter\nfrom .parsers import get_active_lines  # noqa: F401\nfrom .util import defaults  # noqa: F401\n\nlog = logging.getLogger(__name__)\n\n\npackage_info = dict((k, None) for k in [\"RELEASE\", \"COMMIT\", \"VERSION\", \"NAME\"])\n\n\nfor name in package_info:\n    package_info[name] = pkgutil.get_data(__name__, name).strip().decode(\"utf-8\")\n\n\ndef get_nvr():\n    return \"{0}-{1}-{2}\".format(package_info[\"NAME\"],\n                                package_info[\"VERSION\"],\n                                package_info[\"RELEASE\"])\n\n\nRULES_STATUS = {}\n\"\"\"\nMapping of dictionaries containing nvr and commitid for each rule repo included\nin this instance\n\n{\"rule_repo_1\": {\"version\": nvr(), \"commit\": sha1}}\n\"\"\"\n\n\ndef add_status(name, nvr, commit):\n    \"\"\"\n    Rule repositories should call this method in their package __init__ to\n    register their version information.\n    \"\"\"\n    RULES_STATUS[name] = {\"version\": nvr, \"commit\": commit}\n\n\ndef process_dir(broker, root, graph, context, use_pandas=False):\n    ctx = create_context(root, context)\n    log.debug(\"Processing %s with %s\" % (root, ctx))\n\n    if isinstance(ctx, ClusterArchiveContext):\n        from .core.cluster import process_cluster\n        archives = [f for f in ctx.all_files if f.endswith(COMPRESSION_TYPES)]\n        return process_cluster(archives, use_pandas=use_pandas, broker=broker)\n\n    broker[ctx.__class__] = ctx\n    broker = dr.run(graph, broker=broker)\n    return broker\n\n\ndef _run(broker, graph=None, root=None, context=None, use_pandas=False):\n    \"\"\"\n    run is a general interface that is meant for stand alone scripts to use\n    when executing insights components.\n\n    Args:\n        root (str): None will causes a host collection in which command and\n            file specs are run. A directory or archive path will cause\n            collection from the directory or archive, and only file type specs\n            or those that depend on `insights.core.context.HostArchiveContext`\n            will execute.\n        component (function or class): The component to execute. Will only execute\n            the component and its dependency graph. If None, all components with\n            met dependencies will execute.\n\n    Returns:\n        broker: object containing the result of the evaluation.\n    \"\"\"\n\n    if not root:\n        context = context or HostContext\n        broker[context] = context()\n        return dr.run(graph, broker=broker)\n\n    if os.path.isdir(root):\n        return process_dir(broker, root, graph, context, use_pandas)\n    else:\n        with extract(root) as ex:\n            return process_dir(broker, ex.tmp_dir, graph, context, use_pandas)\n\n\ndef apply_configs(configs):\n    \"\"\"\n    Configures components. They can be enabled or disabled, have timeouts set\n    if applicable, and have metadata customized. Valid keys are name, enabled,\n    metadata, and timeout.\n\n    Args:\n        configs (list): a list of dictionaries with the following keys:\n            name, enabled, metadata, and timeout. All keys are optional except\n            name.\n\n            name is the prefix or exact name of any loaded component. Any\n            component starting with name will have the associated configuration\n            applied.\n\n            enabled is whether the matching components will execute even if\n            their dependencies are met. Defaults to True.\n\n            timeout sets the class level timeout attribute of any component so\n            long as the attribute already exists.\n\n            metadata is any dictionary that you want to attach to the\n            component. The dictionary can be retrieved by the component at\n            runtime.\n    \"\"\"\n    delegate_keys = sorted(dr.DELEGATES, key=dr.get_name)\n    for comp_cfg in configs:\n        name = comp_cfg[\"name\"]\n        for c in delegate_keys:\n            delegate = dr.DELEGATES[c]\n            cname = dr.get_name(c)\n            if cname.startswith(name):\n                dr.ENABLED[c] = comp_cfg.get(\"enabled\", True)\n                delegate.metadata.update(comp_cfg.get(\"metadata\", {}))\n                for k, v in delegate.metadata.items():\n                    if hasattr(c, k):\n                        setattr(c, k, v)\n                if hasattr(c, \"timeout\"):\n                    c.timeout = comp_cfg.get(\"timeout\", c.timeout)\n            if cname == name:\n                break\n\n\ndef _load_context(path):\n    if path is None:\n        return\n\n    if \".\" not in path:\n        path = \".\".join([\"insights.core.context\", path])\n    return dr.get_component(path)\n\n\ndef run(component=None, root=None, print_summary=False,\n        context=None, use_pandas=False,\n        print_component=None):\n\n    from .core import dr\n    dr.load_components(\"insights.specs.default\")\n    dr.load_components(\"insights.specs.insights_archive\")\n    dr.load_components(\"insights.specs.sos_archive\")\n    dr.load_components(\"insights.specs.jdr_archive\")\n\n    args = None\n    formatter = None\n    if print_summary:\n        import argparse\n        import logging\n        p = argparse.ArgumentParser(add_help=False)\n        p.add_argument(\"archive\", nargs=\"?\", help=\"Archive or directory to analyze.\")\n        p.add_argument(\"-p\", \"--plugins\", default=\"\", help=\"Comma-separated list without spaces of package(s) or module(s) containing plugins.\")\n        p.add_argument(\"-c\", \"--config\", help=\"Configure components.\")\n        p.add_argument(\"-v\", \"--verbose\", help=\"Verbose output.\", action=\"store_true\")\n        p.add_argument(\"-f\", \"--format\", help=\"Output format.\", default=\"insights.formats.text\")\n        p.add_argument(\"-D\", \"--debug\", help=\"Verbose debug output.\", action=\"store_true\")\n        p.add_argument(\"--context\", help=\"Execution Context. Defaults to HostContext if an archive isn't passed.\")\n        p.add_argument(\"--pandas\", action=\"store_true\", help=\"Use pandas dataframes with cluster rules.\")\n\n        class Args(object):\n            pass\n\n        args = Args()\n        p.parse_known_args(namespace=args)\n        p = argparse.ArgumentParser(parents=[p])\n        args.format = \"insights.formats._json\" if args.format == \"json\" else args.format\n        args.format = \"insights.formats._yaml\" if args.format == \"yaml\" else args.format\n        fmt = args.format if \".\" in args.format else \"insights.formats.\" + args.format\n        Formatter = dr.get_component(fmt)\n        if not Formatter:\n            dr.load_components(fmt, continue_on_error=False)\n            Formatter = get_formatter(fmt)\n        Formatter.configure(p)\n        p.parse_args(namespace=args)\n        formatter = Formatter(args)\n\n        logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO if args.verbose else logging.ERROR)\n        context = _load_context(args.context) or context\n        use_pandas = args.pandas or use_pandas\n\n        root = args.archive or root\n        if root:\n            root = os.path.realpath(root)\n\n        plugins = []\n        if args.plugins:\n            for path in args.plugins.split(\",\"):\n                path = path.strip()\n                if path.endswith(\".py\"):\n                    path, _ = os.path.splitext(path)\n                path = path.rstrip(\"/\").replace(\"/\", \".\")\n                plugins.append(path)\n\n        for p in plugins:\n            dr.load_components(p, continue_on_error=False)\n\n        if args.config:\n            with open(args.config) as f:\n                apply_configs(yaml.load(f))\n\n        if component is None:\n            component = []\n            plugins = tuple(plugins)\n            for c in dr.DELEGATES:\n                if c.__module__.startswith(plugins):\n                    component.append(c)\n\n    if component:\n        if not isinstance(component, (list, set)):\n            component = [component]\n        graph = {}\n        for c in component:\n            graph.update(dr.get_dependency_graph(c))\n    else:\n        graph = dr.COMPONENTS[dr.GROUPS.single]\n\n    broker = dr.Broker()\n\n    if formatter:\n        formatter.preprocess(broker)\n        broker = _run(broker, graph, root, context=context, use_pandas=use_pandas)\n        formatter.postprocess(broker)\n    elif print_component:\n        broker = _run(broker, graph, root, context=context, use_pandas=use_pandas)\n        broker.print_component(print_component)\n    else:\n        broker = _run(broker, graph, root, context=context, use_pandas=use_pandas)\n\n    return broker\n\n\ndef main():\n    run(print_summary=True)\n\n\nif __name__ == \"__main__\":\n    main()\n", "path": "insights/__init__.py"}], "after_files": [{"content": "from __future__ import print_function\nimport logging\nimport pkgutil\nimport os\nimport sys\nimport yaml\nfrom .core import Scannable, LogFileOutput, Parser, IniConfigFile  # noqa: F401\nfrom .core import FileListing, LegacyItemAccess, SysconfigOptions  # noqa: F401\nfrom .core import YAMLParser, JSONParser, XMLParser, CommandParser  # noqa: F401\nfrom .core import AttributeDict  # noqa: F401\nfrom .core import Syslog  # noqa: F401\nfrom .core.archives import COMPRESSION_TYPES, extract  # noqa: F401\nfrom .core import dr  # noqa: F401\nfrom .core.context import ClusterArchiveContext, HostContext, HostArchiveContext  # noqa: F401\nfrom .core.dr import SkipComponent  # noqa: F401\nfrom .core.hydration import create_context\nfrom .core.plugins import combiner, fact, metadata, parser, rule  # noqa: F401\nfrom .core.plugins import datasource, condition, incident  # noqa: F401\nfrom .core.plugins import make_response, make_metadata, make_fingerprint  # noqa: F401\nfrom .core.plugins import make_pass, make_fail  # noqa: F401\nfrom .core.filters import add_filter, apply_filters, get_filters  # noqa: F401\nfrom .formats import get_formatter\nfrom .parsers import get_active_lines  # noqa: F401\nfrom .util import defaults  # noqa: F401\n\nlog = logging.getLogger(__name__)\n\n\npackage_info = dict((k, None) for k in [\"RELEASE\", \"COMMIT\", \"VERSION\", \"NAME\"])\n\n\nfor name in package_info:\n    package_info[name] = pkgutil.get_data(__name__, name).strip().decode(\"utf-8\")\n\n\ndef get_nvr():\n    return \"{0}-{1}-{2}\".format(package_info[\"NAME\"],\n                                package_info[\"VERSION\"],\n                                package_info[\"RELEASE\"])\n\n\nRULES_STATUS = {}\n\"\"\"\nMapping of dictionaries containing nvr and commitid for each rule repo included\nin this instance\n\n{\"rule_repo_1\": {\"version\": nvr(), \"commit\": sha1}}\n\"\"\"\n\n\ndef add_status(name, nvr, commit):\n    \"\"\"\n    Rule repositories should call this method in their package __init__ to\n    register their version information.\n    \"\"\"\n    RULES_STATUS[name] = {\"version\": nvr, \"commit\": commit}\n\n\ndef process_dir(broker, root, graph, context, use_pandas=False):\n    ctx = create_context(root, context)\n    log.debug(\"Processing %s with %s\" % (root, ctx))\n\n    if isinstance(ctx, ClusterArchiveContext):\n        from .core.cluster import process_cluster\n        archives = [f for f in ctx.all_files if f.endswith(COMPRESSION_TYPES)]\n        return process_cluster(archives, use_pandas=use_pandas, broker=broker)\n\n    broker[ctx.__class__] = ctx\n    broker = dr.run(graph, broker=broker)\n    return broker\n\n\ndef _run(broker, graph=None, root=None, context=None, use_pandas=False):\n    \"\"\"\n    run is a general interface that is meant for stand alone scripts to use\n    when executing insights components.\n\n    Args:\n        root (str): None will causes a host collection in which command and\n            file specs are run. A directory or archive path will cause\n            collection from the directory or archive, and only file type specs\n            or those that depend on `insights.core.context.HostArchiveContext`\n            will execute.\n        component (function or class): The component to execute. Will only execute\n            the component and its dependency graph. If None, all components with\n            met dependencies will execute.\n\n    Returns:\n        broker: object containing the result of the evaluation.\n    \"\"\"\n\n    if not root:\n        context = context or HostContext\n        broker[context] = context()\n        return dr.run(graph, broker=broker)\n\n    if os.path.isdir(root):\n        return process_dir(broker, root, graph, context, use_pandas)\n    else:\n        with extract(root) as ex:\n            return process_dir(broker, ex.tmp_dir, graph, context, use_pandas)\n\n\ndef apply_configs(configs):\n    \"\"\"\n    Configures components. They can be enabled or disabled, have timeouts set\n    if applicable, and have metadata customized. Valid keys are name, enabled,\n    metadata, and timeout.\n\n    Args:\n        configs (list): a list of dictionaries with the following keys:\n            name, enabled, metadata, and timeout. All keys are optional except\n            name.\n\n            name is the prefix or exact name of any loaded component. Any\n            component starting with name will have the associated configuration\n            applied.\n\n            enabled is whether the matching components will execute even if\n            their dependencies are met. Defaults to True.\n\n            timeout sets the class level timeout attribute of any component so\n            long as the attribute already exists.\n\n            metadata is any dictionary that you want to attach to the\n            component. The dictionary can be retrieved by the component at\n            runtime.\n    \"\"\"\n    delegate_keys = sorted(dr.DELEGATES, key=dr.get_name)\n    for comp_cfg in configs:\n        name = comp_cfg[\"name\"]\n        for c in delegate_keys:\n            delegate = dr.DELEGATES[c]\n            cname = dr.get_name(c)\n            if cname.startswith(name):\n                dr.ENABLED[c] = comp_cfg.get(\"enabled\", True)\n                delegate.metadata.update(comp_cfg.get(\"metadata\", {}))\n                for k, v in delegate.metadata.items():\n                    if hasattr(c, k):\n                        setattr(c, k, v)\n                if hasattr(c, \"timeout\"):\n                    c.timeout = comp_cfg.get(\"timeout\", c.timeout)\n            if cname == name:\n                break\n\n\ndef _load_context(path):\n    if path is None:\n        return\n\n    if \".\" not in path:\n        path = \".\".join([\"insights.core.context\", path])\n    return dr.get_component(path)\n\n\ndef run(component=None, root=None, print_summary=False,\n        context=None, use_pandas=False,\n        print_component=None):\n\n    from .core import dr\n    dr.load_components(\"insights.specs.default\")\n    dr.load_components(\"insights.specs.insights_archive\")\n    dr.load_components(\"insights.specs.sos_archive\")\n    dr.load_components(\"insights.specs.jdr_archive\")\n\n    args = None\n    formatter = None\n    if print_summary:\n        import argparse\n        import logging\n        p = argparse.ArgumentParser(add_help=False)\n        p.add_argument(\"archive\", nargs=\"?\", help=\"Archive or directory to analyze.\")\n        p.add_argument(\"-p\", \"--plugins\", default=\"\", help=\"Comma-separated list without spaces of package(s) or module(s) containing plugins.\")\n        p.add_argument(\"-c\", \"--config\", help=\"Configure components.\")\n        p.add_argument(\"-v\", \"--verbose\", help=\"Verbose output.\", action=\"store_true\")\n        p.add_argument(\"-f\", \"--format\", help=\"Output format.\", default=\"insights.formats.text\")\n        p.add_argument(\"-D\", \"--debug\", help=\"Verbose debug output.\", action=\"store_true\")\n        p.add_argument(\"--context\", help=\"Execution Context. Defaults to HostContext if an archive isn't passed.\")\n        p.add_argument(\"--pandas\", action=\"store_true\", help=\"Use pandas dataframes with cluster rules.\")\n\n        class Args(object):\n            pass\n\n        args = Args()\n        p.parse_known_args(namespace=args)\n        p = argparse.ArgumentParser(parents=[p])\n        args.format = \"insights.formats._json\" if args.format == \"json\" else args.format\n        args.format = \"insights.formats._yaml\" if args.format == \"yaml\" else args.format\n        fmt = args.format if \".\" in args.format else \"insights.formats.\" + args.format\n        Formatter = dr.get_component(fmt)\n        if not Formatter:\n            dr.load_components(fmt, continue_on_error=False)\n            Formatter = get_formatter(fmt)\n        Formatter.configure(p)\n        p.parse_args(namespace=args)\n        formatter = Formatter(args)\n\n        logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO if args.verbose else logging.ERROR)\n        context = _load_context(args.context) or context\n        use_pandas = args.pandas or use_pandas\n\n        root = args.archive or root\n        if root:\n            root = os.path.realpath(root)\n\n        plugins = []\n        if args.plugins:\n            for path in args.plugins.split(\",\"):\n                path = path.strip()\n                if path.endswith(\".py\"):\n                    path, _ = os.path.splitext(path)\n                path = path.rstrip(\"/\").replace(\"/\", \".\")\n                plugins.append(path)\n\n        for p in plugins:\n            dr.load_components(p, continue_on_error=False)\n\n        if args.config:\n            with open(args.config) as f:\n                apply_configs(yaml.load(f))\n\n        if component is None:\n            component = []\n            plugins = tuple(plugins)\n            for c in dr.DELEGATES:\n                if c.__module__.startswith(plugins):\n                    component.append(c)\n\n    if component:\n        if not isinstance(component, (list, set)):\n            component = [component]\n        graph = {}\n        for c in component:\n            graph.update(dr.get_dependency_graph(c))\n    else:\n        graph = dr.COMPONENTS[dr.GROUPS.single]\n\n    broker = dr.Broker()\n\n    if formatter:\n        formatter.preprocess(broker)\n        broker = _run(broker, graph, root, context=context, use_pandas=use_pandas)\n        formatter.postprocess(broker)\n    elif print_component:\n        broker = _run(broker, graph, root, context=context, use_pandas=use_pandas)\n        broker.print_component(print_component)\n    else:\n        broker = _run(broker, graph, root, context=context, use_pandas=use_pandas)\n\n    return broker\n\n\ndef main():\n    if \"\" not in sys.path:\n        sys.path.insert(0, \"\")\n    run(print_summary=True)\n\n\nif __name__ == \"__main__\":\n    main()\n", "path": "insights/__init__.py"}]}