2011-12-23 06:38:02 +08:00
|
|
|
import cgi
|
2012-01-16 00:06:56 +08:00
|
|
|
import errno
|
2011-12-23 06:38:02 +08:00
|
|
|
import mimetypes
|
|
|
|
import os
|
|
|
|
import posixpath
|
|
|
|
import re
|
|
|
|
import shutil
|
|
|
|
import stat
|
|
|
|
import sys
|
|
|
|
import tempfile
|
|
|
|
from os import path
|
|
|
|
|
|
|
|
import django
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.core.management.base import BaseCommand, CommandError
|
|
|
|
from django.core.management.utils import handle_extensions
|
2015-02-23 02:14:05 +08:00
|
|
|
from django.template import Context, Engine
|
2011-12-23 06:38:02 +08:00
|
|
|
from django.utils import archive
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.utils.six.moves.urllib.request import urlretrieve
|
2014-12-25 20:30:37 +08:00
|
|
|
from django.utils.version import get_docs_version
|
2011-12-23 06:38:02 +08:00
|
|
|
|
|
|
|
_drive_re = re.compile('^([a-z]):', re.I)
|
|
|
|
_url_drive_re = re.compile('^([a-z])[:|]', re.I)
|
|
|
|
|
|
|
|
|
|
|
|
class TemplateCommand(BaseCommand):
|
|
|
|
"""
|
|
|
|
Copies either a Django application layout template or a Django project
|
|
|
|
layout template into the specified directory.
|
|
|
|
|
|
|
|
:param style: A color style object (see django.core.management.color).
|
|
|
|
:param app_or_project: The string 'app' or 'project'.
|
|
|
|
:param name: The name of the application or project.
|
|
|
|
:param directory: The directory to which the template should be copied.
|
|
|
|
:param options: The additional variables passed to project or app templates
|
|
|
|
"""
|
2014-01-20 10:45:21 +08:00
|
|
|
requires_system_checks = False
|
2011-12-23 06:38:02 +08:00
|
|
|
# Can't import settings during this command, because they haven't
|
|
|
|
# necessarily been created.
|
|
|
|
can_import_settings = False
|
|
|
|
# The supported URL schemes
|
|
|
|
url_schemes = ['http', 'https', 'ftp']
|
2013-02-04 07:53:48 +08:00
|
|
|
# Can't perform any active locale changes during this command, because
|
|
|
|
# setting might not be available at all.
|
|
|
|
leave_locale_alone = True
|
2011-12-23 06:38:02 +08:00
|
|
|
|
2014-06-07 04:39:33 +08:00
|
|
|
def add_arguments(self, parser):
|
|
|
|
parser.add_argument('name', help='Name of the application or project.')
|
|
|
|
parser.add_argument('directory', nargs='?', help='Optional destination directory')
|
|
|
|
parser.add_argument('--template',
|
|
|
|
help='The path or URL to load the template from.')
|
|
|
|
parser.add_argument('--extension', '-e', dest='extensions',
|
|
|
|
action='append', default=['py'],
|
|
|
|
help='The file extension(s) to render (default: "py"). '
|
|
|
|
'Separate multiple extensions with commas, or use '
|
|
|
|
'-e multiple times.')
|
|
|
|
parser.add_argument('--name', '-n', dest='files',
|
|
|
|
action='append', default=[],
|
|
|
|
help='The file name(s) to render. '
|
|
|
|
'Separate multiple extensions with commas, or use '
|
|
|
|
'-n multiple times.')
|
|
|
|
|
2011-12-23 06:38:02 +08:00
|
|
|
def handle(self, app_or_project, name, target=None, **options):
|
|
|
|
self.app_or_project = app_or_project
|
|
|
|
self.paths_to_remove = []
|
2014-06-07 04:39:33 +08:00
|
|
|
self.verbosity = options['verbosity']
|
2011-12-23 06:38:02 +08:00
|
|
|
|
2012-10-13 22:05:34 +08:00
|
|
|
self.validate_name(name, app_or_project)
|
2011-12-30 03:06:57 +08:00
|
|
|
|
2011-12-23 06:38:02 +08:00
|
|
|
# if some directory is given, make sure it's nicely expanded
|
|
|
|
if target is None:
|
2012-01-05 07:55:34 +08:00
|
|
|
top_dir = path.join(os.getcwd(), name)
|
|
|
|
try:
|
|
|
|
os.makedirs(top_dir)
|
2012-04-29 00:09:37 +08:00
|
|
|
except OSError as e:
|
2012-01-16 00:06:56 +08:00
|
|
|
if e.errno == errno.EEXIST:
|
|
|
|
message = "'%s' already exists" % top_dir
|
|
|
|
else:
|
|
|
|
message = e
|
|
|
|
raise CommandError(message)
|
2011-12-23 06:38:02 +08:00
|
|
|
else:
|
2012-03-22 06:29:32 +08:00
|
|
|
top_dir = os.path.abspath(path.expanduser(target))
|
|
|
|
if not os.path.exists(top_dir):
|
|
|
|
raise CommandError("Destination directory '%s' does not "
|
|
|
|
"exist, please create it first." % top_dir)
|
2011-12-23 06:38:02 +08:00
|
|
|
|
2014-11-17 16:24:56 +08:00
|
|
|
extensions = tuple(handle_extensions(options['extensions']))
|
2012-02-04 21:01:30 +08:00
|
|
|
extra_files = []
|
2014-06-07 04:39:33 +08:00
|
|
|
for file in options['files']:
|
2012-02-04 21:01:30 +08:00
|
|
|
extra_files.extend(map(lambda x: x.strip(), file.split(',')))
|
2011-12-23 06:38:02 +08:00
|
|
|
if self.verbosity >= 2:
|
|
|
|
self.stdout.write("Rendering %s template files with "
|
|
|
|
"extensions: %s\n" %
|
|
|
|
(app_or_project, ', '.join(extensions)))
|
2012-02-04 21:01:30 +08:00
|
|
|
self.stdout.write("Rendering %s template files with "
|
|
|
|
"filenames: %s\n" %
|
|
|
|
(app_or_project, ', '.join(extra_files)))
|
2011-12-23 06:38:02 +08:00
|
|
|
|
|
|
|
base_name = '%s_name' % app_or_project
|
|
|
|
base_subdir = '%s_template' % app_or_project
|
|
|
|
base_directory = '%s_directory' % app_or_project
|
|
|
|
|
|
|
|
context = Context(dict(options, **{
|
|
|
|
base_name: name,
|
|
|
|
base_directory: top_dir,
|
2014-12-25 20:30:37 +08:00
|
|
|
'docs_version': get_docs_version(),
|
2014-11-25 03:11:55 +08:00
|
|
|
'django_version': django.__version__,
|
2012-07-17 06:26:31 +08:00
|
|
|
}), autoescape=False)
|
2011-12-23 06:38:02 +08:00
|
|
|
|
|
|
|
# Setup a stub settings environment for template rendering
|
|
|
|
from django.conf import settings
|
|
|
|
if not settings.configured:
|
|
|
|
settings.configure()
|
|
|
|
|
2014-06-07 04:39:33 +08:00
|
|
|
template_dir = self.handle_template(options['template'],
|
2011-12-23 06:38:02 +08:00
|
|
|
base_subdir)
|
|
|
|
prefix_length = len(template_dir) + 1
|
|
|
|
|
|
|
|
for root, dirs, files in os.walk(template_dir):
|
|
|
|
|
|
|
|
path_rest = root[prefix_length:]
|
|
|
|
relative_dir = path_rest.replace(base_name, name)
|
|
|
|
if relative_dir:
|
|
|
|
target_dir = path.join(top_dir, relative_dir)
|
|
|
|
if not path.exists(target_dir):
|
|
|
|
os.mkdir(target_dir)
|
|
|
|
|
|
|
|
for dirname in dirs[:]:
|
2012-10-07 05:40:58 +08:00
|
|
|
if dirname.startswith('.') or dirname == '__pycache__':
|
2011-12-23 06:38:02 +08:00
|
|
|
dirs.remove(dirname)
|
|
|
|
|
|
|
|
for filename in files:
|
|
|
|
if filename.endswith(('.pyo', '.pyc', '.py.class')):
|
|
|
|
# Ignore some files as they cause various breakages.
|
|
|
|
continue
|
|
|
|
old_path = path.join(root, filename)
|
|
|
|
new_path = path.join(top_dir, relative_dir,
|
|
|
|
filename.replace(base_name, name))
|
|
|
|
if path.exists(new_path):
|
|
|
|
raise CommandError("%s already exists, overlaying a "
|
|
|
|
"project or app into an existing "
|
|
|
|
"directory won't replace conflicting "
|
|
|
|
"files" % new_path)
|
|
|
|
|
|
|
|
# Only render the Python files, as we don't want to
|
|
|
|
# accidentally render Django templates files
|
2012-12-03 17:37:26 +08:00
|
|
|
with open(old_path, 'rb') as template_file:
|
2011-12-23 06:38:02 +08:00
|
|
|
content = template_file.read()
|
2012-02-04 21:01:30 +08:00
|
|
|
if filename.endswith(extensions) or filename in extra_files:
|
2012-12-03 17:37:26 +08:00
|
|
|
content = content.decode('utf-8')
|
2015-02-23 02:14:05 +08:00
|
|
|
template = Engine().from_string(content)
|
2011-12-23 06:38:02 +08:00
|
|
|
content = template.render(context)
|
2012-12-03 17:37:26 +08:00
|
|
|
content = content.encode('utf-8')
|
|
|
|
with open(new_path, 'wb') as new_file:
|
2011-12-23 06:38:02 +08:00
|
|
|
new_file.write(content)
|
|
|
|
|
|
|
|
if self.verbosity >= 2:
|
|
|
|
self.stdout.write("Creating %s\n" % new_path)
|
|
|
|
try:
|
|
|
|
shutil.copymode(old_path, new_path)
|
|
|
|
self.make_writeable(new_path)
|
|
|
|
except OSError:
|
2012-05-19 19:51:54 +08:00
|
|
|
self.stderr.write(
|
2011-12-23 06:38:02 +08:00
|
|
|
"Notice: Couldn't set permission bits on %s. You're "
|
|
|
|
"probably using an uncommon filesystem setup. No "
|
2012-05-19 19:51:54 +08:00
|
|
|
"problem." % new_path, self.style.NOTICE)
|
2011-12-23 06:38:02 +08:00
|
|
|
|
|
|
|
if self.paths_to_remove:
|
|
|
|
if self.verbosity >= 2:
|
|
|
|
self.stdout.write("Cleaning up temporary files.\n")
|
|
|
|
for path_to_remove in self.paths_to_remove:
|
2011-12-30 01:03:38 +08:00
|
|
|
if path.isfile(path_to_remove):
|
2011-12-23 06:38:02 +08:00
|
|
|
os.remove(path_to_remove)
|
|
|
|
else:
|
2015-02-23 00:49:29 +08:00
|
|
|
shutil.rmtree(path_to_remove)
|
2011-12-23 06:38:02 +08:00
|
|
|
|
|
|
|
def handle_template(self, template, subdir):
|
|
|
|
"""
|
|
|
|
Determines where the app or project templates are.
|
|
|
|
Use django.__path__[0] as the default because we don't
|
|
|
|
know into which directory Django has been installed.
|
|
|
|
"""
|
|
|
|
if template is None:
|
|
|
|
return path.join(django.__path__[0], 'conf', subdir)
|
|
|
|
else:
|
|
|
|
if template.startswith('file://'):
|
|
|
|
template = template[7:]
|
|
|
|
expanded_template = path.expanduser(template)
|
2011-12-30 01:03:38 +08:00
|
|
|
expanded_template = path.normpath(expanded_template)
|
|
|
|
if path.isdir(expanded_template):
|
2011-12-23 06:38:02 +08:00
|
|
|
return expanded_template
|
|
|
|
if self.is_url(template):
|
|
|
|
# downloads the file and returns the path
|
|
|
|
absolute_path = self.download(template)
|
|
|
|
else:
|
|
|
|
absolute_path = path.abspath(expanded_template)
|
2011-12-30 01:03:38 +08:00
|
|
|
if path.exists(absolute_path):
|
2011-12-23 06:38:02 +08:00
|
|
|
return self.extract(absolute_path)
|
|
|
|
|
|
|
|
raise CommandError("couldn't handle %s template %s." %
|
|
|
|
(self.app_or_project, template))
|
|
|
|
|
2012-10-13 22:05:34 +08:00
|
|
|
def validate_name(self, name, app_or_project):
|
|
|
|
if name is None:
|
|
|
|
raise CommandError("you must provide %s %s name" % (
|
|
|
|
"an" if app_or_project == "app" else "a", app_or_project))
|
|
|
|
# If it's not a valid directory name.
|
|
|
|
if not re.search(r'^[_a-zA-Z]\w*$', name):
|
|
|
|
# Provide a smart error message, depending on the error.
|
|
|
|
if not re.search(r'^[_a-zA-Z]', name):
|
|
|
|
message = 'make sure the name begins with a letter or underscore'
|
|
|
|
else:
|
|
|
|
message = 'use only numbers, letters and underscores'
|
|
|
|
raise CommandError("%r is not a valid %s name. Please %s." %
|
|
|
|
(name, app_or_project, message))
|
|
|
|
|
2011-12-23 06:38:02 +08:00
|
|
|
def download(self, url):
|
|
|
|
"""
|
|
|
|
Downloads the given URL and returns the file name.
|
|
|
|
"""
|
2012-01-02 01:45:40 +08:00
|
|
|
def cleanup_url(url):
|
|
|
|
tmp = url.rstrip('/')
|
|
|
|
filename = tmp.split('/')[-1]
|
|
|
|
if url.endswith('/'):
|
2013-10-22 21:31:43 +08:00
|
|
|
display_url = tmp + '/'
|
2012-01-02 01:45:40 +08:00
|
|
|
else:
|
|
|
|
display_url = url
|
|
|
|
return filename, display_url
|
|
|
|
|
2011-12-23 06:38:02 +08:00
|
|
|
prefix = 'django_%s_template_' % self.app_or_project
|
|
|
|
tempdir = tempfile.mkdtemp(prefix=prefix, suffix='_download')
|
|
|
|
self.paths_to_remove.append(tempdir)
|
2012-01-02 01:45:40 +08:00
|
|
|
filename, display_url = cleanup_url(url)
|
2011-12-23 06:38:02 +08:00
|
|
|
|
|
|
|
if self.verbosity >= 2:
|
2012-01-02 01:45:40 +08:00
|
|
|
self.stdout.write("Downloading %s\n" % display_url)
|
2011-12-23 06:38:02 +08:00
|
|
|
try:
|
2012-07-20 21:36:52 +08:00
|
|
|
the_path, info = urlretrieve(url, path.join(tempdir, filename))
|
2012-04-29 00:09:37 +08:00
|
|
|
except IOError as e:
|
2011-12-23 06:38:02 +08:00
|
|
|
raise CommandError("couldn't download URL %s to %s: %s" %
|
|
|
|
(url, filename, e))
|
|
|
|
|
2011-12-30 01:03:38 +08:00
|
|
|
used_name = the_path.split('/')[-1]
|
2011-12-23 06:38:02 +08:00
|
|
|
|
|
|
|
# Trying to get better name from response headers
|
|
|
|
content_disposition = info.get('content-disposition')
|
|
|
|
if content_disposition:
|
|
|
|
_, params = cgi.parse_header(content_disposition)
|
|
|
|
guessed_filename = params.get('filename') or used_name
|
|
|
|
else:
|
|
|
|
guessed_filename = used_name
|
|
|
|
|
|
|
|
# Falling back to content type guessing
|
|
|
|
ext = self.splitext(guessed_filename)[1]
|
|
|
|
content_type = info.get('content-type')
|
|
|
|
if not ext and content_type:
|
|
|
|
ext = mimetypes.guess_extension(content_type)
|
|
|
|
if ext:
|
|
|
|
guessed_filename += ext
|
|
|
|
|
|
|
|
# Move the temporary file to a filename that has better
|
2014-03-02 22:25:53 +08:00
|
|
|
# chances of being recognized by the archive utils
|
2011-12-23 06:38:02 +08:00
|
|
|
if used_name != guessed_filename:
|
2011-12-30 01:03:38 +08:00
|
|
|
guessed_path = path.join(tempdir, guessed_filename)
|
|
|
|
shutil.move(the_path, guessed_path)
|
2011-12-23 06:38:02 +08:00
|
|
|
return guessed_path
|
|
|
|
|
|
|
|
# Giving up
|
2011-12-30 01:03:38 +08:00
|
|
|
return the_path
|
2011-12-23 06:38:02 +08:00
|
|
|
|
2011-12-30 01:03:38 +08:00
|
|
|
def splitext(self, the_path):
|
2011-12-23 06:38:02 +08:00
|
|
|
"""
|
|
|
|
Like os.path.splitext, but takes off .tar, too
|
|
|
|
"""
|
2011-12-30 01:03:38 +08:00
|
|
|
base, ext = posixpath.splitext(the_path)
|
2011-12-23 06:38:02 +08:00
|
|
|
if base.lower().endswith('.tar'):
|
|
|
|
ext = base[-4:] + ext
|
|
|
|
base = base[:-4]
|
|
|
|
return base, ext
|
|
|
|
|
|
|
|
def extract(self, filename):
|
|
|
|
"""
|
|
|
|
Extracts the given file to a temporarily and returns
|
|
|
|
the path of the directory with the extracted content.
|
|
|
|
"""
|
|
|
|
prefix = 'django_%s_template_' % self.app_or_project
|
|
|
|
tempdir = tempfile.mkdtemp(prefix=prefix, suffix='_extract')
|
|
|
|
self.paths_to_remove.append(tempdir)
|
|
|
|
if self.verbosity >= 2:
|
|
|
|
self.stdout.write("Extracting %s\n" % filename)
|
|
|
|
try:
|
|
|
|
archive.extract(filename, tempdir)
|
|
|
|
return tempdir
|
2012-04-29 00:09:37 +08:00
|
|
|
except (archive.ArchiveException, IOError) as e:
|
2011-12-23 06:38:02 +08:00
|
|
|
raise CommandError("couldn't extract file %s to %s: %s" %
|
|
|
|
(filename, tempdir, e))
|
|
|
|
|
|
|
|
def is_url(self, template):
|
|
|
|
"""
|
|
|
|
Returns True if the name looks like a URL
|
|
|
|
"""
|
|
|
|
if ':' not in template:
|
|
|
|
return False
|
|
|
|
scheme = template.split(':', 1)[0].lower()
|
|
|
|
return scheme in self.url_schemes
|
|
|
|
|
|
|
|
def make_writeable(self, filename):
|
|
|
|
"""
|
|
|
|
Make sure that the file is writeable.
|
|
|
|
Useful if our source is read-only.
|
|
|
|
"""
|
|
|
|
if sys.platform.startswith('java'):
|
|
|
|
# On Jython there is no os.access()
|
|
|
|
return
|
|
|
|
if not os.access(filename, os.W_OK):
|
|
|
|
st = os.stat(filename)
|
|
|
|
new_permissions = stat.S_IMODE(st.st_mode) | stat.S_IWUSR
|
|
|
|
os.chmod(filename, new_permissions)
|