|
| 1 | +# FIXME: Rewrite this into something less horrible in the future |
| 2 | +# Right now we just want this to work |
| 3 | +import os |
| 4 | +from importlib import import_module |
| 5 | + |
| 6 | +HELP = "Create a project" |
| 7 | + |
| 8 | + |
| 9 | +def print_usage(): |
| 10 | + print("Usage:") |
| 11 | + print(" crateproject <name>") |
| 12 | + |
| 13 | + |
| 14 | +def run(args): |
| 15 | + if not args: |
| 16 | + print_usage() |
| 17 | + return |
| 18 | + |
| 19 | + name = args[0] |
| 20 | + print(f"Creating project '{name}'") |
| 21 | + |
| 22 | + # Check for python module collision |
| 23 | + try: |
| 24 | + import_module(name) |
| 25 | + except ImportError: |
| 26 | + pass |
| 27 | + else: |
| 28 | + raise ValueError(f"{name} conflicts with an existing python module") |
| 29 | + |
| 30 | + # Is the name a valid identifier? |
| 31 | + validate_name(name) |
| 32 | + |
| 33 | + # Make sure we don't mess with existing directories |
| 34 | + if os.path.exists(name): |
| 35 | + print(f"Directory {name} already exist. Aborting.") |
| 36 | + return |
| 37 | + |
| 38 | + # Create the project directory |
| 39 | + os.makedirs(name) |
| 40 | + |
| 41 | + # Use the default settings file |
| 42 | + os.environ['DEMOSYS_SETTINGS_MODULE'] = 'demosys.conf.default_settings' |
| 43 | + from demosys.conf import settings |
| 44 | + from demosys.conf import settingsfile |
| 45 | + |
| 46 | + with open(os.path.join(name, 'settings.py'), 'w') as fd: |
| 47 | + fd.write(settingsfile.create(settings)) |
| 48 | + |
| 49 | + manage_file = 'manage.py' |
| 50 | + with open(manage_file, 'w') as fd: |
| 51 | + fd.write(gen_manage_py(name)) |
| 52 | + |
| 53 | + os.chmod(manage_file, 0o777) |
| 54 | + |
| 55 | + |
| 56 | +def validate_name(name): |
| 57 | + if not name: |
| 58 | + raise ValueError("Name cannot be empty") |
| 59 | + |
| 60 | + # Can the name be used as an identifier in python (module or package name) |
| 61 | + if not name.isidentifier(): |
| 62 | + raise ValueError(f"{name} is not a valid identifier") |
| 63 | + |
| 64 | + |
| 65 | +def gen_manage_py(project_name): |
| 66 | + lines = [ |
| 67 | + '#!/usr/bin/env python3', |
| 68 | + 'import os', |
| 69 | + 'import sys', |
| 70 | + '', |
| 71 | + 'if __name__ == "__main__":', |
| 72 | + ' os.environ.setdefault("DEMOSYS_SETTINGS_MODULE", "{}.settings")'.format(project_name), |
| 73 | + '', |
| 74 | + ' from demosys.core.management import execute_from_command_line', |
| 75 | + '', |
| 76 | + ' execute_from_command_line(sys.argv)' |
| 77 | + ] |
| 78 | + return "\n".join(lines) |
0 commit comments