We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
`scrapy genspider` should not overwrite existing file

## Summary

If the file mentioned in `scrapy genspider` already exists, then genspider should refuse to generate the the file.

## Motivation

As it stands, existing code can be blown away if this command runs twice.

## Describe alternatives you've considered

Prompting the user for overwriting existing spider.



--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `scrapy/commands/genspider.py`
Content:
```
1 import os
2 import shutil
3 import string
4 
5 from importlib import import_module
6 from os.path import join, dirname, abspath, exists, splitext
7 
8 import scrapy
9 from scrapy.commands import ScrapyCommand
10 from scrapy.utils.template import render_templatefile, string_camelcase
11 from scrapy.exceptions import UsageError
12 
13 
14 def sanitize_module_name(module_name):
15     """Sanitize the given module name, by replacing dashes and points
16     with underscores and prefixing it with a letter if it doesn't start
17     with one
18     """
19     module_name = module_name.replace('-', '_').replace('.', '_')
20     if module_name[0] not in string.ascii_letters:
21         module_name = "a" + module_name
22     return module_name
23 
24 
25 class Command(ScrapyCommand):
26 
27     requires_project = False
28     default_settings = {'LOG_ENABLED': False}
29 
30     def syntax(self):
31         return "[options] <name> <domain>"
32 
33     def short_desc(self):
34         return "Generate new spider using pre-defined templates"
35 
36     def add_options(self, parser):
37         ScrapyCommand.add_options(self, parser)
38         parser.add_option("-l", "--list", dest="list", action="store_true",
39                           help="List available templates")
40         parser.add_option("-e", "--edit", dest="edit", action="store_true",
41                           help="Edit spider after creating it")
42         parser.add_option("-d", "--dump", dest="dump", metavar="TEMPLATE",
43                           help="Dump template to standard output")
44         parser.add_option("-t", "--template", dest="template", default="basic",
45                           help="Uses a custom template.")
46         parser.add_option("--force", dest="force", action="store_true",
47                           help="If the spider already exists, overwrite it with the template")
48 
49     def run(self, args, opts):
50         if opts.list:
51             self._list_templates()
52             return
53         if opts.dump:
54             template_file = self._find_template(opts.dump)
55             if template_file:
56                 with open(template_file, "r") as f:
57                     print(f.read())
58             return
59         if len(args) != 2:
60             raise UsageError()
61 
62         name, domain = args[0:2]
63         module = sanitize_module_name(name)
64 
65         if self.settings.get('BOT_NAME') == module:
66             print("Cannot create a spider with the same name as your project")
67             return
68 
69         try:
70             spidercls = self.crawler_process.spider_loader.load(name)
71         except KeyError:
72             pass
73         else:
74             # if spider already exists and not --force then halt
75             if not opts.force:
76                 print("Spider %r already exists in module:" % name)
77                 print("  %s" % spidercls.__module__)
78                 return
79         template_file = self._find_template(opts.template)
80         if template_file:
81             self._genspider(module, name, domain, opts.template, template_file)
82             if opts.edit:
83                 self.exitcode = os.system('scrapy edit "%s"' % name)
84 
85     def _genspider(self, module, name, domain, template_name, template_file):
86         """Generate the spider module, based on the given template"""
87         tvars = {
88             'project_name': self.settings.get('BOT_NAME'),
89             'ProjectName': string_camelcase(self.settings.get('BOT_NAME')),
90             'module': module,
91             'name': name,
92             'domain': domain,
93             'classname': '%sSpider' % ''.join(s.capitalize() for s in module.split('_'))
94         }
95         if self.settings.get('NEWSPIDER_MODULE'):
96             spiders_module = import_module(self.settings['NEWSPIDER_MODULE'])
97             spiders_dir = abspath(dirname(spiders_module.__file__))
98         else:
99             spiders_module = None
100             spiders_dir = "."
101         spider_file = "%s.py" % join(spiders_dir, module)
102         shutil.copyfile(template_file, spider_file)
103         render_templatefile(spider_file, **tvars)
104         print("Created spider %r using template %r "
105               % (name, template_name), end=('' if spiders_module else '\n'))
106         if spiders_module:
107             print("in module:\n  %s.%s" % (spiders_module.__name__, module))
108 
109     def _find_template(self, template):
110         template_file = join(self.templates_dir, '%s.tmpl' % template)
111         if exists(template_file):
112             return template_file
113         print("Unable to find template: %s\n" % template)
114         print('Use "scrapy genspider --list" to see all available templates.')
115 
116     def _list_templates(self):
117         print("Available templates:")
118         for filename in sorted(os.listdir(self.templates_dir)):
119             if filename.endswith('.tmpl'):
120                 print("  %s" % splitext(filename)[0])
121 
122     @property
123     def templates_dir(self):
124         return join(
125             self.settings['TEMPLATES_DIR'] or join(scrapy.__path__[0], 'templates'),
126             'spiders'
127         )
128
```
--- 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/scrapy/commands/genspider.py b/scrapy/commands/genspider.py
--- a/scrapy/commands/genspider.py
+++ b/scrapy/commands/genspider.py
@@ -66,16 +66,9 @@
             print("Cannot create a spider with the same name as your project")
             return
 
-        try:
-            spidercls = self.crawler_process.spider_loader.load(name)
-        except KeyError:
-            pass
-        else:
-            # if spider already exists and not --force then halt
-            if not opts.force:
-                print("Spider %r already exists in module:" % name)
-                print("  %s" % spidercls.__module__)
-                return
+        if not opts.force and self._spider_exists(name):
+            return
+
         template_file = self._find_template(opts.template)
         if template_file:
             self._genspider(module, name, domain, opts.template, template_file)
@@ -119,6 +112,34 @@
             if filename.endswith('.tmpl'):
                 print("  %s" % splitext(filename)[0])
 
+    def _spider_exists(self, name):
+        if not self.settings.get('NEWSPIDER_MODULE'):
+            # if run as a standalone command and file with same filename already exists
+            if exists(name + ".py"):
+                print("%s already exists" % (abspath(name + ".py")))
+                return True
+            return False
+
+        try:
+            spidercls = self.crawler_process.spider_loader.load(name)
+        except KeyError:
+            pass
+        else:
+            # if spider with same name exists
+            print("Spider %r already exists in module:" % name)
+            print("  %s" % spidercls.__module__)
+            return True
+
+        # a file with the same name exists in the target directory
+        spiders_module = import_module(self.settings['NEWSPIDER_MODULE'])
+        spiders_dir = dirname(spiders_module.__file__)
+        spiders_dir_abs = abspath(spiders_dir)
+        if exists(join(spiders_dir_abs, name + ".py")):
+            print("%s already exists" % (join(spiders_dir_abs, (name + ".py"))))
+            return True
+
+        return False
+
     @property
     def templates_dir(self):
         return join(

{"golden_diff": "diff --git a/scrapy/commands/genspider.py b/scrapy/commands/genspider.py\n--- a/scrapy/commands/genspider.py\n+++ b/scrapy/commands/genspider.py\n@@ -66,16 +66,9 @@\n             print(\"Cannot create a spider with the same name as your project\")\n             return\n \n-        try:\n-            spidercls = self.crawler_process.spider_loader.load(name)\n-        except KeyError:\n-            pass\n-        else:\n-            # if spider already exists and not --force then halt\n-            if not opts.force:\n-                print(\"Spider %r already exists in module:\" % name)\n-                print(\"  %s\" % spidercls.__module__)\n-                return\n+        if not opts.force and self._spider_exists(name):\n+            return\n+\n         template_file = self._find_template(opts.template)\n         if template_file:\n             self._genspider(module, name, domain, opts.template, template_file)\n@@ -119,6 +112,34 @@\n             if filename.endswith('.tmpl'):\n                 print(\"  %s\" % splitext(filename)[0])\n \n+    def _spider_exists(self, name):\n+        if not self.settings.get('NEWSPIDER_MODULE'):\n+            # if run as a standalone command and file with same filename already exists\n+            if exists(name + \".py\"):\n+                print(\"%s already exists\" % (abspath(name + \".py\")))\n+                return True\n+            return False\n+\n+        try:\n+            spidercls = self.crawler_process.spider_loader.load(name)\n+        except KeyError:\n+            pass\n+        else:\n+            # if spider with same name exists\n+            print(\"Spider %r already exists in module:\" % name)\n+            print(\"  %s\" % spidercls.__module__)\n+            return True\n+\n+        # a file with the same name exists in the target directory\n+        spiders_module = import_module(self.settings['NEWSPIDER_MODULE'])\n+        spiders_dir = dirname(spiders_module.__file__)\n+        spiders_dir_abs = abspath(spiders_dir)\n+        if exists(join(spiders_dir_abs, name + \".py\")):\n+            print(\"%s already exists\" % (join(spiders_dir_abs, (name + \".py\"))))\n+            return True\n+\n+        return False\n+\n     @property\n     def templates_dir(self):\n         return join(\n", "issue": "`scrapy genspider` should not overwrite existing file\n\r\n## Summary\r\n\r\nIf the file mentioned in `scrapy genspider` already exists, then genspider should refuse to generate the the file.\r\n\r\n## Motivation\r\n\r\nAs it stands, existing code can be blown away if this command runs twice.\r\n\r\n## Describe alternatives you've considered\r\n\r\nPrompting the user for overwriting existing spider.\r\n\r\n\n", "before_files": [{"content": "import os\nimport shutil\nimport string\n\nfrom importlib import import_module\nfrom os.path import join, dirname, abspath, exists, splitext\n\nimport scrapy\nfrom scrapy.commands import ScrapyCommand\nfrom scrapy.utils.template import render_templatefile, string_camelcase\nfrom scrapy.exceptions import UsageError\n\n\ndef sanitize_module_name(module_name):\n    \"\"\"Sanitize the given module name, by replacing dashes and points\n    with underscores and prefixing it with a letter if it doesn't start\n    with one\n    \"\"\"\n    module_name = module_name.replace('-', '_').replace('.', '_')\n    if module_name[0] not in string.ascii_letters:\n        module_name = \"a\" + module_name\n    return module_name\n\n\nclass Command(ScrapyCommand):\n\n    requires_project = False\n    default_settings = {'LOG_ENABLED': False}\n\n    def syntax(self):\n        return \"[options] <name> <domain>\"\n\n    def short_desc(self):\n        return \"Generate new spider using pre-defined templates\"\n\n    def add_options(self, parser):\n        ScrapyCommand.add_options(self, parser)\n        parser.add_option(\"-l\", \"--list\", dest=\"list\", action=\"store_true\",\n                          help=\"List available templates\")\n        parser.add_option(\"-e\", \"--edit\", dest=\"edit\", action=\"store_true\",\n                          help=\"Edit spider after creating it\")\n        parser.add_option(\"-d\", \"--dump\", dest=\"dump\", metavar=\"TEMPLATE\",\n                          help=\"Dump template to standard output\")\n        parser.add_option(\"-t\", \"--template\", dest=\"template\", default=\"basic\",\n                          help=\"Uses a custom template.\")\n        parser.add_option(\"--force\", dest=\"force\", action=\"store_true\",\n                          help=\"If the spider already exists, overwrite it with the template\")\n\n    def run(self, args, opts):\n        if opts.list:\n            self._list_templates()\n            return\n        if opts.dump:\n            template_file = self._find_template(opts.dump)\n            if template_file:\n                with open(template_file, \"r\") as f:\n                    print(f.read())\n            return\n        if len(args) != 2:\n            raise UsageError()\n\n        name, domain = args[0:2]\n        module = sanitize_module_name(name)\n\n        if self.settings.get('BOT_NAME') == module:\n            print(\"Cannot create a spider with the same name as your project\")\n            return\n\n        try:\n            spidercls = self.crawler_process.spider_loader.load(name)\n        except KeyError:\n            pass\n        else:\n            # if spider already exists and not --force then halt\n            if not opts.force:\n                print(\"Spider %r already exists in module:\" % name)\n                print(\"  %s\" % spidercls.__module__)\n                return\n        template_file = self._find_template(opts.template)\n        if template_file:\n            self._genspider(module, name, domain, opts.template, template_file)\n            if opts.edit:\n                self.exitcode = os.system('scrapy edit \"%s\"' % name)\n\n    def _genspider(self, module, name, domain, template_name, template_file):\n        \"\"\"Generate the spider module, based on the given template\"\"\"\n        tvars = {\n            'project_name': self.settings.get('BOT_NAME'),\n            'ProjectName': string_camelcase(self.settings.get('BOT_NAME')),\n            'module': module,\n            'name': name,\n            'domain': domain,\n            'classname': '%sSpider' % ''.join(s.capitalize() for s in module.split('_'))\n        }\n        if self.settings.get('NEWSPIDER_MODULE'):\n            spiders_module = import_module(self.settings['NEWSPIDER_MODULE'])\n            spiders_dir = abspath(dirname(spiders_module.__file__))\n        else:\n            spiders_module = None\n            spiders_dir = \".\"\n        spider_file = \"%s.py\" % join(spiders_dir, module)\n        shutil.copyfile(template_file, spider_file)\n        render_templatefile(spider_file, **tvars)\n        print(\"Created spider %r using template %r \"\n              % (name, template_name), end=('' if spiders_module else '\\n'))\n        if spiders_module:\n            print(\"in module:\\n  %s.%s\" % (spiders_module.__name__, module))\n\n    def _find_template(self, template):\n        template_file = join(self.templates_dir, '%s.tmpl' % template)\n        if exists(template_file):\n            return template_file\n        print(\"Unable to find template: %s\\n\" % template)\n        print('Use \"scrapy genspider --list\" to see all available templates.')\n\n    def _list_templates(self):\n        print(\"Available templates:\")\n        for filename in sorted(os.listdir(self.templates_dir)):\n            if filename.endswith('.tmpl'):\n                print(\"  %s\" % splitext(filename)[0])\n\n    @property\n    def templates_dir(self):\n        return join(\n            self.settings['TEMPLATES_DIR'] or join(scrapy.__path__[0], 'templates'),\n            'spiders'\n        )\n", "path": "scrapy/commands/genspider.py"}], "after_files": [{"content": "import os\nimport shutil\nimport string\n\nfrom importlib import import_module\nfrom os.path import join, dirname, abspath, exists, splitext\n\nimport scrapy\nfrom scrapy.commands import ScrapyCommand\nfrom scrapy.utils.template import render_templatefile, string_camelcase\nfrom scrapy.exceptions import UsageError\n\n\ndef sanitize_module_name(module_name):\n    \"\"\"Sanitize the given module name, by replacing dashes and points\n    with underscores and prefixing it with a letter if it doesn't start\n    with one\n    \"\"\"\n    module_name = module_name.replace('-', '_').replace('.', '_')\n    if module_name[0] not in string.ascii_letters:\n        module_name = \"a\" + module_name\n    return module_name\n\n\nclass Command(ScrapyCommand):\n\n    requires_project = False\n    default_settings = {'LOG_ENABLED': False}\n\n    def syntax(self):\n        return \"[options] <name> <domain>\"\n\n    def short_desc(self):\n        return \"Generate new spider using pre-defined templates\"\n\n    def add_options(self, parser):\n        ScrapyCommand.add_options(self, parser)\n        parser.add_option(\"-l\", \"--list\", dest=\"list\", action=\"store_true\",\n                          help=\"List available templates\")\n        parser.add_option(\"-e\", \"--edit\", dest=\"edit\", action=\"store_true\",\n                          help=\"Edit spider after creating it\")\n        parser.add_option(\"-d\", \"--dump\", dest=\"dump\", metavar=\"TEMPLATE\",\n                          help=\"Dump template to standard output\")\n        parser.add_option(\"-t\", \"--template\", dest=\"template\", default=\"basic\",\n                          help=\"Uses a custom template.\")\n        parser.add_option(\"--force\", dest=\"force\", action=\"store_true\",\n                          help=\"If the spider already exists, overwrite it with the template\")\n\n    def run(self, args, opts):\n        if opts.list:\n            self._list_templates()\n            return\n        if opts.dump:\n            template_file = self._find_template(opts.dump)\n            if template_file:\n                with open(template_file, \"r\") as f:\n                    print(f.read())\n            return\n        if len(args) != 2:\n            raise UsageError()\n\n        name, domain = args[0:2]\n        module = sanitize_module_name(name)\n\n        if self.settings.get('BOT_NAME') == module:\n            print(\"Cannot create a spider with the same name as your project\")\n            return\n\n        if not opts.force and self._spider_exists(name):\n            return\n\n        template_file = self._find_template(opts.template)\n        if template_file:\n            self._genspider(module, name, domain, opts.template, template_file)\n            if opts.edit:\n                self.exitcode = os.system('scrapy edit \"%s\"' % name)\n\n    def _genspider(self, module, name, domain, template_name, template_file):\n        \"\"\"Generate the spider module, based on the given template\"\"\"\n        tvars = {\n            'project_name': self.settings.get('BOT_NAME'),\n            'ProjectName': string_camelcase(self.settings.get('BOT_NAME')),\n            'module': module,\n            'name': name,\n            'domain': domain,\n            'classname': '%sSpider' % ''.join(s.capitalize() for s in module.split('_'))\n        }\n        if self.settings.get('NEWSPIDER_MODULE'):\n            spiders_module = import_module(self.settings['NEWSPIDER_MODULE'])\n            spiders_dir = abspath(dirname(spiders_module.__file__))\n        else:\n            spiders_module = None\n            spiders_dir = \".\"\n        spider_file = \"%s.py\" % join(spiders_dir, module)\n        shutil.copyfile(template_file, spider_file)\n        render_templatefile(spider_file, **tvars)\n        print(\"Created spider %r using template %r \"\n              % (name, template_name), end=('' if spiders_module else '\\n'))\n        if spiders_module:\n            print(\"in module:\\n  %s.%s\" % (spiders_module.__name__, module))\n\n    def _find_template(self, template):\n        template_file = join(self.templates_dir, '%s.tmpl' % template)\n        if exists(template_file):\n            return template_file\n        print(\"Unable to find template: %s\\n\" % template)\n        print('Use \"scrapy genspider --list\" to see all available templates.')\n\n    def _list_templates(self):\n        print(\"Available templates:\")\n        for filename in sorted(os.listdir(self.templates_dir)):\n            if filename.endswith('.tmpl'):\n                print(\"  %s\" % splitext(filename)[0])\n\n    def _spider_exists(self, name):\n        if not self.settings.get('NEWSPIDER_MODULE'):\n            # if run as a standalone command and file with same filename already exists\n            if exists(name + \".py\"):\n                print(\"%s already exists\" % (abspath(name + \".py\")))\n                return True\n            return False\n\n        try:\n            spidercls = self.crawler_process.spider_loader.load(name)\n        except KeyError:\n            pass\n        else:\n            # if spider with same name exists\n            print(\"Spider %r already exists in module:\" % name)\n            print(\"  %s\" % spidercls.__module__)\n            return True\n\n        # a file with the same name exists in the target directory\n        spiders_module = import_module(self.settings['NEWSPIDER_MODULE'])\n        spiders_dir = dirname(spiders_module.__file__)\n        spiders_dir_abs = abspath(spiders_dir)\n        if exists(join(spiders_dir_abs, name + \".py\")):\n            print(\"%s already exists\" % (join(spiders_dir_abs, (name + \".py\"))))\n            return True\n\n        return False\n\n    @property\n    def templates_dir(self):\n        return join(\n            self.settings['TEMPLATES_DIR'] or join(scrapy.__path__[0], 'templates'),\n            'spiders'\n        )\n", "path": "scrapy/commands/genspider.py"}]}