We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
utils.get_root_dir() should not be run for import_* and init
Here’s a fun thing you can try at home:

``` console
$ cd /tmp
$ nikola init site_1
[2014-03-14T15:39:05Z] INFO: init: Created empty site at site_1.
$ cd site_1
$ mkdir subdir
$ cd subdir
$ nikola init site_2
[2014-03-14T15:39:41Z] INFO: init: Created empty site at site_2.
$ ls -l .
total 0
$ ls -l ..
total 32
-rw-r--r-- 1 kwpolska kwpolska 27413 Mar 14 16:39 conf.py
-rw-r--r-- 1 kwpolska kwpolska  1923 Mar 14 16:39 conf.pyc
drwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 files/
drwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 galleries/
drwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 listings/
drwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 posts/
drwxr-xr-x 7 kwpolska kwpolska   160 Mar 14 16:39 site_2/    ← wat
drwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 stories/
drwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 subdir/
$
```

The same behavior applies to `import_*`:

``` console
$ pwd
/tmp/site_1/subdir
$ nikola import_wordpress ~/git/nikola/tests/wordpress_unicode_export.xml
[2014-03-14T15:41:24Z] INFO: init: Created empty site at new_site.
[2014-03-14T15:41:24Z] INFO: Nikola: Configuration will be written to: new_site/conf.py
$ ls -l .
total 0
$ ls -l ..
total 32
-rw-r--r-- 1 kwpolska kwpolska 27413 Mar 14 16:39 conf.py
-rw-r--r-- 1 kwpolska kwpolska  1923 Mar 14 16:39 conf.pyc
drwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 files/
drwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 galleries/
drwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 listings/
drwxr-xr-x 7 kwpolska kwpolska   180 Mar 14 16:41 new_site/  ← wat
drwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 posts/
drwxr-xr-x 7 kwpolska kwpolska   160 Mar 14 16:39 site_2/    ← wat
drwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 stories/
drwxr-xr-x 3 kwpolska kwpolska    40 Mar 14 16:39 subdir/
$ mkdir nesting_is_fun
$ cd nesting_is_fun
$ nikola import_wordpress ~/git/nikola/tests/wordpress_unicode_export.xml
[2014-03-14T15:42:05Z] NOTICE: Nikola: The folder new_site already exists - assuming that this is a already existing Nikola site.
[2014-03-14T15:42:05Z] INFO: Nikola: Configuration will be written to: new_site/conf.py.import_wordpress-20140314_164205
$
```

This can be dangerous — especially because one can put a file named `conf.py` anywhere higher in the directory structure and destroy his Nikola attempts.

How could we fix it?  We could just not run `utils.get_root_dir()` if the user wants to execute one of those commands (it’s executed in `__main__.py`).


--- 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     colorful = False
64     if sys.stderr.isatty():
65         colorful = True
66         try:
67             import colorama
68             colorama.init()
69         except ImportError:
70             if os.name == 'nt':
71                 colorful = False
72 
73     root = get_root_dir()
74     if root:
75         os.chdir(root)
76 
77     sys.path.append('')
78     try:
79         import conf
80         _reload(conf)
81         config = conf.__dict__
82     except Exception:
83         if os.path.exists('conf.py'):
84             msg = traceback.format_exc(0).splitlines()[1]
85             LOGGER.error('In conf.py line {0}: {1}'.format(sys.exc_info()[2].tb_lineno, msg))
86             sys.exit(1)
87         config = {}
88 
89     config.update({'__colorful__': colorful})
90 
91     site = Nikola(**config)
92     return DoitNikola(site, quiet).run(args)
93 
94 
95 class Help(DoitHelp):
96     """show Nikola usage instead of doit """
97 
98     @staticmethod
99     def print_usage(cmds):
100         """print nikola "usage" (basic help) instructions"""
101         print("Nikola is a tool to create static websites and blogs. For full documentation and more information, please visit http://getnikola.com/\n\n")
102         print("Available commands:")
103         for cmd in sorted(cmds.values(), key=attrgetter('name')):
104             print("  nikola %-*s %s" % (20, cmd.name, cmd.doc_purpose))
105         print("")
106         print("  nikola help                 show help / reference")
107         print("  nikola help <command>       show command usage")
108         print("  nikola help <task-name>     show task usage")
109 
110 
111 class Build(DoitRun):
112     """expose "run" command as "build" for backward compatibility"""
113     def __init__(self, *args, **kw):
114         opts = list(self.cmd_options)
115         opts.append(
116             {
117                 'name': 'strict',
118                 'long': 'strict',
119                 'default': False,
120                 'type': bool,
121                 'help': "Fail on things that would normally be warnings.",
122             }
123         )
124         opts.append(
125             {
126                 'name': 'quiet',
127                 'long': 'quiet',
128                 'short': 'q',
129                 'default': False,
130                 'type': bool,
131                 'help': "Run quietly.",
132             }
133         )
134         self.cmd_options = tuple(opts)
135         super(Build, self).__init__(*args, **kw)
136 
137 
138 class Clean(DoitClean):
139     """A clean that removes cache/"""
140 
141     def clean_tasks(self, tasks, dryrun):
142         if not dryrun and config:
143             cache_folder = config.get('CACHE_FOLDER', 'cache')
144             if os.path.exists(cache_folder):
145                 shutil.rmtree(cache_folder)
146         return super(Clean, self).clean_tasks(tasks, dryrun)
147 
148 # Nikola has its own "auto" commands that uses livereload.
149 # Expose original doit "auto" command as "doit_auto".
150 DoitAuto.name = 'doit_auto'
151 
152 
153 class NikolaTaskLoader(TaskLoader):
154     """custom task loader to get tasks from Nikola instead of dodo.py file"""
155     def __init__(self, nikola, quiet=False):
156         self.nikola = nikola
157         self.quiet = quiet
158 
159     def load_tasks(self, cmd, opt_values, pos_args):
160         if self.quiet:
161             DOIT_CONFIG = {
162                 'verbosity': 0,
163                 'reporter': 'zero',
164             }
165         else:
166             DOIT_CONFIG = {
167                 'reporter': ExecutedOnlyReporter,
168             }
169         DOIT_CONFIG['default_tasks'] = ['render_site', 'post_render']
170         tasks = generate_tasks(
171             'render_site',
172             self.nikola.gen_tasks('render_site', "Task", 'Group of tasks to render the site.'))
173         latetasks = generate_tasks(
174             'post_render',
175             self.nikola.gen_tasks('post_render', "LateTask", 'Group of tasks to be executes after site is rendered.'))
176         return tasks + latetasks, DOIT_CONFIG
177 
178 
179 class DoitNikola(DoitMain):
180     # overwite help command
181     DOIT_CMDS = list(DoitMain.DOIT_CMDS) + [Help, Build, Clean, DoitAuto]
182     TASK_LOADER = NikolaTaskLoader
183 
184     def __init__(self, nikola, quiet=False):
185         self.nikola = nikola
186         self.task_loader = self.TASK_LOADER(nikola, quiet)
187 
188     def get_commands(self):
189         # core doit commands
190         cmds = DoitMain.get_commands(self)
191         # load nikola commands
192         for name, cmd in self.nikola.commands.items():
193             cmds[name] = cmd
194         return cmds
195 
196     def run(self, cmd_args):
197         sub_cmds = self.get_commands()
198         args = self.process_args(cmd_args)
199         args = [sys_decode(arg) for arg in args]
200 
201         if len(args) == 0 or any(arg in ["--help", '-h'] for arg in args):
202             cmd_args = ['help']
203             args = ['help']
204             # Hide run because Nikola uses build
205             sub_cmds.pop('run')
206         if len(args) == 0 or any(arg in ["--version", '-V'] for arg in args):
207             cmd_args = ['version']
208             args = ['version']
209         if len(args) == 0 or args[0] not in sub_cmds.keys() or \
210                 args[0] == 'build':
211             # Check for conf.py before launching run
212             if not self.nikola.configured:
213                 LOGGER.error("This command needs to run inside an "
214                              "existing Nikola site.")
215                 return False
216         return super(DoitNikola, self).run(cmd_args)
217 
218     @staticmethod
219     def print_version():
220         print("Nikola v" + __version__)
221 
222 if __name__ == "__main__":
223     sys.exit(main(sys.argv[1:]))
224
```
--- 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
@@ -70,9 +70,16 @@
             if os.name == 'nt':
                 colorful = False
 
-    root = get_root_dir()
-    if root:
-        os.chdir(root)
+    # Those commands do not require a `conf.py`.  (Issue #1132)
+    # Moreover, actually having one somewhere in the tree can be bad, putting
+    # the output of that command (the new site) in an unknown directory that is
+    # not the current working directory.  (does not apply to `version`)
+    argname = args[0] if len(args) > 0 else None
+    if argname not in ['init', 'import_wordpress', 'import_feed',
+                       'import_blogger', 'version']:
+        root = get_root_dir()
+        if root:
+            os.chdir(root)
 
     sys.path.append('')
     try:

{"golden_diff": "diff --git a/nikola/__main__.py b/nikola/__main__.py\n--- a/nikola/__main__.py\n+++ b/nikola/__main__.py\n@@ -70,9 +70,16 @@\n             if os.name == 'nt':\n                 colorful = False\n \n-    root = get_root_dir()\n-    if root:\n-        os.chdir(root)\n+    # Those commands do not require a `conf.py`.  (Issue #1132)\n+    # Moreover, actually having one somewhere in the tree can be bad, putting\n+    # the output of that command (the new site) in an unknown directory that is\n+    # not the current working directory.  (does not apply to `version`)\n+    argname = args[0] if len(args) > 0 else None\n+    if argname not in ['init', 'import_wordpress', 'import_feed',\n+                       'import_blogger', 'version']:\n+        root = get_root_dir()\n+        if root:\n+            os.chdir(root)\n \n     sys.path.append('')\n     try:\n", "issue": "utils.get_root_dir() should not be run for import_* and init\nHere\u2019s a fun thing you can try at home:\n\n``` console\n$ cd /tmp\n$ nikola init site_1\n[2014-03-14T15:39:05Z] INFO: init: Created empty site at site_1.\n$ cd site_1\n$ mkdir subdir\n$ cd subdir\n$ nikola init site_2\n[2014-03-14T15:39:41Z] INFO: init: Created empty site at site_2.\n$ ls -l .\ntotal 0\n$ ls -l ..\ntotal 32\n-rw-r--r-- 1 kwpolska kwpolska 27413 Mar 14 16:39 conf.py\n-rw-r--r-- 1 kwpolska kwpolska  1923 Mar 14 16:39 conf.pyc\ndrwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 files/\ndrwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 galleries/\ndrwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 listings/\ndrwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 posts/\ndrwxr-xr-x 7 kwpolska kwpolska   160 Mar 14 16:39 site_2/    \u2190 wat\ndrwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 stories/\ndrwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 subdir/\n$\n```\n\nThe same behavior applies to `import_*`:\n\n``` console\n$ pwd\n/tmp/site_1/subdir\n$ nikola import_wordpress ~/git/nikola/tests/wordpress_unicode_export.xml\n[2014-03-14T15:41:24Z] INFO: init: Created empty site at new_site.\n[2014-03-14T15:41:24Z] INFO: Nikola: Configuration will be written to: new_site/conf.py\n$ ls -l .\ntotal 0\n$ ls -l ..\ntotal 32\n-rw-r--r-- 1 kwpolska kwpolska 27413 Mar 14 16:39 conf.py\n-rw-r--r-- 1 kwpolska kwpolska  1923 Mar 14 16:39 conf.pyc\ndrwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 files/\ndrwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 galleries/\ndrwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 listings/\ndrwxr-xr-x 7 kwpolska kwpolska   180 Mar 14 16:41 new_site/  \u2190 wat\ndrwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 posts/\ndrwxr-xr-x 7 kwpolska kwpolska   160 Mar 14 16:39 site_2/    \u2190 wat\ndrwxr-xr-x 2 kwpolska kwpolska    40 Mar 14 16:39 stories/\ndrwxr-xr-x 3 kwpolska kwpolska    40 Mar 14 16:39 subdir/\n$ mkdir nesting_is_fun\n$ cd nesting_is_fun\n$ nikola import_wordpress ~/git/nikola/tests/wordpress_unicode_export.xml\n[2014-03-14T15:42:05Z] NOTICE: Nikola: The folder new_site already exists - assuming that this is a already existing Nikola site.\n[2014-03-14T15:42:05Z] INFO: Nikola: Configuration will be written to: new_site/conf.py.import_wordpress-20140314_164205\n$\n```\n\nThis can be dangerous \u2014 especially because one can put a file named `conf.py` anywhere higher in the directory structure and destroy his Nikola attempts.\n\nHow could we fix it?  We could just not run `utils.get_root_dir()` if the user wants to execute one of those commands (it\u2019s executed in `__main__.py`).\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    colorful = False\n    if sys.stderr.isatty():\n        colorful = True\n        try:\n            import colorama\n            colorama.init()\n        except ImportError:\n            if os.name == 'nt':\n                colorful = False\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    config.update({'__colorful__': colorful})\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\nif __name__ == \"__main__\":\n    sys.exit(main(sys.argv[1:]))\n", "path": "nikola/__main__.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    colorful = False\n    if sys.stderr.isatty():\n        colorful = True\n        try:\n            import colorama\n            colorama.init()\n        except ImportError:\n            if os.name == 'nt':\n                colorful = False\n\n    # Those commands do not require a `conf.py`.  (Issue #1132)\n    # Moreover, actually having one somewhere in the tree can be bad, putting\n    # the output of that command (the new site) in an unknown directory that is\n    # not the current working directory.  (does not apply to `version`)\n    argname = args[0] if len(args) > 0 else None\n    if argname not in ['init', 'import_wordpress', 'import_feed',\n                       'import_blogger', 'version']:\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    config.update({'__colorful__': colorful})\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\nif __name__ == \"__main__\":\n    sys.exit(main(sys.argv[1:]))\n", "path": "nikola/__main__.py"}]}