def register_postscript(self, script_path: str, target_func: str, runtime="python") -> int: mys.log("Sorry, Mirage Prescript is now under construction. ; (", withError=True) return 0
def __insert_app_path(self, app_name, setting_file): lines = [] insert_line = 0 try: with open(setting_file, "r") as setting: try: lines = setting.readlines() except: mys.log("Failed to load configuration file lines.", withError=True) except: pass for i in range(len(lines)): if "INSTALLED_APPS = [" in lines[i]: insert_line = i elif "INSTALLED_APPS = (" in lines[i]: insert_line = i with open(setting_file, "w") as setting: app_config = app_name[0].upper() + app_name[1:] + "Config" lines.insert(insert_line + 1, " \'" + app_name + ".apps." + app_config + "\',\n") setting.writelines(lines)
def initialize(): with MirageEnvironment(MirageEnvironmentLevel.inproject): if not fileable.exists(".mirage"): mys.log("Creating Mirage workspace...") fileable.mkdir(".mirage") fileable.mkdir(".mirage/cache/") fileable.mkdir(".mirage/persistence/")
def _check_before(self): try: import django except ImportError: mys.log("Failed to import Django!", withError = True, errorDetail = "You have to install Django before creating a new Django project.") raise ImportError
def main(self): with proj.MirageEnvironment(proj.MirageEnvironmentLevel.indjango): try: os.system("python manage.py runserver") except KeyboardInterrupt: mys.log("Good bye!") except: mys.log("Failed to launch web browser!", withError=True)
def _get_copyright(self, detail): if detail == Detail.copyright_start_year: return self._data["project"]["copyright"]["start_year"] elif detail == Detail.copyright_copyrigtors: return self._data["project"]["copyright"]["copyrightors"] else: mys.log("The config information named " + detail + " does not exist!", withError = True) raise MiragefileUnknownError
def main(self): mys.log("Merging all migrations...") if mys.log( "Are you sure to merge all migrations? This operation will delete all migration files!" ,withConfirm = True): self._merge() else: mys.log("Canceled")
def run(self) -> Void: for flow in self._flows: try: flow() except: mys.log("Something error has occured!", withError=True, errorDetail=mys.raise_error_message(flow)) raise Exception
def _get_private_profile(self, detail): if detail == Detail.private_name: return self._data["private_profile"]["name"] elif detail == Detail.private_license_url: return self._data["private_license"]["url"] else: mys.log("The config information named " + detail + " does not exist!", withError = True) raise MiragefileUnknownError
def _load_json(self, filename): if not os.path.exists(filename): mys.log("Failed to find Miragefile!", withError = True) raise FileNotFoundError with open(filename, "r") as jsonfile: try: return json.load(jsonfile) except: mys.log("Failed to load Miragefile!", withError = True, errorDetail = mys.raise_error_message(self._load_json)) raise FileNotFoundError
def __init__(self, file_type = None): with proj.MirageEnvironment(proj.MirageEnvironmentLevel.inproject): if file_type == "secret": self._data = self._load_json("Miragefile.secret") elif file_type == "addon": self._data = self._load_json("Miragefile.addon") elif file_type == None: self._data = self._load_json("Miragefile") else: mys.log("Wrong configuration type {0}.".format(file_type), withError = True)
def query_execute(connection, cur, query): try: cur.execute(query) except sqlite3.Error as e: mys.log("SQLite3 error has occured!", withError=True, errorDetail=e.args[0]) except: mys.log("Unknown error has occured!", withError=True, errorDetail=mys.raise_error_message( MirageWorkspace.__write_persistence_file_meta))
def _get_django(self, detail): if detail == Detail.django_path: return self._data["project"]["django"]["path"] elif detail == Detail.django_module: return self._data["project"]["django"]["module"] elif detail == Detail.django_package_manager: return self._data["project"]["django"]["package"] elif detail == Detail.django_db_backend: return self._data["project"]["django"]["database"] else: mys.log("The config information named " + str(detail) + " does not exist!", withError = True) raise MiragefileUnknownError
def get(self, category, detail): try: if category == Category.project_basic: return self._get_project(detail) if category == Category.django: return self._get_django(detail) if category == Category.copyright: return self._get_copyright(detail) if category == Category.private_profile: return self._get_private_profile(detail) except: mys.log("Failed to get value from Miragefile!", withError = True)
def main(self) -> bool: if Path("self._module_name").is_dir(): mys.log("Module {0} is already exists!".format(self._module_name), withError = True) else: mys.log("Generating \"{0}\" module...".format(self._module_name)) Path(self._module_name).mkdir() with InDir(self._module_name): open("__init__.py", "a") return True
def main(self) -> Void: mys.log("Checking system information...") if self.get_os() == "Darwin": print("OS: macOS") elif self.get_os() == "Windows": print("OS: Windows") elif self.get_os() == "Linux": print("OS: Linux") print("Python: ", self.get_python_version()[0], ".", self.get_python_version()[1], ".", self.get_python_version()[2])
def main(self) -> bool: try: self._check_all() except: mys.log("Environmental compatability is invalid.", withError=True) return for app in self._must_creat_apps: mys.log("Creating a app " + app + ".") self._create_app(app) self._create_url(app) self._install_app(app) return True
def _merge(self): with proj.MirageEnvironment(proj.MirageEnvironmentLevel.inapp): mys.log("Integrate migrations...") with proj.InDir("migrations"): path_obj = Path(os.getcwd()) migration_script_path = path_obj.glob("*.py") for path in migration_script_path: if not "__init__.py" in str(path): mys.log("Removing " + str(path) + "!") os.remove(path) with proj.MirageEnvironment(proj.MirageEnvironmentLevel.indjango): os.system("python manage.py makemigrations")
def _check_all(self): reserved_names = ("test", "os") for app in self._must_creat_apps: for name in reserved_names: if app == name: mys.log("The app named " + app + " is reserved by Django!", withError=True) raise ValueError for app in self._must_creat_apps: if os.path.isdir(app): mys.log("The app named " + app + " is already exists.", withError=True) raise FileExistsError
def _get_project(self, detail): if detail == Detail.project_name: return self._data["project"]["name"] elif detail == Detail.project_version: return self._data["project"]["version"] elif detail == Detail.project_author: return self._data["project"]["author"] elif detail == Detail.project_git: return self._data["project"]["git"] elif detail == Detail.project_license: return self._data["project"]["license"] elif detail == Detail.project_description: return self._data["project"]["description"] else: mys.log("The config information named " + str(detail) + " does not exist!", withError = True) raise MiragefileUnknownError
def parse(self) -> Void: # If there are no command, show usage. if len(sys.argv) == 1: instance = getattr(workflows, "UsageShow")(self._arguments) instance.run() return # Check excute function is not empty. if not self._exec_flow == None: instance = getattr(workflows, self._exec_flow)(self._arguments) instance.run() return else: system.log("Unable to invoke action \"{0}\"!".format(sys.argv[1]), withError = True) instance = getattr(workflows, "UsageShow")(self._arguments) instance.run()
def main(self): # ModelClass name:string+maxlen=40 no:integer+as_primary=True model_contents = "" for data in self._data: model_contents += "{0}\n".format(self._parse_data(data)) # Write model file sys.log("Writing model...") try: with open("models.py", "a") as writing: writing.write( create_model_class(self._model_name, model_contents)) except: sys.log("Failed to create / overwrite models.py!", withError=True, errorDetail=sys.raise_error_message(self.main))
def _check(self, logger): with proj.InDir(self._to): if Path(self._app).is_dir(): if not mys.log( "%s ia already exists.\nAre you sure to replace new one?" % self._app, withConfirm=True): raise FileExistsError else: os.system("rm -rf " + self._app)
def main(self): # Beta Warning mys.log("This feature is now under Beta version.", withError=True) # Logger instance logger = mys.progress.Progress() with proj.MirageEnvironment(proj.MirageEnvironmentLevel.indjango): # In advance checking. try: self._check(logger) except: return logger.write("Searching application %s..." % self._app, withLazy=True) if Path(self._app).is_dir(): mys.log(os.getcwd()) shutil.copytree(self._app, os.path.join(self._to, self._app)) logger.update("Completed!") else: logger.update("Can not detect application %s!" % self._app) mys.log("Failed to transfer app %s!" % self._app, withError=True, errorDetail=mys.raise_error_message( "The application diresctory does not exists!")) return
def _install_app(self, name): try: master_app = self.__detect_master_app() except: mys.log("Failed to detect master app.", withError=True) mys.log("Installing app...") with proj.InDir(master_app): if os.path.isdir("environment"): with proj.InDir("./environment"): self.__insert_app_path(name, "base.py") elif os.path.isdir("settings"): with proj.InDir("./settings"): self.__insert_app_path(name, "base.py") else: if os.path.isfile("settings.py"): self.__insert_app_path(name, "settings.py") else: mys.log( "Failed to install Django app due to missing configuration file.", withError=True)
def _make_option(self, ops, data_type): if ops == None: if data_type == "string": return "max_length = 255" else: return "" opstring = "" # Max len check text_is_maxlen = False for op in ops: if "maxlen" in op[0]: text_is_maxlen = True if data_type == "string" and text_is_maxlen == False: opstring += "max_length = 255, " # Generate filed options for op in ops: if op[0] == "maxlen": opstring += "max_length = {0}".format(op[1]) elif op[0] == "primary": opstring += "primary_key = {0}".format(op[1]) elif op[0] == "default": opstring += "default = {0}".format(op[1]) elif op[0] == "blank": opstring += "blank = {0}".format(op[1]) elif op[0] == "null": opstring += "null = {0}".format(op[1]) elif op[0] == "db_column": opstring += "db_column = {0}".format(op[1]) else: sys.log("Failed to create filed option " + op + "!", withError=True) continue if not op[0] == ops[len(ops) - 1][0]: opstring += ", " return opstring
def main(self) -> Void: mys.log("Checking mirage update...") with tempfile.TemporaryDirectory() as td: with InDir(td): sys.path.append(td) request.urlretrieve(self._url, "mg_version_check.py") try: import mg_version_check except ImportError: mys.log("Failed to get version information!", withError=True, errorDetail=mys.raise_error_message(self.main, traceback.format_exc())) return if ver == mg_version_check.__version__: mys.log("Up-to-date !") else: mys.log("Update available!", withError=True) print("This version: {0}".format(ver)) print("Available version: {0}".format(mg_version_check.__version__))
def _load_script(self) -> object: with MirageEnvironment(WorkingLevel.inproject): sys.path.append(os.getcwd()) try: fp, name, desc = imp.find_module("mirage.config") config_script = imp.load_module("config_script", fp, name, desc) if config_script.MirageConfig.assertBool(): mys.log("Config script loaded!") else: mys.log("Failed to import mirage.config.py !", withError=True) raise ImportError except ImportError: mys.log("Failed to import mirage.config.py !", withError=True)
def deinitialize(self) -> Void: mys.log("Bye : )")
def initialize(self) -> Void: mys.log("Mirage Setting Script v0.0.1")