We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
`nikola -V/--version` doesn’t work outside of a site
```
(nikola-py2)[kwpolska@kw-cassandra ~WORKON_HOME]% nikola --version
[2014-01-04T17:40:42Z] ERROR: Nikola: This command needs to run inside an existing Nikola site.
(nikola-py2)[kwpolska@kw-cassandra ~WORKON_HOME]% cd ~/nikola
(nikola-py2)[kwpolska@kw-cassandra nikola Gmaster]% nikola --version
Nikola version 6.2.1
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `nikola/main.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 
3 # Copyright © 2012-2014 Roberto Alsina and others.
4 
5 # Permission is hereby granted, free of charge, to any
6 # person obtaining a copy of this software and associated
7 # documentation files (the "Software"), to deal in the
8 # Software without restriction, including without limitation
9 # the rights to use, copy, modify, merge, publish,
10 # distribute, sublicense, and/or sell copies of the
11 # Software, and to permit persons to whom the Software is
12 # furnished to do so, subject to the following conditions:
13 #
14 # The above copyright notice and this permission notice
15 # shall be included in all copies or substantial portions of
16 # the Software.
17 #
18 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
19 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
20 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
21 # PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
22 # OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
23 # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
24 # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 
27 from __future__ import print_function, unicode_literals
28 from operator import attrgetter
29 import os
30 import shutil
31 import sys
32 import traceback
33 
34 from doit.loader import generate_tasks
35 from doit.cmd_base import TaskLoader
36 from doit.reporter import ExecutedOnlyReporter
37 from doit.doit_cmd import DoitMain
38 from doit.cmd_help import Help as DoitHelp
39 from doit.cmd_run import Run as DoitRun
40 from doit.cmd_clean import Clean as DoitClean
41 from doit.cmd_auto import Auto as DoitAuto
42 from logbook import NullHandler
43 
44 from . import __version__
45 from .nikola import Nikola
46 from .utils import _reload, sys_decode, get_root_dir, LOGGER, STRICT_HANDLER
47 
48 
49 config = {}
50 
51 
52 def main(args):
53     quiet = False
54     if len(args) > 0 and args[0] == 'build' and '--strict' in args:
55         LOGGER.notice('Running in strict mode')
56         STRICT_HANDLER.push_application()
57     if len(args) > 0 and args[0] == 'build' and '-q' in args or '--quiet' in args:
58         nullhandler = NullHandler()
59         nullhandler.push_application()
60         quiet = True
61     global config
62 
63     root = get_root_dir()
64     if root:
65         os.chdir(root)
66 
67     sys.path.append('')
68     try:
69         import conf
70         _reload(conf)
71         config = conf.__dict__
72     except Exception:
73         if os.path.exists('conf.py'):
74             msg = traceback.format_exc(0).splitlines()[1]
75             LOGGER.error('In conf.py line {0}: {1}'.format(sys.exc_info()[2].tb_lineno, msg))
76             sys.exit(1)
77         config = {}
78 
79     site = Nikola(**config)
80     return DoitNikola(site, quiet).run(args)
81 
82 
83 class Help(DoitHelp):
84     """show Nikola usage instead of doit """
85 
86     @staticmethod
87     def print_usage(cmds):
88         """print nikola "usage" (basic help) instructions"""
89         print("Nikola is a tool to create static websites and blogs. For full documentation and more information, please visit http://getnikola.com\n\n")
90         print("Available commands:")
91         for cmd in sorted(cmds.values(), key=attrgetter('name')):
92             print("  nikola %-*s %s" % (20, cmd.name, cmd.doc_purpose))
93         print("")
94         print("  nikola help                 show help / reference")
95         print("  nikola help <command>       show command usage")
96         print("  nikola help <task-name>     show task usage")
97 
98 
99 class Build(DoitRun):
100     """expose "run" command as "build" for backward compatibility"""
101     def __init__(self, *args, **kw):
102         opts = list(self.cmd_options)
103         opts.append(
104             {
105                 'name': 'strict',
106                 'long': 'strict',
107                 'default': False,
108                 'type': bool,
109                 'help': "Fail on things that would normally be warnings.",
110             }
111         )
112         opts.append(
113             {
114                 'name': 'quiet',
115                 'long': 'quiet',
116                 'short': 'q',
117                 'default': False,
118                 'type': bool,
119                 'help': "Run quietly.",
120             }
121         )
122         self.cmd_options = tuple(opts)
123         super(Build, self).__init__(*args, **kw)
124 
125 
126 class Clean(DoitClean):
127     """A clean that removes cache/"""
128 
129     def clean_tasks(self, tasks, dryrun):
130         if not dryrun and config:
131             cache_folder = config.get('CACHE_FOLDER', 'cache')
132             if os.path.exists(cache_folder):
133                 shutil.rmtree(cache_folder)
134         return super(Clean, self).clean_tasks(tasks, dryrun)
135 
136 # Nikola has its own "auto" commands that uses livereload.
137 # Expose original doit "auto" command as "doit_auto".
138 DoitAuto.name = 'doit_auto'
139 
140 
141 class NikolaTaskLoader(TaskLoader):
142     """custom task loader to get tasks from Nikola instead of dodo.py file"""
143     def __init__(self, nikola, quiet=False):
144         self.nikola = nikola
145         self.quiet = quiet
146 
147     def load_tasks(self, cmd, opt_values, pos_args):
148         if self.quiet:
149             DOIT_CONFIG = {
150                 'verbosity': 0,
151                 'reporter': 'zero',
152             }
153         else:
154             DOIT_CONFIG = {
155                 'reporter': ExecutedOnlyReporter,
156             }
157         DOIT_CONFIG['default_tasks'] = ['render_site', 'post_render']
158         tasks = generate_tasks(
159             'render_site',
160             self.nikola.gen_tasks('render_site', "Task", 'Group of tasks to render the site.'))
161         latetasks = generate_tasks(
162             'post_render',
163             self.nikola.gen_tasks('post_render', "LateTask", 'Group of tasks to be executes after site is rendered.'))
164         return tasks + latetasks, DOIT_CONFIG
165 
166 
167 class DoitNikola(DoitMain):
168     # overwite help command
169     DOIT_CMDS = list(DoitMain.DOIT_CMDS) + [Help, Build, Clean, DoitAuto]
170     TASK_LOADER = NikolaTaskLoader
171 
172     def __init__(self, nikola, quiet=False):
173         self.nikola = nikola
174         self.task_loader = self.TASK_LOADER(nikola, quiet)
175 
176     def get_commands(self):
177         # core doit commands
178         cmds = DoitMain.get_commands(self)
179         # load nikola commands
180         for name, cmd in self.nikola.commands.items():
181             cmds[name] = cmd
182         return cmds
183 
184     def run(self, cmd_args):
185         sub_cmds = self.get_commands()
186         args = self.process_args(cmd_args)
187         args = [sys_decode(arg) for arg in args]
188 
189         if len(args) == 0 or any(arg in ["--help", '-h'] for arg in args):
190             cmd_args = ['help']
191             args = ['help']
192             # Hide run because Nikola uses build
193             sub_cmds.pop('run')
194 
195         if len(args) == 0 or args[0] not in sub_cmds.keys() or \
196                 args[0] == 'build':
197             # Check for conf.py before launching run
198             if not self.nikola.configured:
199                 LOGGER.error("This command needs to run inside an "
200                              "existing Nikola site.")
201                 return False
202         return super(DoitNikola, self).run(cmd_args)
203 
204     @staticmethod
205     def print_version():
206         print("Nikola version " + __version__)
207
```

Path: `nikola/plugins/command/version.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 
3 # Copyright © 2012-2014 Roberto Alsina and others.
4 
5 # Permission is hereby granted, free of charge, to any
6 # person obtaining a copy of this software and associated
7 # documentation files (the "Software"), to deal in the
8 # Software without restriction, including without limitation
9 # the rights to use, copy, modify, merge, publish,
10 # distribute, sublicense, and/or sell copies of the
11 # Software, and to permit persons to whom the Software is
12 # furnished to do so, subject to the following conditions:
13 #
14 # The above copyright notice and this permission notice
15 # shall be included in all copies or substantial portions of
16 # the Software.
17 #
18 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
19 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
20 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
21 # PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
22 # OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
23 # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
24 # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 
27 from __future__ import print_function
28 
29 from nikola.plugin_categories import Command
30 from nikola import __version__
31 
32 
33 class CommandVersion(Command):
34     """Print the version."""
35 
36     name = "version"
37 
38     doc_usage = ""
39     needs_config = False
40     doc_purpose = "print the Nikola version number"
41 
42     def _execute(self, options={}, args=None):
43         """Print the version number."""
44         print("Nikola version " + __version__)
45
```
--- 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/nikola/main.py b/nikola/main.py
--- a/nikola/main.py
+++ b/nikola/main.py
@@ -191,7 +191,9 @@
             args = ['help']
             # Hide run because Nikola uses build
             sub_cmds.pop('run')
-
+        if len(args) == 0 or any(arg in ["--version", '-V'] for arg in args):
+            cmd_args = ['version']
+            args = ['version']
         if len(args) == 0 or args[0] not in sub_cmds.keys() or \
                 args[0] == 'build':
             # Check for conf.py before launching run
@@ -203,4 +205,4 @@
 
     @staticmethod
     def print_version():
-        print("Nikola version " + __version__)
+        print("Nikola v" + __version__)
diff --git a/nikola/plugins/command/version.py b/nikola/plugins/command/version.py
--- a/nikola/plugins/command/version.py
+++ b/nikola/plugins/command/version.py
@@ -41,4 +41,4 @@
 
     def _execute(self, options={}, args=None):
         """Print the version number."""
-        print("Nikola version " + __version__)
+        print("Nikola v" + __version__)

{"golden_diff": "diff --git a/nikola/main.py b/nikola/main.py\n--- a/nikola/main.py\n+++ b/nikola/main.py\n@@ -191,7 +191,9 @@\n             args = ['help']\n             # Hide run because Nikola uses build\n             sub_cmds.pop('run')\n-\n+        if len(args) == 0 or any(arg in [\"--version\", '-V'] for arg in args):\n+            cmd_args = ['version']\n+            args = ['version']\n         if len(args) == 0 or args[0] not in sub_cmds.keys() or \\\n                 args[0] == 'build':\n             # Check for conf.py before launching run\n@@ -203,4 +205,4 @@\n \n     @staticmethod\n     def print_version():\n-        print(\"Nikola version \" + __version__)\n+        print(\"Nikola v\" + __version__)\ndiff --git a/nikola/plugins/command/version.py b/nikola/plugins/command/version.py\n--- a/nikola/plugins/command/version.py\n+++ b/nikola/plugins/command/version.py\n@@ -41,4 +41,4 @@\n \n     def _execute(self, options={}, args=None):\n         \"\"\"Print the version number.\"\"\"\n-        print(\"Nikola version \" + __version__)\n+        print(\"Nikola v\" + __version__)\n", "issue": "`nikola -V/--version` doesn\u2019t work outside of a site\n```\n(nikola-py2)[kwpolska@kw-cassandra ~WORKON_HOME]% nikola --version\n[2014-01-04T17:40:42Z] ERROR: Nikola: This command needs to run inside an existing Nikola site.\n(nikola-py2)[kwpolska@kw-cassandra ~WORKON_HOME]% cd ~/nikola\n(nikola-py2)[kwpolska@kw-cassandra nikola Gmaster]% nikola --version\nNikola version 6.2.1\n```\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\n# Copyright \u00a9 2012-2014 Roberto Alsina and others.\n\n# Permission is hereby granted, free of charge, to any\n# person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the\n# Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the\n# Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice\n# shall be included in all copies or substantial portions of\n# the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\n# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfrom __future__ import print_function, unicode_literals\nfrom operator import attrgetter\nimport os\nimport shutil\nimport sys\nimport traceback\n\nfrom doit.loader import generate_tasks\nfrom doit.cmd_base import TaskLoader\nfrom doit.reporter import ExecutedOnlyReporter\nfrom doit.doit_cmd import DoitMain\nfrom doit.cmd_help import Help as DoitHelp\nfrom doit.cmd_run import Run as DoitRun\nfrom doit.cmd_clean import Clean as DoitClean\nfrom doit.cmd_auto import Auto as DoitAuto\nfrom logbook import NullHandler\n\nfrom . import __version__\nfrom .nikola import Nikola\nfrom .utils import _reload, sys_decode, get_root_dir, LOGGER, STRICT_HANDLER\n\n\nconfig = {}\n\n\ndef main(args):\n    quiet = False\n    if len(args) > 0 and args[0] == 'build' and '--strict' in args:\n        LOGGER.notice('Running in strict mode')\n        STRICT_HANDLER.push_application()\n    if len(args) > 0 and args[0] == 'build' and '-q' in args or '--quiet' in args:\n        nullhandler = NullHandler()\n        nullhandler.push_application()\n        quiet = True\n    global config\n\n    root = get_root_dir()\n    if root:\n        os.chdir(root)\n\n    sys.path.append('')\n    try:\n        import conf\n        _reload(conf)\n        config = conf.__dict__\n    except Exception:\n        if os.path.exists('conf.py'):\n            msg = traceback.format_exc(0).splitlines()[1]\n            LOGGER.error('In conf.py line {0}: {1}'.format(sys.exc_info()[2].tb_lineno, msg))\n            sys.exit(1)\n        config = {}\n\n    site = Nikola(**config)\n    return DoitNikola(site, quiet).run(args)\n\n\nclass Help(DoitHelp):\n    \"\"\"show Nikola usage instead of doit \"\"\"\n\n    @staticmethod\n    def print_usage(cmds):\n        \"\"\"print nikola \"usage\" (basic help) instructions\"\"\"\n        print(\"Nikola is a tool to create static websites and blogs. For full documentation and more information, please visit http://getnikola.com\\n\\n\")\n        print(\"Available commands:\")\n        for cmd in sorted(cmds.values(), key=attrgetter('name')):\n            print(\"  nikola %-*s %s\" % (20, cmd.name, cmd.doc_purpose))\n        print(\"\")\n        print(\"  nikola help                 show help / reference\")\n        print(\"  nikola help <command>       show command usage\")\n        print(\"  nikola help <task-name>     show task usage\")\n\n\nclass Build(DoitRun):\n    \"\"\"expose \"run\" command as \"build\" for backward compatibility\"\"\"\n    def __init__(self, *args, **kw):\n        opts = list(self.cmd_options)\n        opts.append(\n            {\n                'name': 'strict',\n                'long': 'strict',\n                'default': False,\n                'type': bool,\n                'help': \"Fail on things that would normally be warnings.\",\n            }\n        )\n        opts.append(\n            {\n                'name': 'quiet',\n                'long': 'quiet',\n                'short': 'q',\n                'default': False,\n                'type': bool,\n                'help': \"Run quietly.\",\n            }\n        )\n        self.cmd_options = tuple(opts)\n        super(Build, self).__init__(*args, **kw)\n\n\nclass Clean(DoitClean):\n    \"\"\"A clean that removes cache/\"\"\"\n\n    def clean_tasks(self, tasks, dryrun):\n        if not dryrun and config:\n            cache_folder = config.get('CACHE_FOLDER', 'cache')\n            if os.path.exists(cache_folder):\n                shutil.rmtree(cache_folder)\n        return super(Clean, self).clean_tasks(tasks, dryrun)\n\n# Nikola has its own \"auto\" commands that uses livereload.\n# Expose original doit \"auto\" command as \"doit_auto\".\nDoitAuto.name = 'doit_auto'\n\n\nclass NikolaTaskLoader(TaskLoader):\n    \"\"\"custom task loader to get tasks from Nikola instead of dodo.py file\"\"\"\n    def __init__(self, nikola, quiet=False):\n        self.nikola = nikola\n        self.quiet = quiet\n\n    def load_tasks(self, cmd, opt_values, pos_args):\n        if self.quiet:\n            DOIT_CONFIG = {\n                'verbosity': 0,\n                'reporter': 'zero',\n            }\n        else:\n            DOIT_CONFIG = {\n                'reporter': ExecutedOnlyReporter,\n            }\n        DOIT_CONFIG['default_tasks'] = ['render_site', 'post_render']\n        tasks = generate_tasks(\n            'render_site',\n            self.nikola.gen_tasks('render_site', \"Task\", 'Group of tasks to render the site.'))\n        latetasks = generate_tasks(\n            'post_render',\n            self.nikola.gen_tasks('post_render', \"LateTask\", 'Group of tasks to be executes after site is rendered.'))\n        return tasks + latetasks, DOIT_CONFIG\n\n\nclass DoitNikola(DoitMain):\n    # overwite help command\n    DOIT_CMDS = list(DoitMain.DOIT_CMDS) + [Help, Build, Clean, DoitAuto]\n    TASK_LOADER = NikolaTaskLoader\n\n    def __init__(self, nikola, quiet=False):\n        self.nikola = nikola\n        self.task_loader = self.TASK_LOADER(nikola, quiet)\n\n    def get_commands(self):\n        # core doit commands\n        cmds = DoitMain.get_commands(self)\n        # load nikola commands\n        for name, cmd in self.nikola.commands.items():\n            cmds[name] = cmd\n        return cmds\n\n    def run(self, cmd_args):\n        sub_cmds = self.get_commands()\n        args = self.process_args(cmd_args)\n        args = [sys_decode(arg) for arg in args]\n\n        if len(args) == 0 or any(arg in [\"--help\", '-h'] for arg in args):\n            cmd_args = ['help']\n            args = ['help']\n            # Hide run because Nikola uses build\n            sub_cmds.pop('run')\n\n        if len(args) == 0 or args[0] not in sub_cmds.keys() or \\\n                args[0] == 'build':\n            # Check for conf.py before launching run\n            if not self.nikola.configured:\n                LOGGER.error(\"This command needs to run inside an \"\n                             \"existing Nikola site.\")\n                return False\n        return super(DoitNikola, self).run(cmd_args)\n\n    @staticmethod\n    def print_version():\n        print(\"Nikola version \" + __version__)\n", "path": "nikola/main.py"}, {"content": "# -*- coding: utf-8 -*-\n\n# Copyright \u00a9 2012-2014 Roberto Alsina and others.\n\n# Permission is hereby granted, free of charge, to any\n# person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the\n# Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the\n# Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice\n# shall be included in all copies or substantial portions of\n# the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\n# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfrom __future__ import print_function\n\nfrom nikola.plugin_categories import Command\nfrom nikola import __version__\n\n\nclass CommandVersion(Command):\n    \"\"\"Print the version.\"\"\"\n\n    name = \"version\"\n\n    doc_usage = \"\"\n    needs_config = False\n    doc_purpose = \"print the Nikola version number\"\n\n    def _execute(self, options={}, args=None):\n        \"\"\"Print the version number.\"\"\"\n        print(\"Nikola version \" + __version__)\n", "path": "nikola/plugins/command/version.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\n# Copyright \u00a9 2012-2014 Roberto Alsina and others.\n\n# Permission is hereby granted, free of charge, to any\n# person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the\n# Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the\n# Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice\n# shall be included in all copies or substantial portions of\n# the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\n# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfrom __future__ import print_function, unicode_literals\nfrom operator import attrgetter\nimport os\nimport shutil\nimport sys\nimport traceback\n\nfrom doit.loader import generate_tasks\nfrom doit.cmd_base import TaskLoader\nfrom doit.reporter import ExecutedOnlyReporter\nfrom doit.doit_cmd import DoitMain\nfrom doit.cmd_help import Help as DoitHelp\nfrom doit.cmd_run import Run as DoitRun\nfrom doit.cmd_clean import Clean as DoitClean\nfrom doit.cmd_auto import Auto as DoitAuto\nfrom logbook import NullHandler\n\nfrom . import __version__\nfrom .nikola import Nikola\nfrom .utils import _reload, sys_decode, get_root_dir, LOGGER, STRICT_HANDLER\n\n\nconfig = {}\n\n\ndef main(args):\n    quiet = False\n    if len(args) > 0 and args[0] == 'build' and '--strict' in args:\n        LOGGER.notice('Running in strict mode')\n        STRICT_HANDLER.push_application()\n    if len(args) > 0 and args[0] == 'build' and '-q' in args or '--quiet' in args:\n        nullhandler = NullHandler()\n        nullhandler.push_application()\n        quiet = True\n    global config\n\n    root = get_root_dir()\n    if root:\n        os.chdir(root)\n\n    sys.path.append('')\n    try:\n        import conf\n        _reload(conf)\n        config = conf.__dict__\n    except Exception:\n        if os.path.exists('conf.py'):\n            msg = traceback.format_exc(0).splitlines()[1]\n            LOGGER.error('In conf.py line {0}: {1}'.format(sys.exc_info()[2].tb_lineno, msg))\n            sys.exit(1)\n        config = {}\n\n    site = Nikola(**config)\n    return DoitNikola(site, quiet).run(args)\n\n\nclass Help(DoitHelp):\n    \"\"\"show Nikola usage instead of doit \"\"\"\n\n    @staticmethod\n    def print_usage(cmds):\n        \"\"\"print nikola \"usage\" (basic help) instructions\"\"\"\n        print(\"Nikola is a tool to create static websites and blogs. For full documentation and more information, please visit http://getnikola.com\\n\\n\")\n        print(\"Available commands:\")\n        for cmd in sorted(cmds.values(), key=attrgetter('name')):\n            print(\"  nikola %-*s %s\" % (20, cmd.name, cmd.doc_purpose))\n        print(\"\")\n        print(\"  nikola help                 show help / reference\")\n        print(\"  nikola help <command>       show command usage\")\n        print(\"  nikola help <task-name>     show task usage\")\n\n\nclass Build(DoitRun):\n    \"\"\"expose \"run\" command as \"build\" for backward compatibility\"\"\"\n    def __init__(self, *args, **kw):\n        opts = list(self.cmd_options)\n        opts.append(\n            {\n                'name': 'strict',\n                'long': 'strict',\n                'default': False,\n                'type': bool,\n                'help': \"Fail on things that would normally be warnings.\",\n            }\n        )\n        opts.append(\n            {\n                'name': 'quiet',\n                'long': 'quiet',\n                'short': 'q',\n                'default': False,\n                'type': bool,\n                'help': \"Run quietly.\",\n            }\n        )\n        self.cmd_options = tuple(opts)\n        super(Build, self).__init__(*args, **kw)\n\n\nclass Clean(DoitClean):\n    \"\"\"A clean that removes cache/\"\"\"\n\n    def clean_tasks(self, tasks, dryrun):\n        if not dryrun and config:\n            cache_folder = config.get('CACHE_FOLDER', 'cache')\n            if os.path.exists(cache_folder):\n                shutil.rmtree(cache_folder)\n        return super(Clean, self).clean_tasks(tasks, dryrun)\n\n# Nikola has its own \"auto\" commands that uses livereload.\n# Expose original doit \"auto\" command as \"doit_auto\".\nDoitAuto.name = 'doit_auto'\n\n\nclass NikolaTaskLoader(TaskLoader):\n    \"\"\"custom task loader to get tasks from Nikola instead of dodo.py file\"\"\"\n    def __init__(self, nikola, quiet=False):\n        self.nikola = nikola\n        self.quiet = quiet\n\n    def load_tasks(self, cmd, opt_values, pos_args):\n        if self.quiet:\n            DOIT_CONFIG = {\n                'verbosity': 0,\n                'reporter': 'zero',\n            }\n        else:\n            DOIT_CONFIG = {\n                'reporter': ExecutedOnlyReporter,\n            }\n        DOIT_CONFIG['default_tasks'] = ['render_site', 'post_render']\n        tasks = generate_tasks(\n            'render_site',\n            self.nikola.gen_tasks('render_site', \"Task\", 'Group of tasks to render the site.'))\n        latetasks = generate_tasks(\n            'post_render',\n            self.nikola.gen_tasks('post_render', \"LateTask\", 'Group of tasks to be executes after site is rendered.'))\n        return tasks + latetasks, DOIT_CONFIG\n\n\nclass DoitNikola(DoitMain):\n    # overwite help command\n    DOIT_CMDS = list(DoitMain.DOIT_CMDS) + [Help, Build, Clean, DoitAuto]\n    TASK_LOADER = NikolaTaskLoader\n\n    def __init__(self, nikola, quiet=False):\n        self.nikola = nikola\n        self.task_loader = self.TASK_LOADER(nikola, quiet)\n\n    def get_commands(self):\n        # core doit commands\n        cmds = DoitMain.get_commands(self)\n        # load nikola commands\n        for name, cmd in self.nikola.commands.items():\n            cmds[name] = cmd\n        return cmds\n\n    def run(self, cmd_args):\n        sub_cmds = self.get_commands()\n        args = self.process_args(cmd_args)\n        args = [sys_decode(arg) for arg in args]\n\n        if len(args) == 0 or any(arg in [\"--help\", '-h'] for arg in args):\n            cmd_args = ['help']\n            args = ['help']\n            # Hide run because Nikola uses build\n            sub_cmds.pop('run')\n        if len(args) == 0 or any(arg in [\"--version\", '-V'] for arg in args):\n            cmd_args = ['version']\n            args = ['version']\n        if len(args) == 0 or args[0] not in sub_cmds.keys() or \\\n                args[0] == 'build':\n            # Check for conf.py before launching run\n            if not self.nikola.configured:\n                LOGGER.error(\"This command needs to run inside an \"\n                             \"existing Nikola site.\")\n                return False\n        return super(DoitNikola, self).run(cmd_args)\n\n    @staticmethod\n    def print_version():\n        print(\"Nikola v\" + __version__)\n", "path": "nikola/main.py"}, {"content": "# -*- coding: utf-8 -*-\n\n# Copyright \u00a9 2012-2014 Roberto Alsina and others.\n\n# Permission is hereby granted, free of charge, to any\n# person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the\n# Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the\n# Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice\n# shall be included in all copies or substantial portions of\n# the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\n# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfrom __future__ import print_function\n\nfrom nikola.plugin_categories import Command\nfrom nikola import __version__\n\n\nclass CommandVersion(Command):\n    \"\"\"Print the version.\"\"\"\n\n    name = \"version\"\n\n    doc_usage = \"\"\n    needs_config = False\n    doc_purpose = \"print the Nikola version number\"\n\n    def _execute(self, options={}, args=None):\n        \"\"\"Print the version number.\"\"\"\n        print(\"Nikola v\" + __version__)\n", "path": "nikola/plugins/command/version.py"}]}