We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
git commit bear doesn't work if coala isn't run in the same directory
it should also work if I provide a coafile with `-c`, @Makman2 can you fix that soonish? This is kind of the reason why this breaks everywhere for my gitmate experiments.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `coalib/bears/Bear.py`
Content:
```
1 import traceback
2 from pyprint.Printer import Printer
3 
4 from coalib.misc.Decorators import enforce_signature
5 from coalib.output.printers.LogPrinter import LogPrinter
6 from coalib.settings.FunctionMetadata import FunctionMetadata
7 from coalib.settings.Section import Section
8 
9 
10 class Bear(Printer, LogPrinter):
11     """
12     A bear contains the actual subroutine that is responsible for checking
13     source code for certain specifications. However it can actually do
14     whatever it wants with the files it gets. If you are missing some Result
15     type, feel free to contact us and/or help us extending the coalib.
16 
17     This is the base class for every bear. If you want to write an bear, you
18     will probably want to look at the GlobalBear and LocalBear classes that
19     inherit from this class. In any case you'll want to overwrite at least the
20     run method. You can send debug/warning/error messages through the
21     debug(), warn(), err() functions. These will send the
22     appropriate messages so that they are outputted. Be aware that if you use
23     err(), you are expected to also terminate the bear run-through
24     immediately.
25 
26     If you need some setup or teardown for your bear, feel free to overwrite
27     the set_up() and tear_down() functions. They will be invoked
28     before/after every run invocation.
29 
30     Settings are available at all times through self.section.
31     """
32 
33     @enforce_signature
34     def __init__(self,
35                  section: Section,
36                  message_queue,
37                  timeout=0):
38         """
39         Constructs a new bear.
40 
41         :param section:       The section object where bear settings are
42                               contained.
43         :param message_queue: The queue object for messages. Can be `None`.
44         :param timeout:       The time the bear is allowed to run. To set no
45                               time limit, use 0.
46         :raises TypeError:    Raised when `message_queue` is no queue.
47         :raises RuntimeError: Raised when bear requirements are not fulfilled.
48         """
49         Printer.__init__(self)
50         LogPrinter.__init__(self, self)
51 
52         if message_queue is not None and not hasattr(message_queue, "put"):
53             raise TypeError("message_queue has to be a Queue or None.")
54 
55         self.section = section
56         self.message_queue = message_queue
57         self.timeout = timeout
58 
59         cp = type(self).check_prerequisites()
60         if cp is not True:
61             error_string = ("The bear " + type(self).__name__ +
62                             " does not fulfill all requirements.")
63             if cp is not False:
64                 error_string += " " + cp
65 
66             self.warn(error_string)
67             raise RuntimeError(error_string)
68 
69     def _print(self, output, **kwargs):
70         self.debug(output)
71 
72     def log_message(self, log_message, timestamp=None, **kwargs):
73         if self.message_queue is not None:
74             self.message_queue.put(log_message)
75 
76     def run(self, *args, dependency_results=None, **kwargs):
77         raise NotImplementedError
78 
79     def run_bear_from_section(self, args, kwargs):
80         try:
81             kwargs.update(
82                 self.get_metadata().create_params_from_section(self.section))
83         except ValueError as err:
84             self.warn("The bear {} cannot be executed.".format(
85                 type(self).__name__), str(err))
86             return
87 
88         return self.run(*args, **kwargs)
89 
90     def execute(self, *args, **kwargs):
91         name = type(self).__name__
92         try:
93             self.debug("Running bear {}...".format(name))
94             # If it's already a list it won't change it
95             return list(self.run_bear_from_section(args, kwargs) or [])
96         except:
97             self.warn(
98                 "Bear {} failed to run. Take a look at debug messages for "
99                 "further information.".format(name))
100             self.debug(
101                 "The bear {bear} raised an exception. If you are the writer "
102                 "of this bear, please make sure to catch all exceptions. If "
103                 "not and this error annoys you, you might want to get in "
104                 "contact with the writer of this bear.\n\nTraceback "
105                 "information is provided below:\n\n{traceback}"
106                 "\n".format(bear=name, traceback=traceback.format_exc()))
107 
108     @staticmethod
109     def kind():
110         """
111         :return: The kind of the bear
112         """
113         raise NotImplementedError
114 
115     @classmethod
116     def get_metadata(cls):
117         """
118         :return: Metadata for the run function. However parameters like `self`
119                  or parameters implicitly used by coala (e.g. filename for
120                  local bears) are already removed.
121         """
122         return FunctionMetadata.from_function(
123             cls.run,
124             omit={"self", "dependency_results"})
125 
126     @classmethod
127     def missing_dependencies(cls, lst):
128         """
129         Checks if the given list contains all dependencies.
130 
131         :param lst: A list of all already resolved bear classes (not
132                     instances).
133         :return:    A list of missing dependencies.
134         """
135         dep_classes = cls.get_dependencies()
136 
137         for item in lst:
138             if item in dep_classes:
139                 dep_classes.remove(item)
140 
141         return dep_classes
142 
143     @staticmethod
144     def get_dependencies():
145         """
146         Retrieves bear classes that are to be executed before this bear gets
147         executed. The results of these bears will then be passed to the
148         run method as a dict via the dependency_results argument. The dict
149         will have the name of the Bear as key and the list of its results as
150         results.
151 
152         :return: A list of bear classes.
153         """
154         return []
155 
156     @classmethod
157     def get_non_optional_settings(cls):
158         """
159         This method has to determine which settings are needed by this bear.
160         The user will be prompted for needed settings that are not available
161         in the settings file so don't include settings where a default value
162         would do.
163 
164         :return: A dictionary of needed settings as keys and a tuple of help
165                  text and annotation as values
166         """
167         return cls.get_metadata().non_optional_params
168 
169     @classmethod
170     def check_prerequisites(cls):
171         """
172         Checks whether needed runtime prerequisites of the bear are satisfied.
173 
174         This function gets executed at construction and returns True by
175         default.
176 
177         Section value requirements shall be checked inside the `run` method.
178 
179         :return: True if prerequisites are satisfied, else False or a string
180                  that serves a more detailed description of what's missing.
181         """
182         return True
183
```

Path: `bears/vcs/git/GitCommitBear.py`
Content:
```
1 import shutil
2 
3 from coalib.bears.GlobalBear import GlobalBear
4 from coalib.misc.Shell import run_shell_command
5 from coalib.results.Result import Result
6 
7 
8 class GitCommitBear(GlobalBear):
9     _git_command = "git log -1 --pretty=%B"
10 
11     @classmethod
12     def check_prerequisites(cls):
13         if shutil.which("git") is None:
14             return "git is not installed."
15         else:
16             return True
17 
18     def run(self,
19             shortlog_length: int=50,
20             body_line_length: int=73,
21             force_body: bool=False,
22             allow_empty_commit_message: bool=False):
23         """
24         Checks the current git commit message at HEAD.
25 
26         This bear ensures that the shortlog and body do not exceed a given
27         line-length and that a newline lies between them.
28 
29         :param shortlog_length:            The maximum length of the shortlog.
30                                            The shortlog is the first line of
31                                            the commit message. The newline
32                                            character at end does not count to
33                                            the length.
34         :param body_line_length:           The maximum line-length of the body.
35                                            The newline character at each line
36                                            end does not count to the length.
37         :param force_body:                 Whether a body shall exist or not.
38         :param allow_empty_commit_message: Whether empty commit messages are
39                                            allowed or not.
40         """
41         stdout, stderr = run_shell_command(self._git_command)
42 
43         if stderr:
44             self.err("git:", repr(stderr))
45             return
46 
47         # git automatically removes trailing whitespaces. Also we need to
48         # remove the last \n printed to align the prompt onto the next line.
49         stdout = stdout.splitlines()[:-1]
50 
51         if len(stdout) == 0:
52             if not allow_empty_commit_message:
53                 yield Result(self, "HEAD commit has no message.")
54             return
55 
56         yield from self.check_shortlog(shortlog_length, stdout[0])
57         yield from self.check_body(body_line_length, force_body, stdout[1:])
58 
59     def check_shortlog(self, shortlog_length, shortlog):
60         """
61         Checks the given shortlog.
62 
63         :param shortlog_length: The maximum length of the shortlog. The newline
64                                 character at end does not count to the length.
65         :param shortlog:        The shortlog message string.
66         """
67         if len(shortlog) > shortlog_length:
68             yield Result(self, "Shortlog of HEAD commit is too long.")
69 
70     def check_body(self, body_line_length, force_body, body):
71         """
72         Checks the given commit body.
73 
74         :param body_line_length: The maximum line-length of the body. The
75                                  newline character at each line end does not
76                                  count to the length.
77         :param force_body:       Whether a body shall exist or not.
78         :param body:             The commit body splitted by lines.
79         """
80         if len(body) == 0:
81             if force_body:
82                 yield Result(self, "No commit message body at HEAD.")
83             return
84 
85         if body[0] != "":
86             yield Result(self, "No newline between shortlog and body at HEAD.")
87             return
88 
89         if any(len(line) > body_line_length for line in body[1:]):
90             yield Result(self, "Body of HEAD commit contains too long lines.")
91
```
--- 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/bears/vcs/git/GitCommitBear.py b/bears/vcs/git/GitCommitBear.py
--- a/bears/vcs/git/GitCommitBear.py
+++ b/bears/vcs/git/GitCommitBear.py
@@ -1,4 +1,5 @@
 import shutil
+import os
 
 from coalib.bears.GlobalBear import GlobalBear
 from coalib.misc.Shell import run_shell_command
@@ -38,6 +39,10 @@
         :param allow_empty_commit_message: Whether empty commit messages are
                                            allowed or not.
         """
+        config_dir = self.get_config_dir()
+        old_dir = os.getcwd()
+        if config_dir:
+            os.chdir(config_dir)
         stdout, stderr = run_shell_command(self._git_command)
 
         if stderr:
@@ -56,6 +61,8 @@
         yield from self.check_shortlog(shortlog_length, stdout[0])
         yield from self.check_body(body_line_length, force_body, stdout[1:])
 
+        os.chdir(old_dir)
+
     def check_shortlog(self, shortlog_length, shortlog):
         """
         Checks the given shortlog.
diff --git a/coalib/bears/Bear.py b/coalib/bears/Bear.py
--- a/coalib/bears/Bear.py
+++ b/coalib/bears/Bear.py
@@ -5,6 +5,7 @@
 from coalib.output.printers.LogPrinter import LogPrinter
 from coalib.settings.FunctionMetadata import FunctionMetadata
 from coalib.settings.Section import Section
+from coalib.settings.ConfigurationGathering import get_config_directory
 
 
 class Bear(Printer, LogPrinter):
@@ -180,3 +181,11 @@
                  that serves a more detailed description of what's missing.
         """
         return True
+
+    def get_config_dir(self):
+        """
+        Gives the directory where the configuration file is
+
+        :return: Directory of the config file
+        """
+        return get_config_directory(self.section)

{"golden_diff": "diff --git a/bears/vcs/git/GitCommitBear.py b/bears/vcs/git/GitCommitBear.py\n--- a/bears/vcs/git/GitCommitBear.py\n+++ b/bears/vcs/git/GitCommitBear.py\n@@ -1,4 +1,5 @@\n import shutil\n+import os\n \n from coalib.bears.GlobalBear import GlobalBear\n from coalib.misc.Shell import run_shell_command\n@@ -38,6 +39,10 @@\n         :param allow_empty_commit_message: Whether empty commit messages are\n                                            allowed or not.\n         \"\"\"\n+        config_dir = self.get_config_dir()\n+        old_dir = os.getcwd()\n+        if config_dir:\n+            os.chdir(config_dir)\n         stdout, stderr = run_shell_command(self._git_command)\n \n         if stderr:\n@@ -56,6 +61,8 @@\n         yield from self.check_shortlog(shortlog_length, stdout[0])\n         yield from self.check_body(body_line_length, force_body, stdout[1:])\n \n+        os.chdir(old_dir)\n+\n     def check_shortlog(self, shortlog_length, shortlog):\n         \"\"\"\n         Checks the given shortlog.\ndiff --git a/coalib/bears/Bear.py b/coalib/bears/Bear.py\n--- a/coalib/bears/Bear.py\n+++ b/coalib/bears/Bear.py\n@@ -5,6 +5,7 @@\n from coalib.output.printers.LogPrinter import LogPrinter\n from coalib.settings.FunctionMetadata import FunctionMetadata\n from coalib.settings.Section import Section\n+from coalib.settings.ConfigurationGathering import get_config_directory\n \n \n class Bear(Printer, LogPrinter):\n@@ -180,3 +181,11 @@\n                  that serves a more detailed description of what's missing.\n         \"\"\"\n         return True\n+\n+    def get_config_dir(self):\n+        \"\"\"\n+        Gives the directory where the configuration file is\n+\n+        :return: Directory of the config file\n+        \"\"\"\n+        return get_config_directory(self.section)\n", "issue": "git commit bear doesn't work if coala isn't run in the same directory\nit should also work if I provide a coafile with `-c`, @Makman2 can you fix that soonish? This is kind of the reason why this breaks everywhere for my gitmate experiments.\n\n", "before_files": [{"content": "import traceback\nfrom pyprint.Printer import Printer\n\nfrom coalib.misc.Decorators import enforce_signature\nfrom coalib.output.printers.LogPrinter import LogPrinter\nfrom coalib.settings.FunctionMetadata import FunctionMetadata\nfrom coalib.settings.Section import Section\n\n\nclass Bear(Printer, LogPrinter):\n    \"\"\"\n    A bear contains the actual subroutine that is responsible for checking\n    source code for certain specifications. However it can actually do\n    whatever it wants with the files it gets. If you are missing some Result\n    type, feel free to contact us and/or help us extending the coalib.\n\n    This is the base class for every bear. If you want to write an bear, you\n    will probably want to look at the GlobalBear and LocalBear classes that\n    inherit from this class. In any case you'll want to overwrite at least the\n    run method. You can send debug/warning/error messages through the\n    debug(), warn(), err() functions. These will send the\n    appropriate messages so that they are outputted. Be aware that if you use\n    err(), you are expected to also terminate the bear run-through\n    immediately.\n\n    If you need some setup or teardown for your bear, feel free to overwrite\n    the set_up() and tear_down() functions. They will be invoked\n    before/after every run invocation.\n\n    Settings are available at all times through self.section.\n    \"\"\"\n\n    @enforce_signature\n    def __init__(self,\n                 section: Section,\n                 message_queue,\n                 timeout=0):\n        \"\"\"\n        Constructs a new bear.\n\n        :param section:       The section object where bear settings are\n                              contained.\n        :param message_queue: The queue object for messages. Can be `None`.\n        :param timeout:       The time the bear is allowed to run. To set no\n                              time limit, use 0.\n        :raises TypeError:    Raised when `message_queue` is no queue.\n        :raises RuntimeError: Raised when bear requirements are not fulfilled.\n        \"\"\"\n        Printer.__init__(self)\n        LogPrinter.__init__(self, self)\n\n        if message_queue is not None and not hasattr(message_queue, \"put\"):\n            raise TypeError(\"message_queue has to be a Queue or None.\")\n\n        self.section = section\n        self.message_queue = message_queue\n        self.timeout = timeout\n\n        cp = type(self).check_prerequisites()\n        if cp is not True:\n            error_string = (\"The bear \" + type(self).__name__ +\n                            \" does not fulfill all requirements.\")\n            if cp is not False:\n                error_string += \" \" + cp\n\n            self.warn(error_string)\n            raise RuntimeError(error_string)\n\n    def _print(self, output, **kwargs):\n        self.debug(output)\n\n    def log_message(self, log_message, timestamp=None, **kwargs):\n        if self.message_queue is not None:\n            self.message_queue.put(log_message)\n\n    def run(self, *args, dependency_results=None, **kwargs):\n        raise NotImplementedError\n\n    def run_bear_from_section(self, args, kwargs):\n        try:\n            kwargs.update(\n                self.get_metadata().create_params_from_section(self.section))\n        except ValueError as err:\n            self.warn(\"The bear {} cannot be executed.\".format(\n                type(self).__name__), str(err))\n            return\n\n        return self.run(*args, **kwargs)\n\n    def execute(self, *args, **kwargs):\n        name = type(self).__name__\n        try:\n            self.debug(\"Running bear {}...\".format(name))\n            # If it's already a list it won't change it\n            return list(self.run_bear_from_section(args, kwargs) or [])\n        except:\n            self.warn(\n                \"Bear {} failed to run. Take a look at debug messages for \"\n                \"further information.\".format(name))\n            self.debug(\n                \"The bear {bear} raised an exception. If you are the writer \"\n                \"of this bear, please make sure to catch all exceptions. If \"\n                \"not and this error annoys you, you might want to get in \"\n                \"contact with the writer of this bear.\\n\\nTraceback \"\n                \"information is provided below:\\n\\n{traceback}\"\n                \"\\n\".format(bear=name, traceback=traceback.format_exc()))\n\n    @staticmethod\n    def kind():\n        \"\"\"\n        :return: The kind of the bear\n        \"\"\"\n        raise NotImplementedError\n\n    @classmethod\n    def get_metadata(cls):\n        \"\"\"\n        :return: Metadata for the run function. However parameters like `self`\n                 or parameters implicitly used by coala (e.g. filename for\n                 local bears) are already removed.\n        \"\"\"\n        return FunctionMetadata.from_function(\n            cls.run,\n            omit={\"self\", \"dependency_results\"})\n\n    @classmethod\n    def missing_dependencies(cls, lst):\n        \"\"\"\n        Checks if the given list contains all dependencies.\n\n        :param lst: A list of all already resolved bear classes (not\n                    instances).\n        :return:    A list of missing dependencies.\n        \"\"\"\n        dep_classes = cls.get_dependencies()\n\n        for item in lst:\n            if item in dep_classes:\n                dep_classes.remove(item)\n\n        return dep_classes\n\n    @staticmethod\n    def get_dependencies():\n        \"\"\"\n        Retrieves bear classes that are to be executed before this bear gets\n        executed. The results of these bears will then be passed to the\n        run method as a dict via the dependency_results argument. The dict\n        will have the name of the Bear as key and the list of its results as\n        results.\n\n        :return: A list of bear classes.\n        \"\"\"\n        return []\n\n    @classmethod\n    def get_non_optional_settings(cls):\n        \"\"\"\n        This method has to determine which settings are needed by this bear.\n        The user will be prompted for needed settings that are not available\n        in the settings file so don't include settings where a default value\n        would do.\n\n        :return: A dictionary of needed settings as keys and a tuple of help\n                 text and annotation as values\n        \"\"\"\n        return cls.get_metadata().non_optional_params\n\n    @classmethod\n    def check_prerequisites(cls):\n        \"\"\"\n        Checks whether needed runtime prerequisites of the bear are satisfied.\n\n        This function gets executed at construction and returns True by\n        default.\n\n        Section value requirements shall be checked inside the `run` method.\n\n        :return: True if prerequisites are satisfied, else False or a string\n                 that serves a more detailed description of what's missing.\n        \"\"\"\n        return True\n", "path": "coalib/bears/Bear.py"}, {"content": "import shutil\n\nfrom coalib.bears.GlobalBear import GlobalBear\nfrom coalib.misc.Shell import run_shell_command\nfrom coalib.results.Result import Result\n\n\nclass GitCommitBear(GlobalBear):\n    _git_command = \"git log -1 --pretty=%B\"\n\n    @classmethod\n    def check_prerequisites(cls):\n        if shutil.which(\"git\") is None:\n            return \"git is not installed.\"\n        else:\n            return True\n\n    def run(self,\n            shortlog_length: int=50,\n            body_line_length: int=73,\n            force_body: bool=False,\n            allow_empty_commit_message: bool=False):\n        \"\"\"\n        Checks the current git commit message at HEAD.\n\n        This bear ensures that the shortlog and body do not exceed a given\n        line-length and that a newline lies between them.\n\n        :param shortlog_length:            The maximum length of the shortlog.\n                                           The shortlog is the first line of\n                                           the commit message. The newline\n                                           character at end does not count to\n                                           the length.\n        :param body_line_length:           The maximum line-length of the body.\n                                           The newline character at each line\n                                           end does not count to the length.\n        :param force_body:                 Whether a body shall exist or not.\n        :param allow_empty_commit_message: Whether empty commit messages are\n                                           allowed or not.\n        \"\"\"\n        stdout, stderr = run_shell_command(self._git_command)\n\n        if stderr:\n            self.err(\"git:\", repr(stderr))\n            return\n\n        # git automatically removes trailing whitespaces. Also we need to\n        # remove the last \\n printed to align the prompt onto the next line.\n        stdout = stdout.splitlines()[:-1]\n\n        if len(stdout) == 0:\n            if not allow_empty_commit_message:\n                yield Result(self, \"HEAD commit has no message.\")\n            return\n\n        yield from self.check_shortlog(shortlog_length, stdout[0])\n        yield from self.check_body(body_line_length, force_body, stdout[1:])\n\n    def check_shortlog(self, shortlog_length, shortlog):\n        \"\"\"\n        Checks the given shortlog.\n\n        :param shortlog_length: The maximum length of the shortlog. The newline\n                                character at end does not count to the length.\n        :param shortlog:        The shortlog message string.\n        \"\"\"\n        if len(shortlog) > shortlog_length:\n            yield Result(self, \"Shortlog of HEAD commit is too long.\")\n\n    def check_body(self, body_line_length, force_body, body):\n        \"\"\"\n        Checks the given commit body.\n\n        :param body_line_length: The maximum line-length of the body. The\n                                 newline character at each line end does not\n                                 count to the length.\n        :param force_body:       Whether a body shall exist or not.\n        :param body:             The commit body splitted by lines.\n        \"\"\"\n        if len(body) == 0:\n            if force_body:\n                yield Result(self, \"No commit message body at HEAD.\")\n            return\n\n        if body[0] != \"\":\n            yield Result(self, \"No newline between shortlog and body at HEAD.\")\n            return\n\n        if any(len(line) > body_line_length for line in body[1:]):\n            yield Result(self, \"Body of HEAD commit contains too long lines.\")\n", "path": "bears/vcs/git/GitCommitBear.py"}], "after_files": [{"content": "import traceback\nfrom pyprint.Printer import Printer\n\nfrom coalib.misc.Decorators import enforce_signature\nfrom coalib.output.printers.LogPrinter import LogPrinter\nfrom coalib.settings.FunctionMetadata import FunctionMetadata\nfrom coalib.settings.Section import Section\nfrom coalib.settings.ConfigurationGathering import get_config_directory\n\n\nclass Bear(Printer, LogPrinter):\n    \"\"\"\n    A bear contains the actual subroutine that is responsible for checking\n    source code for certain specifications. However it can actually do\n    whatever it wants with the files it gets. If you are missing some Result\n    type, feel free to contact us and/or help us extending the coalib.\n\n    This is the base class for every bear. If you want to write an bear, you\n    will probably want to look at the GlobalBear and LocalBear classes that\n    inherit from this class. In any case you'll want to overwrite at least the\n    run method. You can send debug/warning/error messages through the\n    debug(), warn(), err() functions. These will send the\n    appropriate messages so that they are outputted. Be aware that if you use\n    err(), you are expected to also terminate the bear run-through\n    immediately.\n\n    If you need some setup or teardown for your bear, feel free to overwrite\n    the set_up() and tear_down() functions. They will be invoked\n    before/after every run invocation.\n\n    Settings are available at all times through self.section.\n    \"\"\"\n\n    @enforce_signature\n    def __init__(self,\n                 section: Section,\n                 message_queue,\n                 timeout=0):\n        \"\"\"\n        Constructs a new bear.\n\n        :param section:       The section object where bear settings are\n                              contained.\n        :param message_queue: The queue object for messages. Can be `None`.\n        :param timeout:       The time the bear is allowed to run. To set no\n                              time limit, use 0.\n        :raises TypeError:    Raised when `message_queue` is no queue.\n        :raises RuntimeError: Raised when bear requirements are not fulfilled.\n        \"\"\"\n        Printer.__init__(self)\n        LogPrinter.__init__(self, self)\n\n        if message_queue is not None and not hasattr(message_queue, \"put\"):\n            raise TypeError(\"message_queue has to be a Queue or None.\")\n\n        self.section = section\n        self.message_queue = message_queue\n        self.timeout = timeout\n\n        cp = type(self).check_prerequisites()\n        if cp is not True:\n            error_string = (\"The bear \" + type(self).__name__ +\n                            \" does not fulfill all requirements.\")\n            if cp is not False:\n                error_string += \" \" + cp\n\n            self.warn(error_string)\n            raise RuntimeError(error_string)\n\n    def _print(self, output, **kwargs):\n        self.debug(output)\n\n    def log_message(self, log_message, timestamp=None, **kwargs):\n        if self.message_queue is not None:\n            self.message_queue.put(log_message)\n\n    def run(self, *args, dependency_results=None, **kwargs):\n        raise NotImplementedError\n\n    def run_bear_from_section(self, args, kwargs):\n        try:\n            kwargs.update(\n                self.get_metadata().create_params_from_section(self.section))\n        except ValueError as err:\n            self.warn(\"The bear {} cannot be executed.\".format(\n                type(self).__name__), str(err))\n            return\n\n        return self.run(*args, **kwargs)\n\n    def execute(self, *args, **kwargs):\n        name = type(self).__name__\n        try:\n            self.debug(\"Running bear {}...\".format(name))\n            # If it's already a list it won't change it\n            return list(self.run_bear_from_section(args, kwargs) or [])\n        except:\n            self.warn(\n                \"Bear {} failed to run. Take a look at debug messages for \"\n                \"further information.\".format(name))\n            self.debug(\n                \"The bear {bear} raised an exception. If you are the writer \"\n                \"of this bear, please make sure to catch all exceptions. If \"\n                \"not and this error annoys you, you might want to get in \"\n                \"contact with the writer of this bear.\\n\\nTraceback \"\n                \"information is provided below:\\n\\n{traceback}\"\n                \"\\n\".format(bear=name, traceback=traceback.format_exc()))\n\n    @staticmethod\n    def kind():\n        \"\"\"\n        :return: The kind of the bear\n        \"\"\"\n        raise NotImplementedError\n\n    @classmethod\n    def get_metadata(cls):\n        \"\"\"\n        :return: Metadata for the run function. However parameters like `self`\n                 or parameters implicitly used by coala (e.g. filename for\n                 local bears) are already removed.\n        \"\"\"\n        return FunctionMetadata.from_function(\n            cls.run,\n            omit={\"self\", \"dependency_results\"})\n\n    @classmethod\n    def missing_dependencies(cls, lst):\n        \"\"\"\n        Checks if the given list contains all dependencies.\n\n        :param lst: A list of all already resolved bear classes (not\n                    instances).\n        :return:    A list of missing dependencies.\n        \"\"\"\n        dep_classes = cls.get_dependencies()\n\n        for item in lst:\n            if item in dep_classes:\n                dep_classes.remove(item)\n\n        return dep_classes\n\n    @staticmethod\n    def get_dependencies():\n        \"\"\"\n        Retrieves bear classes that are to be executed before this bear gets\n        executed. The results of these bears will then be passed to the\n        run method as a dict via the dependency_results argument. The dict\n        will have the name of the Bear as key and the list of its results as\n        results.\n\n        :return: A list of bear classes.\n        \"\"\"\n        return []\n\n    @classmethod\n    def get_non_optional_settings(cls):\n        \"\"\"\n        This method has to determine which settings are needed by this bear.\n        The user will be prompted for needed settings that are not available\n        in the settings file so don't include settings where a default value\n        would do.\n\n        :return: A dictionary of needed settings as keys and a tuple of help\n                 text and annotation as values\n        \"\"\"\n        return cls.get_metadata().non_optional_params\n\n    @classmethod\n    def check_prerequisites(cls):\n        \"\"\"\n        Checks whether needed runtime prerequisites of the bear are satisfied.\n\n        This function gets executed at construction and returns True by\n        default.\n\n        Section value requirements shall be checked inside the `run` method.\n\n        :return: True if prerequisites are satisfied, else False or a string\n                 that serves a more detailed description of what's missing.\n        \"\"\"\n        return True\n\n    def get_config_dir(self):\n        \"\"\"\n        Gives the directory where the configuration file is\n\n        :return: Directory of the config file\n        \"\"\"\n        return get_config_directory(self.section)\n", "path": "coalib/bears/Bear.py"}, {"content": "import shutil\nimport os\n\nfrom coalib.bears.GlobalBear import GlobalBear\nfrom coalib.misc.Shell import run_shell_command\nfrom coalib.results.Result import Result\n\n\nclass GitCommitBear(GlobalBear):\n    _git_command = \"git log -1 --pretty=%B\"\n\n    @classmethod\n    def check_prerequisites(cls):\n        if shutil.which(\"git\") is None:\n            return \"git is not installed.\"\n        else:\n            return True\n\n    def run(self,\n            shortlog_length: int=50,\n            body_line_length: int=73,\n            force_body: bool=False,\n            allow_empty_commit_message: bool=False):\n        \"\"\"\n        Checks the current git commit message at HEAD.\n\n        This bear ensures that the shortlog and body do not exceed a given\n        line-length and that a newline lies between them.\n\n        :param shortlog_length:            The maximum length of the shortlog.\n                                           The shortlog is the first line of\n                                           the commit message. The newline\n                                           character at end does not count to\n                                           the length.\n        :param body_line_length:           The maximum line-length of the body.\n                                           The newline character at each line\n                                           end does not count to the length.\n        :param force_body:                 Whether a body shall exist or not.\n        :param allow_empty_commit_message: Whether empty commit messages are\n                                           allowed or not.\n        \"\"\"\n        config_dir = self.get_config_dir()\n        old_dir = os.getcwd()\n        if config_dir:\n            os.chdir(config_dir)\n        stdout, stderr = run_shell_command(self._git_command)\n\n        if stderr:\n            self.err(\"git:\", repr(stderr))\n            return\n\n        # git automatically removes trailing whitespaces. Also we need to\n        # remove the last \\n printed to align the prompt onto the next line.\n        stdout = stdout.splitlines()[:-1]\n\n        if len(stdout) == 0:\n            if not allow_empty_commit_message:\n                yield Result(self, \"HEAD commit has no message.\")\n            return\n\n        yield from self.check_shortlog(shortlog_length, stdout[0])\n        yield from self.check_body(body_line_length, force_body, stdout[1:])\n\n        os.chdir(old_dir)\n\n    def check_shortlog(self, shortlog_length, shortlog):\n        \"\"\"\n        Checks the given shortlog.\n\n        :param shortlog_length: The maximum length of the shortlog. The newline\n                                character at end does not count to the length.\n        :param shortlog:        The shortlog message string.\n        \"\"\"\n        if len(shortlog) > shortlog_length:\n            yield Result(self, \"Shortlog of HEAD commit is too long.\")\n\n    def check_body(self, body_line_length, force_body, body):\n        \"\"\"\n        Checks the given commit body.\n\n        :param body_line_length: The maximum line-length of the body. The\n                                 newline character at each line end does not\n                                 count to the length.\n        :param force_body:       Whether a body shall exist or not.\n        :param body:             The commit body splitted by lines.\n        \"\"\"\n        if len(body) == 0:\n            if force_body:\n                yield Result(self, \"No commit message body at HEAD.\")\n            return\n\n        if body[0] != \"\":\n            yield Result(self, \"No newline between shortlog and body at HEAD.\")\n            return\n\n        if any(len(line) > body_line_length for line in body[1:]):\n            yield Result(self, \"Body of HEAD commit contains too long lines.\")\n", "path": "bears/vcs/git/GitCommitBear.py"}]}