We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
 [WARNI]  Could not get the package version from pkg_resource
I execute a ADO pipeline that checks a terraform directory with subdirectories that have 4 modules locally.

![image](https://user-images.githubusercontent.com/22588533/220620198-ffaf26a1-1b1d-472f-922a-30565df2cfe2.png)


Checkov version:
docker.io/bridgecrew/checkov:latest

Path of the Terraform maint.tf and directory that checks chekov: PoC\platform\main.tf


Execution:
LOG_LEVEL=DEBUG;docker run --volume $(pwd):/tf bridgecrew/checkov --directory /tf --framework terraform --output junitxml --soft-fail > $(pwd)/CheckovReport.xml
Result:
2023-02-22 12:23:07,252 [MainThread  ] [WARNI]  Could not get the package version from pkg_resources



I did a list of the files and I can see the checkovReport.xml but it doesn't have enough data to be published:
No Result Found to Publish '/home/vsts/work/1/s/PoC/platform/CheckovReport.xml'.


=====================List all the files of main folder============================
/home/vsts/work/1/s/PoC/platform
total 40
-rw-r--r--  1 vsts docker 3728 Feb 22 12:22 main.tf
drwxr-xr-x 10 vsts docker 4096 Feb 22 12:22 azure-tfmodule
-rw-r--r--  1 vsts docker 2563 Feb 22 12:22 README.md
-rw-r--r--  1 vsts docker  962 Feb 22 12:22 .gitignore
drwxr-xr-x  3 vsts docker 4096 Feb 22 12:22 ..
-rw-r--r--  1 vsts docker 1256 Feb 22 12:22 versions.tf
-rw-r--r--  1 vsts docker 1477 Feb 22 12:22 variables.tf
-rw-r--r--  1 vsts docker 1292 Feb 22 12:22 terraform.tfvars
drwxr-xr-x  3 vsts docker 4096 Feb 22 12:23 .
-rw-r--r--  1 vsts docker 2191 Feb 22 12:23 CheckovReport.xml


This is an example of one of the modules with the WARNI, on the main.tf, where workingDirectory: "./PoC/platform"
module "azurerm_log_analytics_workspace" {
  source              = "./azure-tfmodule/azure-loganalytics-workspace"
  law_name                = module.naming_standard.standard.log-analytics-workspace
  location            = var.location
  resource_group_name = var.resource_group_name
  law_sku             = var.law_sku
  retention_in_days   = var.law_retention_in_days
  tags                = var.tags 

   depends_on = [
    module.naming_standard
  ]
}

If I try to check a terraform plan in json format not the main.tf I get the same warning. 
If I execute same pipeline in the terraform directory without modules it works, the problem is when I try to execute the checkov  and review a local modules or the terraform plan output that calls local modules. Is not on this example but I tested too.


This is my yml pipeline stage:
pool:
  vmImage: ubuntu-latest

stages:
- stage: "runCheckov"
  displayName: "Checkov - Scan Terraform files"
  jobs:
   - job: "runCheckov"
     displayName: "Checkov > Pull, run and publish results of Checkov scan"
     steps:
      - bash: |
                docker pull bridgecrew/checkov
        workingDirectory: "./PoC/platform"
        displayName: "Pull > bridgecrew/checkov"
      - bash: |
                LOG_LEVEL=DEBUG;docker run --volume $(pwd):/tf bridgecrew/checkov --directory /tf --framework terraform --output junitxml --soft-fail > $(pwd)/CheckovReport.xml
        workingDirectory: "./PoC/platform"
        displayName: "Run > checkov"
      - script: |
                      echo "=====================List all the files of main folder============================"
                      cd ./PoC/platform
                      pwd
                      ls -ltra
      - task: PublishTestResults@2
        inputs:
            testRunTitle: "Checkov Results"
            failTaskOnFailedTests: true
            testResultsFormat: "JUnit"
            testResultsFiles: "CheckovReport.xml"
            searchFolder: "./PoC/platform"
            displayName: "Publish > Checkov scan results"
            mergeTestResults: false
            publishRunAttachments: true


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `checkov/common/util/stopit/utils.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 """
3 ============
4 stopit.utils
5 ============
6 
7 Misc utilities and common resources
8 """
9 
10 import functools
11 import logging
12 import sys
13 
14 # Custom logger
15 LOG = logging.getLogger(name='stopit')
16 
17 if sys.version_info < (2, 7):
18     class NullHandler(logging.Handler):
19         """Copied from Python 2.7 to avoid getting `No handlers could be found
20         for logger "xxx"` http://bugs.python.org/issue16539
21         """
22         def handle(self, record):
23             pass
24 
25         def emit(self, record):
26             pass
27 
28         def createLock(self):
29             self.lock = None  # noqa
30 else:
31     from logging import NullHandler
32 
33 LOG.addHandler(NullHandler())
34 
35 
36 class TimeoutException(Exception):
37     """Raised when the block under context management takes longer to complete
38     than the allowed maximum timeout value.
39     """
40     pass
41 
42 
43 class BaseTimeout(object):
44     """Context manager for limiting in the time the execution of a block
45 
46     :param seconds: ``float`` or ``int`` duration enabled to run the context
47       manager block
48     :param swallow_exc: ``False`` if you want to manage the
49       ``TimeoutException`` (or any other) in an outer ``try ... except``
50       structure. ``True`` (default) if you just want to check the execution of
51       the block with the ``state`` attribute of the context manager.
52     """
53 
54     def __init__(self, seconds, swallow_exc=True):
55 
56         # Possible values for the ``state`` attribute, self explanative
57         self.EXECUTED, self.EXECUTING, self.TIMED_OUT, self.INTERRUPTED, self.CANCELED = range(5)
58 
59         self.seconds = seconds
60         self.swallow_exc = swallow_exc
61         self.state = self.EXECUTED
62 
63     def __bool__(self):
64         return self.state in (self.EXECUTED, self.EXECUTING, self.CANCELED)
65 
66     def __repr__(self):
67         """Debug helper
68         """
69         return "<{0} in state: {1}>".format(self.__class__.__name__, self.state)
70 
71     def __enter__(self):
72         self.state = self.EXECUTING
73         self.setup_interrupt()
74         return self
75 
76     def __exit__(self, exc_type, exc_val, exc_tb):
77         if exc_type is TimeoutException:
78             if self.state != self.TIMED_OUT:
79                 self.state = self.INTERRUPTED
80                 self.suppress_interrupt()
81             LOG.warning("Code block execution exceeded {0} seconds timeout".format(self.seconds),
82                         exc_info=(exc_type, exc_val, exc_tb))
83             return self.swallow_exc
84         else:
85             if exc_type is None:
86                 self.state = self.EXECUTED
87             self.suppress_interrupt()
88         return False
89 
90     def cancel(self):
91         """In case in the block you realize you don't need anymore
92        limitation"""
93         self.state = self.CANCELED
94         self.suppress_interrupt()
95 
96     # Methods must be provided by subclasses
97     def suppress_interrupt(self):
98         """Removes/neutralizes the feature that interrupts the executed block
99         """
100         raise NotImplementedError
101 
102     def setup_interrupt(self):
103         """Installs/initializes the feature that interrupts the executed block
104         """
105         raise NotImplementedError
106 
107 
108 class base_timeoutable(object):
109     """A base for function or method decorator that raises a ``TimeoutException`` to
110     decorated functions that should not last a certain amount of time.
111 
112     Any decorated callable may receive a ``timeout`` optional parameter that
113     specifies the number of seconds allocated to the callable execution.
114 
115     The decorated functions that exceed that timeout return ``None`` or the
116     value provided by the decorator.
117 
118     :param default: The default value in case we timed out during the decorated
119       function execution. Default is None.
120 
121     :param timeout_param: As adding dynamically a ``timeout`` named parameter
122       to the decorated callable may conflict with the callable signature, you
123       may choose another name to provide that parameter. Your decoration line
124       could look like ``@timeoutable(timeout_param='my_timeout')``
125 
126     .. note::
127 
128        This is a base class that must be subclassed. subclasses must override
129        thz ``to_ctx_mgr`` with a timeout  context manager class which in turn
130        must subclasses of above ``BaseTimeout`` class.
131     """
132 
133     def __init__(self, default=None, timeout_param='timeout'):
134         self.to_ctx_mgr = None
135         self.default, self.timeout_param = default, timeout_param
136 
137     def __call__(self, func):
138         @functools.wraps(func)
139         def wrapper(*args, **kwargs):
140             timeout = kwargs.pop(self.timeout_param, None)
141             if timeout:
142                 with self.to_ctx_mgr(timeout, swallow_exc=True):
143                     result = self.default  # noqa
144                     # ``result`` may not be assigned below in case of timeout
145                     result = func(*args, **kwargs)
146                 return result
147             else:
148                 return func(*args, **kwargs)
149         return wrapper
150
```

Path: `checkov/common/util/stopit/__init__.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 """
3 ======
4 stopit
5 ======
6 
7 code from:
8 https://github.com/glenfant/stopit
9 package:
10 https://pypi.org/project/stopit
11 
12 Public resources from ``stopit``
13 """
14 
15 import pkg_resources
16 
17 from .utils import LOG, TimeoutException
18 from .threadstop import ThreadingTimeout, async_raise, threading_timeoutable
19 from .signalstop import SignalTimeout, signal_timeoutable
20 
21 # PEP 396 style version marker
22 try:
23     __version__ = pkg_resources.get_distribution(__name__).version
24 except Exception:
25     LOG.warning("Could not get the package version from pkg_resources")
26     __version__ = 'unknown'
27 
28 __all__ = (
29     'ThreadingTimeout', 'async_raise', 'threading_timeoutable',
30     'SignalTimeout', 'signal_timeoutable', 'TimeoutException'
31 )
32
```
--- 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/checkov/common/util/stopit/__init__.py b/checkov/common/util/stopit/__init__.py
--- a/checkov/common/util/stopit/__init__.py
+++ b/checkov/common/util/stopit/__init__.py
@@ -12,18 +12,10 @@
 Public resources from ``stopit``
 """
 
-import pkg_resources
-
-from .utils import LOG, TimeoutException
+from .utils import TimeoutException
 from .threadstop import ThreadingTimeout, async_raise, threading_timeoutable
 from .signalstop import SignalTimeout, signal_timeoutable
 
-# PEP 396 style version marker
-try:
-    __version__ = pkg_resources.get_distribution(__name__).version
-except Exception:
-    LOG.warning("Could not get the package version from pkg_resources")
-    __version__ = 'unknown'
 
 __all__ = (
     'ThreadingTimeout', 'async_raise', 'threading_timeoutable',
diff --git a/checkov/common/util/stopit/utils.py b/checkov/common/util/stopit/utils.py
--- a/checkov/common/util/stopit/utils.py
+++ b/checkov/common/util/stopit/utils.py
@@ -26,7 +26,7 @@
             pass
 
         def createLock(self):
-            self.lock = None  # noqa
+            self.lock = None
 else:
     from logging import NullHandler
 
@@ -140,7 +140,7 @@
             timeout = kwargs.pop(self.timeout_param, None)
             if timeout:
                 with self.to_ctx_mgr(timeout, swallow_exc=True):
-                    result = self.default  # noqa
+                    result = self.default
                     # ``result`` may not be assigned below in case of timeout
                     result = func(*args, **kwargs)
                 return result

{"golden_diff": "diff --git a/checkov/common/util/stopit/__init__.py b/checkov/common/util/stopit/__init__.py\n--- a/checkov/common/util/stopit/__init__.py\n+++ b/checkov/common/util/stopit/__init__.py\n@@ -12,18 +12,10 @@\n Public resources from ``stopit``\n \"\"\"\n \n-import pkg_resources\n-\n-from .utils import LOG, TimeoutException\n+from .utils import TimeoutException\n from .threadstop import ThreadingTimeout, async_raise, threading_timeoutable\n from .signalstop import SignalTimeout, signal_timeoutable\n \n-# PEP 396 style version marker\n-try:\n-    __version__ = pkg_resources.get_distribution(__name__).version\n-except Exception:\n-    LOG.warning(\"Could not get the package version from pkg_resources\")\n-    __version__ = 'unknown'\n \n __all__ = (\n     'ThreadingTimeout', 'async_raise', 'threading_timeoutable',\ndiff --git a/checkov/common/util/stopit/utils.py b/checkov/common/util/stopit/utils.py\n--- a/checkov/common/util/stopit/utils.py\n+++ b/checkov/common/util/stopit/utils.py\n@@ -26,7 +26,7 @@\n             pass\n \n         def createLock(self):\n-            self.lock = None  # noqa\n+            self.lock = None\n else:\n     from logging import NullHandler\n \n@@ -140,7 +140,7 @@\n             timeout = kwargs.pop(self.timeout_param, None)\n             if timeout:\n                 with self.to_ctx_mgr(timeout, swallow_exc=True):\n-                    result = self.default  # noqa\n+                    result = self.default\n                     # ``result`` may not be assigned below in case of timeout\n                     result = func(*args, **kwargs)\n                 return result\n", "issue": " [WARNI]  Could not get the package version from pkg_resource\nI execute a ADO pipeline that checks a terraform directory with subdirectories that have 4 modules locally.\r\n\r\n![image](https://user-images.githubusercontent.com/22588533/220620198-ffaf26a1-1b1d-472f-922a-30565df2cfe2.png)\r\n\r\n\r\nCheckov version:\r\ndocker.io/bridgecrew/checkov:latest\r\n\r\nPath of the Terraform maint.tf and directory that checks chekov: PoC\\platform\\main.tf\r\n\r\n\r\nExecution:\r\nLOG_LEVEL=DEBUG;docker run --volume $(pwd):/tf bridgecrew/checkov --directory /tf --framework terraform --output junitxml --soft-fail > $(pwd)/CheckovReport.xml\r\nResult:\r\n2023-02-22 12:23:07,252 [MainThread  ] [WARNI]  Could not get the package version from pkg_resources\r\n\r\n\r\n\r\nI did a list of the files and I can see the checkovReport.xml but it doesn't have enough data to be published:\r\nNo Result Found to Publish '/home/vsts/work/1/s/PoC/platform/CheckovReport.xml'.\r\n\r\n\r\n=====================List all the files of main folder============================\r\n/home/vsts/work/1/s/PoC/platform\r\ntotal 40\r\n-rw-r--r--  1 vsts docker 3728 Feb 22 12:22 main.tf\r\ndrwxr-xr-x 10 vsts docker 4096 Feb 22 12:22 azure-tfmodule\r\n-rw-r--r--  1 vsts docker 2563 Feb 22 12:22 README.md\r\n-rw-r--r--  1 vsts docker  962 Feb 22 12:22 .gitignore\r\ndrwxr-xr-x  3 vsts docker 4096 Feb 22 12:22 ..\r\n-rw-r--r--  1 vsts docker 1256 Feb 22 12:22 versions.tf\r\n-rw-r--r--  1 vsts docker 1477 Feb 22 12:22 variables.tf\r\n-rw-r--r--  1 vsts docker 1292 Feb 22 12:22 terraform.tfvars\r\ndrwxr-xr-x  3 vsts docker 4096 Feb 22 12:23 .\r\n-rw-r--r--  1 vsts docker 2191 Feb 22 12:23 CheckovReport.xml\r\n\r\n\r\nThis is an example of one of the modules with the WARNI, on the main.tf, where workingDirectory: \"./PoC/platform\"\r\nmodule \"azurerm_log_analytics_workspace\" {\r\n  source              = \"./azure-tfmodule/azure-loganalytics-workspace\"\r\n  law_name                = module.naming_standard.standard.log-analytics-workspace\r\n  location            = var.location\r\n  resource_group_name = var.resource_group_name\r\n  law_sku             = var.law_sku\r\n  retention_in_days   = var.law_retention_in_days\r\n  tags                = var.tags \r\n\r\n   depends_on = [\r\n    module.naming_standard\r\n  ]\r\n}\r\n\r\nIf I try to check a terraform plan in json format not the main.tf I get the same warning. \r\nIf I execute same pipeline in the terraform directory without modules it works, the problem is when I try to execute the checkov  and review a local modules or the terraform plan output that calls local modules. Is not on this example but I tested too.\r\n\r\n\r\nThis is my yml pipeline stage:\r\npool:\r\n  vmImage: ubuntu-latest\r\n\r\nstages:\r\n- stage: \"runCheckov\"\r\n  displayName: \"Checkov - Scan Terraform files\"\r\n  jobs:\r\n   - job: \"runCheckov\"\r\n     displayName: \"Checkov > Pull, run and publish results of Checkov scan\"\r\n     steps:\r\n      - bash: |\r\n                docker pull bridgecrew/checkov\r\n        workingDirectory: \"./PoC/platform\"\r\n        displayName: \"Pull > bridgecrew/checkov\"\r\n      - bash: |\r\n                LOG_LEVEL=DEBUG;docker run --volume $(pwd):/tf bridgecrew/checkov --directory /tf --framework terraform --output junitxml --soft-fail > $(pwd)/CheckovReport.xml\r\n        workingDirectory: \"./PoC/platform\"\r\n        displayName: \"Run > checkov\"\r\n      - script: |\r\n                      echo \"=====================List all the files of main folder============================\"\r\n                      cd ./PoC/platform\r\n                      pwd\r\n                      ls -ltra\r\n      - task: PublishTestResults@2\r\n        inputs:\r\n            testRunTitle: \"Checkov Results\"\r\n            failTaskOnFailedTests: true\r\n            testResultsFormat: \"JUnit\"\r\n            testResultsFiles: \"CheckovReport.xml\"\r\n            searchFolder: \"./PoC/platform\"\r\n            displayName: \"Publish > Checkov scan results\"\r\n            mergeTestResults: false\r\n            publishRunAttachments: true\r\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"\n============\nstopit.utils\n============\n\nMisc utilities and common resources\n\"\"\"\n\nimport functools\nimport logging\nimport sys\n\n# Custom logger\nLOG = logging.getLogger(name='stopit')\n\nif sys.version_info < (2, 7):\n    class NullHandler(logging.Handler):\n        \"\"\"Copied from Python 2.7 to avoid getting `No handlers could be found\n        for logger \"xxx\"` http://bugs.python.org/issue16539\n        \"\"\"\n        def handle(self, record):\n            pass\n\n        def emit(self, record):\n            pass\n\n        def createLock(self):\n            self.lock = None  # noqa\nelse:\n    from logging import NullHandler\n\nLOG.addHandler(NullHandler())\n\n\nclass TimeoutException(Exception):\n    \"\"\"Raised when the block under context management takes longer to complete\n    than the allowed maximum timeout value.\n    \"\"\"\n    pass\n\n\nclass BaseTimeout(object):\n    \"\"\"Context manager for limiting in the time the execution of a block\n\n    :param seconds: ``float`` or ``int`` duration enabled to run the context\n      manager block\n    :param swallow_exc: ``False`` if you want to manage the\n      ``TimeoutException`` (or any other) in an outer ``try ... except``\n      structure. ``True`` (default) if you just want to check the execution of\n      the block with the ``state`` attribute of the context manager.\n    \"\"\"\n\n    def __init__(self, seconds, swallow_exc=True):\n\n        # Possible values for the ``state`` attribute, self explanative\n        self.EXECUTED, self.EXECUTING, self.TIMED_OUT, self.INTERRUPTED, self.CANCELED = range(5)\n\n        self.seconds = seconds\n        self.swallow_exc = swallow_exc\n        self.state = self.EXECUTED\n\n    def __bool__(self):\n        return self.state in (self.EXECUTED, self.EXECUTING, self.CANCELED)\n\n    def __repr__(self):\n        \"\"\"Debug helper\n        \"\"\"\n        return \"<{0} in state: {1}>\".format(self.__class__.__name__, self.state)\n\n    def __enter__(self):\n        self.state = self.EXECUTING\n        self.setup_interrupt()\n        return self\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        if exc_type is TimeoutException:\n            if self.state != self.TIMED_OUT:\n                self.state = self.INTERRUPTED\n                self.suppress_interrupt()\n            LOG.warning(\"Code block execution exceeded {0} seconds timeout\".format(self.seconds),\n                        exc_info=(exc_type, exc_val, exc_tb))\n            return self.swallow_exc\n        else:\n            if exc_type is None:\n                self.state = self.EXECUTED\n            self.suppress_interrupt()\n        return False\n\n    def cancel(self):\n        \"\"\"In case in the block you realize you don't need anymore\n       limitation\"\"\"\n        self.state = self.CANCELED\n        self.suppress_interrupt()\n\n    # Methods must be provided by subclasses\n    def suppress_interrupt(self):\n        \"\"\"Removes/neutralizes the feature that interrupts the executed block\n        \"\"\"\n        raise NotImplementedError\n\n    def setup_interrupt(self):\n        \"\"\"Installs/initializes the feature that interrupts the executed block\n        \"\"\"\n        raise NotImplementedError\n\n\nclass base_timeoutable(object):\n    \"\"\"A base for function or method decorator that raises a ``TimeoutException`` to\n    decorated functions that should not last a certain amount of time.\n\n    Any decorated callable may receive a ``timeout`` optional parameter that\n    specifies the number of seconds allocated to the callable execution.\n\n    The decorated functions that exceed that timeout return ``None`` or the\n    value provided by the decorator.\n\n    :param default: The default value in case we timed out during the decorated\n      function execution. Default is None.\n\n    :param timeout_param: As adding dynamically a ``timeout`` named parameter\n      to the decorated callable may conflict with the callable signature, you\n      may choose another name to provide that parameter. Your decoration line\n      could look like ``@timeoutable(timeout_param='my_timeout')``\n\n    .. note::\n\n       This is a base class that must be subclassed. subclasses must override\n       thz ``to_ctx_mgr`` with a timeout  context manager class which in turn\n       must subclasses of above ``BaseTimeout`` class.\n    \"\"\"\n\n    def __init__(self, default=None, timeout_param='timeout'):\n        self.to_ctx_mgr = None\n        self.default, self.timeout_param = default, timeout_param\n\n    def __call__(self, func):\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            timeout = kwargs.pop(self.timeout_param, None)\n            if timeout:\n                with self.to_ctx_mgr(timeout, swallow_exc=True):\n                    result = self.default  # noqa\n                    # ``result`` may not be assigned below in case of timeout\n                    result = func(*args, **kwargs)\n                return result\n            else:\n                return func(*args, **kwargs)\n        return wrapper\n", "path": "checkov/common/util/stopit/utils.py"}, {"content": "# -*- coding: utf-8 -*-\n\"\"\"\n======\nstopit\n======\n\ncode from:\nhttps://github.com/glenfant/stopit\npackage:\nhttps://pypi.org/project/stopit\n\nPublic resources from ``stopit``\n\"\"\"\n\nimport pkg_resources\n\nfrom .utils import LOG, TimeoutException\nfrom .threadstop import ThreadingTimeout, async_raise, threading_timeoutable\nfrom .signalstop import SignalTimeout, signal_timeoutable\n\n# PEP 396 style version marker\ntry:\n    __version__ = pkg_resources.get_distribution(__name__).version\nexcept Exception:\n    LOG.warning(\"Could not get the package version from pkg_resources\")\n    __version__ = 'unknown'\n\n__all__ = (\n    'ThreadingTimeout', 'async_raise', 'threading_timeoutable',\n    'SignalTimeout', 'signal_timeoutable', 'TimeoutException'\n)\n", "path": "checkov/common/util/stopit/__init__.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"\n============\nstopit.utils\n============\n\nMisc utilities and common resources\n\"\"\"\n\nimport functools\nimport logging\nimport sys\n\n# Custom logger\nLOG = logging.getLogger(name='stopit')\n\nif sys.version_info < (2, 7):\n    class NullHandler(logging.Handler):\n        \"\"\"Copied from Python 2.7 to avoid getting `No handlers could be found\n        for logger \"xxx\"` http://bugs.python.org/issue16539\n        \"\"\"\n        def handle(self, record):\n            pass\n\n        def emit(self, record):\n            pass\n\n        def createLock(self):\n            self.lock = None\nelse:\n    from logging import NullHandler\n\nLOG.addHandler(NullHandler())\n\n\nclass TimeoutException(Exception):\n    \"\"\"Raised when the block under context management takes longer to complete\n    than the allowed maximum timeout value.\n    \"\"\"\n    pass\n\n\nclass BaseTimeout(object):\n    \"\"\"Context manager for limiting in the time the execution of a block\n\n    :param seconds: ``float`` or ``int`` duration enabled to run the context\n      manager block\n    :param swallow_exc: ``False`` if you want to manage the\n      ``TimeoutException`` (or any other) in an outer ``try ... except``\n      structure. ``True`` (default) if you just want to check the execution of\n      the block with the ``state`` attribute of the context manager.\n    \"\"\"\n\n    def __init__(self, seconds, swallow_exc=True):\n\n        # Possible values for the ``state`` attribute, self explanative\n        self.EXECUTED, self.EXECUTING, self.TIMED_OUT, self.INTERRUPTED, self.CANCELED = range(5)\n\n        self.seconds = seconds\n        self.swallow_exc = swallow_exc\n        self.state = self.EXECUTED\n\n    def __bool__(self):\n        return self.state in (self.EXECUTED, self.EXECUTING, self.CANCELED)\n\n    def __repr__(self):\n        \"\"\"Debug helper\n        \"\"\"\n        return \"<{0} in state: {1}>\".format(self.__class__.__name__, self.state)\n\n    def __enter__(self):\n        self.state = self.EXECUTING\n        self.setup_interrupt()\n        return self\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        if exc_type is TimeoutException:\n            if self.state != self.TIMED_OUT:\n                self.state = self.INTERRUPTED\n                self.suppress_interrupt()\n            LOG.warning(\"Code block execution exceeded {0} seconds timeout\".format(self.seconds),\n                        exc_info=(exc_type, exc_val, exc_tb))\n            return self.swallow_exc\n        else:\n            if exc_type is None:\n                self.state = self.EXECUTED\n            self.suppress_interrupt()\n        return False\n\n    def cancel(self):\n        \"\"\"In case in the block you realize you don't need anymore\n       limitation\"\"\"\n        self.state = self.CANCELED\n        self.suppress_interrupt()\n\n    # Methods must be provided by subclasses\n    def suppress_interrupt(self):\n        \"\"\"Removes/neutralizes the feature that interrupts the executed block\n        \"\"\"\n        raise NotImplementedError\n\n    def setup_interrupt(self):\n        \"\"\"Installs/initializes the feature that interrupts the executed block\n        \"\"\"\n        raise NotImplementedError\n\n\nclass base_timeoutable(object):\n    \"\"\"A base for function or method decorator that raises a ``TimeoutException`` to\n    decorated functions that should not last a certain amount of time.\n\n    Any decorated callable may receive a ``timeout`` optional parameter that\n    specifies the number of seconds allocated to the callable execution.\n\n    The decorated functions that exceed that timeout return ``None`` or the\n    value provided by the decorator.\n\n    :param default: The default value in case we timed out during the decorated\n      function execution. Default is None.\n\n    :param timeout_param: As adding dynamically a ``timeout`` named parameter\n      to the decorated callable may conflict with the callable signature, you\n      may choose another name to provide that parameter. Your decoration line\n      could look like ``@timeoutable(timeout_param='my_timeout')``\n\n    .. note::\n\n       This is a base class that must be subclassed. subclasses must override\n       thz ``to_ctx_mgr`` with a timeout  context manager class which in turn\n       must subclasses of above ``BaseTimeout`` class.\n    \"\"\"\n\n    def __init__(self, default=None, timeout_param='timeout'):\n        self.to_ctx_mgr = None\n        self.default, self.timeout_param = default, timeout_param\n\n    def __call__(self, func):\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            timeout = kwargs.pop(self.timeout_param, None)\n            if timeout:\n                with self.to_ctx_mgr(timeout, swallow_exc=True):\n                    result = self.default\n                    # ``result`` may not be assigned below in case of timeout\n                    result = func(*args, **kwargs)\n                return result\n            else:\n                return func(*args, **kwargs)\n        return wrapper\n", "path": "checkov/common/util/stopit/utils.py"}, {"content": "# -*- coding: utf-8 -*-\n\"\"\"\n======\nstopit\n======\n\ncode from:\nhttps://github.com/glenfant/stopit\npackage:\nhttps://pypi.org/project/stopit\n\nPublic resources from ``stopit``\n\"\"\"\n\nfrom .utils import TimeoutException\nfrom .threadstop import ThreadingTimeout, async_raise, threading_timeoutable\nfrom .signalstop import SignalTimeout, signal_timeoutable\n\n\n__all__ = (\n    'ThreadingTimeout', 'async_raise', 'threading_timeoutable',\n    'SignalTimeout', 'signal_timeoutable', 'TimeoutException'\n)\n", "path": "checkov/common/util/stopit/__init__.py"}]}