Ejemplo n.º 1
0
    def create(self, model, **kwargs):

        model = self.check_noun(model)
        model = sanitized_string(model)
        classname = inflection.camelize(model)

        filename = f"{model.lower()}.py"

        template = 'manager.tpl'
        template_import = 'manager-import.tpl'

        content = rendered_file_template(path=self.TEMPLATES_DIRECTORY,
                                         template=template,
                                         context={
                                             'classname': classname,
                                             'model': model
                                         })

        import_content = rendered_file_template(path=self.TEMPLATES_DIRECTORY,
                                                template=template_import,
                                                context={
                                                    'classname': classname,
                                                    'model': model
                                                })

        self.add_import(template=template_import, content=import_content)

        if self.create_file(path=self.cwd, filename=filename, content=content):

            resource = f"{classname}Manager"
            log_success(DEFAULT_CREATE_MESSAGE.format(filename, resource))
Ejemplo n.º 2
0
    def create(self, model, **kwargs):
        model = self.check_noun(model)
        model = sanitized_string(model)
        classname = inflection.camelize(model)

        if kwargs.get('fields') is not None:
            self.parse_fields(model, kwargs.get('fields'))

        template = 'fixture.tpl' \
            if not kwargs.get('template') \
            else kwargs.get('template')

        content = rendered_file_template(path=self.TEMPLATES_DIRECTORY,
                                         template=template,
                                         context={
                                             'total': int(kwargs.get('total')),
                                             'app': self.app_name,
                                             'classname': classname,
                                             'fields': self.fixture_fields,
                                         })

        self.create_file(
            content=content,
            filename=f'{inflection.pluralize(model)}.json',
            path=self.cwd,
        )
Ejemplo n.º 3
0
    def delete(self, model, **kwargs):
        model = self.check_noun(model)
        classname = inflection.camelize(model)
        class_type = kwargs.get('class_type', None)

        filename = f"{model}.py"
        template_import = 'view-function-import.tpl'

        if class_type is not None:
            filename = f"{model}_{class_type}.py"
            template_import = 'view-class-import.tpl'

        content = rendered_file_template(path=self.TEMPLATES_DIRECTORY,
                                         template=template_import,
                                         context={
                                             'model': model,
                                             'classname': classname,
                                             'class_type': class_type,
                                         })

        self.remove_import(content=content)

        if self.destroy_file(filename=filename, path=self.cwd):

            resource = f"{model}_view."
            if class_type:
                resource = f"{classname}{class_type.capitalize()}View."
            log_success(DEFAULT_DELETE_MESSAGE.format(filename, resource))

        return True
Ejemplo n.º 4
0
    def __create(self, project, template, filename):

        # return self.run_or_log_dry(message='Skipping creating with --dry enabled')

        try:
            self.change_directory(self.cwd)

            content = rendered_file_template(path=TEMPLATE_DIR,
                                             template=template,
                                             context={'project': project})
            self.create_file(content=content, filename=filename)
            log_success(f"Created {filename}")
        except FileNotFoundError:
            log_error(f"Unable to create {filename}")
Ejemplo n.º 5
0
    def create(self, model, **kwargs):

        model = sanitized_string(model)
        class_type = kwargs.get('class_type', None)
        page_title = inflection.camelize(model)

        template = 'template.tpl'
        filename = f"{model}.html"
        if class_type:
            if class_type not in ['template']:
                filename = f"{model.lower()}_{class_type}.html"
                template = f"template_{class_type}.tpl"

            if class_type == 'list':
                page_title = inflection.pluralize(model)

        content = rendered_file_template(path=self.TEMPLATES_DIRECTORY,
                                         template=template,
                                         context={'page_title': page_title})

        self.create_file(path=self.cwd, filename=filename, content=content)

        log_success(f"Successfully created {filename} template.")
Ejemplo n.º 6
0
    def create_app(self, app, auth=False, project=None, **kwargs):
        """
        Creates a django app and customizes its directory

        :param project: name of django project
        :param app: name of django app
        :param auth: app is used for authentication
        :param kwargs:
        :return: app directory. None if an error occurred.
        """

        project = '' if not project else sanitized_string(project)
        app = sanitized_string(app)

        if self.is_dry:
            if self.verbose:
                log_standard(
                    f'Skipping creation of app {app} with --dry enabled')
            return False

        if self.verbose:
            log_verbose(header=f'Creating app {app}:',
                        message=f'\tLocation: {os.getcwd()}')

        # Create django application
        try:
            if self.package:
                self.make_directory(app)
                self.change_directory(app)

            subprocess.check_output(['django-admin', 'startapp', app])
        except subprocess.CalledProcessError:
            log_error(DEFAULT_ERRORS['app'].format(app))
            return False

        # Add license, setup.py, and other files
        if self.package:
            try:
                for filename, template in APP_PACKAGE_FILES.items():
                    content = rendered_file_template(
                        path=self.TEMPLATES_DIRECTORY,
                        template=template,
                        context={
                            'app': app,
                            'app_namespace': app,
                            'classname': inflection.camelize(app),
                            'package': self.package,
                            'project': project,
                            'year': datetime.today().year,
                            **kwargs,
                        })

                    self.create_file(path=os.getcwd(),
                                     filename=filename,
                                     content=content)
            except OSError:
                pass

        # Perform app customizations
        self.change_directory(app)
        directory = os.getcwd()
        FSHelper.config['apps'].append({
            'app':
            app,
            'path':
            directory,
            'created_at':
            now().strftime("%d/%m/%Y %H:%M:%S"),
            'updated_at':
            now().strftime("%d/%m/%Y %H:%M:%S"),
        })

        if self.verbose:
            log_verbose(header='Customizations:', message=f'\t{app}')

        # Remove unwanted files
        try:
            for unwanted in UNWANTED_FILES:
                os.remove(unwanted)
        except FileNotFoundError:
            pass

        if self.verbose:
            log_verbose(header="Removed unwanted modules:",
                        message=f'\t{UNWANTED_FILES}')

        # Parse templates for apps.py and urls.py
        try:
            for filename, template in APP_TEMPLATES.items():
                content = rendered_file_template(path=self.TEMPLATES_DIRECTORY,
                                                 template=template,
                                                 context={
                                                     'app':
                                                     app,
                                                     'classname':
                                                     inflection.camelize(app),
                                                     'package':
                                                     self.package,
                                                     'project':
                                                     project,
                                                 })

                self.create_file(path=os.getcwd(),
                                 filename=filename,
                                 content=content)
        except OSError:
            pass

        # Create app-specific packages and module
        if kwargs.get('api'):
            DEFAULT_APP_PACKAGES.remove('admin')
            DEFAULT_APP_PACKAGES.remove('forms')
            DEFAULT_APP_PACKAGES.remove('templates')
            DEFAULT_APP_PACKAGES.remove('views')

        if kwargs.get('audit_record'):
            DEFAULT_APP_PACKAGES.add('audit')

        for package in DEFAULT_APP_PACKAGES:
            try:
                self.create_app_package(package=package,
                                        project=project,
                                        app=app)
            except OSError as e:
                log_error(f"Cannot create package: {package}\n{e}")

        if auth:
            if self.verbose:
                log_verbose(header=f'Adding custom user model in {app}',
                            message='')

            self.__custom_app(project=project,
                              app=app,
                              base=os.getcwd(),
                              type=CustomAppType.Authentication)

        self.change_directory(PREVIOUS_WORKING_DIRECTORY)
        log_success(DEFAULT_APP_CREATION_LOG.format(app))

        return directory
Ejemplo n.º 7
0
    def create_app_package(self, package, project, app):
        """
        Create an app package and any associated sub-packages or modules

        :param package: name of app package
        :param project: name of django project
        :param app: name of app
        :return: None
        """

        package = sanitized_string(package)
        app = sanitized_string(app)

        # Create app package
        self.create_package(project=project, package=package, app=app)

        # Package customizations
        self.change_directory(package)

        if self.verbose:
            log_verbose(header=f'Customizations for "{package}":', message='')

        self.create_package(project=project, package='helpers', app=app)
        if package == 'admin':
            self.create_package(project=project, package='actions', app=app)
            self.create_package(project=project, package='inlines', app=app)
            self.create_package(project=project,
                                package='permissions',
                                app=app)
        if package == 'audit':
            filename = '__init__.py'
            index = self.TEMPLATE_FILES.index('audit.tpl')
            template = self.TEMPLATES_DIRECTORY[index]

            content = rendered_file_template(path=self.TEMPLATES_DIRECTORY,
                                             template=template,
                                             context={
                                                 'app':
                                                 app,
                                                 'classname':
                                                 inflection.camelize(app),
                                                 'package':
                                                 package,
                                                 'project':
                                                 project,
                                             })

            self.create_file(
                path=os.getcwd(),
                filename=filename,
                content=content,
                force=True,
            )
        if package == 'models':
            self.create_package(project=project, package='managers', app=app)
            self.create_package(project=project, package='signals', app=app)
            self.create_package(project=project, package='tests', app=app)
            self.create_package(project=project, package='validators', app=app)
            self.create_package(project=project,
                                package='permissions',
                                app=app)
        if package == 'serializers':
            self.create_package(project=project, package='tests', app=app)
        if package == 'views':
            filename = 'urls.py'
            index = self.TEMPLATE_FILES.index('routes.tpl')
            template = self.TEMPLATE_FILES[index]

            content = rendered_file_template(path=self.TEMPLATES_DIRECTORY,
                                             template=template,
                                             context={
                                                 'app':
                                                 app,
                                                 'classname':
                                                 inflection.camelize(app),
                                                 'package':
                                                 self.package,
                                                 'project':
                                                 project,
                                             })

            self.create_file(
                path=os.getcwd(),
                filename=filename,
                content=content,
            )
        if package == 'viewsets':
            self.create_package(project=project,
                                package='permissions',
                                app=app)
            filename = 'router.py'
            index = self.TEMPLATE_FILES.index('router.tpl')
            template = self.TEMPLATE_FILES[index]

            content = rendered_file_template(path=self.TEMPLATES_DIRECTORY,
                                             template=template,
                                             context={
                                                 'app': app,
                                                 'package': self.package,
                                                 'project': project,
                                             })

            self.create_file(
                path=os.getcwd(),
                filename=filename,
                content=content,
            )

        self.change_directory(PREVIOUS_WORKING_DIRECTORY)

        if self.verbose:
            log_verbose(header=f'Finished customizing "{package}" package.',
                        message='')
Ejemplo n.º 8
0
    def create(self, model, **kwargs):
        model = self.check_noun(model)
        model = sanitized_string(model)
        classname = inflection.camelize(model)
        singular = inflection.singularize(classname)
        plural = inflection.pluralize(classname)
        class_type = kwargs.get('class_type', None)
        extra = {}

        filename = f"{model.lower()}.py"
        template = 'view-function.tpl'
        template_import = 'view-function-import.tpl'
        view_name = inflection.underscore(singular)
        route_name = f'{inflection.underscore(model)}/'
        template_name = f'{model.lower()}.html'

        if class_type is not None:
            filename = f"{model.lower()}_{class_type}.py"
            template = 'view-class.tpl'
            template_import = 'view-class-import.tpl'

            if class_type not in ['template']:
                view_name = inflection.underscore(singular) + f'-{class_type}'
                template_name += f'_{class_type.lower()}.html'
                extra[
                    'object_name'] = plural if class_type == 'list' else singular

            if class_type in ['form', 'update', 'create']:
                extra['form_class'] = f'{classname}Form'

            if class_type in ['list']:
                route_name = f'{inflection.underscore(plural)}/'
                extra['pagination'] = True

            if class_type in ['detail', 'update']:
                route_name += '<slug:slug>'

        content = rendered_file_template(path=self.TEMPLATES_DIRECTORY,
                                         template=template,
                                         context={
                                             'model': model,
                                             'classname': classname,
                                             'class_type': class_type,
                                             'route_name': route_name,
                                             'view_name': view_name,
                                             'template_name': template_name,
                                             **extra,
                                         })

        import_content = rendered_file_template(path=self.TEMPLATES_DIRECTORY,
                                                template=template_import,
                                                context={
                                                    'model': model,
                                                    'classname': classname,
                                                    'class_type': class_type,
                                                })

        self.add_import(template=template_import, content=import_content)

        if self.create_file(path=self.cwd, filename=filename, content=content):

            resource = f"{model}_view."
            if class_type:
                resource = f"{classname}{class_type.capitalize()}View."
            log_success(DEFAULT_CREATE_MESSAGE.format(filename, resource))