Importing A Theme From A Template
6665
function importTheme(req, res, next) {
  req.appformsResultPayload = req.appformsResultPayload || {};
  var themeData = (req.appformsResultPayload.data && req.appformsResultPayload.type === constants.resultTypes.themeTemplate) ? req.appformsResultPayload.data : undefined ;

  var importThemeParams = {
    theme: themeData,
    name: req.body.name,
    description: req.body.description,
    userEmail: req.user.email
  };

  forms.cloneTheme(_.extend(req.connectionOptions, importThemeParams), resultHandler(constants.resultTypes.themes, req, next));
}
311288
def install_templates(srcroot, destroot, prefix='', excludes=None,
                      includes=None, path_prefix=None):
    #pylint:disable=too-many-arguments,too-many-statements
    
    #pylint: disable=too-many-locals
    if excludes is None:
        excludes = []
    if includes is None:
        includes = []
    if not os.path.exists(os.path.join(prefix, destroot)):
        os.makedirs(os.path.join(prefix, destroot))
    for pathname in os.listdir(os.path.join(srcroot, prefix)):
        pathname = os.path.join(prefix, pathname)
        excluded = False
        for pat in excludes:
            if re.match(pat, pathname):
                excluded = True
                break
        if excluded:
            for pat in includes:
                if re.match(pat, pathname):
                    excluded = False
                    break
        if excluded:
            LOGGER.debug("skip %s", pathname)
            continue
        source_name = os.path.join(srcroot, pathname)
        dest_name = os.path.join(destroot, pathname)
        if os.path.isfile(source_name) and not os.path.exists(dest_name):
            # We don't want to overwrite specific theme files by generic ones.
            with open(source_name) as source:
                template_string = source.read()
            try:
                template_string = force_text(template_string)
                lexer = DebugLexer(template_string)
                tokens = lexer.tokenize()
                if not os.path.isdir(os.path.dirname(dest_name)):
                    os.makedirs(os.path.dirname(dest_name))
                engine, libraries, builtins = get_html_engine()
                if isinstance(engine, DjangoTemplates):
                    with open(dest_name, 'w') as dest:
                        parser = AssetsParser(tokens,
                            URLRewriteWrapper(dest, path_prefix),
                            libraries=libraries,
                            builtins=builtins,
                            origin=None)
                        parser.parse_through()
                else:
                    template_name = None
                    tokens = Lexer(engine.env).tokeniter(template_string,
                        template_name, filename=source_name)
                    buffered_tokens = []
                    state = None
                    with open(dest_name, 'w') as dest:
                        for token in tokens:
                            if state is None:
                                if token[1] == 'block_begin':
                                    state = STATE_BLOCK_BEGIN
                            elif state == STATE_BLOCK_BEGIN:
                                if token[1] == 'name':
                                    if token[2] == 'assets':
                                        state = STATE_ASSETS_BEGIN
                                    else:
                                        buffered_tokens += [token]
                                        state = None
                            elif state == STATE_ASSETS_BEGIN:
                                if (token[1] == 'name'
                                    and token[2] == 'endassets'):
                                    state = STATE_ASSETS_END
                            elif state == STATE_ASSETS_END:
                                if token[1] == 'block_end':
                                    buffered_tokens += [token]
                                    state = None
                            if state is None:
                                if buffered_tokens:
                                    for tok in buffered_tokens:
                                        if (tok[1] == 'name' and
                                            tok[2] == 'assets'):
                                            dest.write(_render_assets(
                                                buffered_tokens,
                                                engine.env.assets_environment))
                                            buffered_tokens = []
                                            break
                                    if buffered_tokens:
                                        dest.write("%s" % ''.join([token[2]
                                            for token in buffered_tokens]))
                                    buffered_tokens = []
                                else:
                                    dest.write("%s" % str(token[2]))
                            else:
                                buffered_tokens += [token]
                        if buffered_tokens:
                            dest.write("%s" % ''.join([
                                token[2] for token in buffered_tokens]))
                            buffered_tokens = []
                        dest.write("\n")

                cmdline = ['diff', '-u', source_name, dest_name]
                cmd = subprocess.Popen(cmdline, stdout=subprocess.PIPE)
                lines = cmd.stdout.readlines()
                cmd.wait()
                # Non-zero error codes are ok here. That's how diff
                # indicates the files are different.
                if lines:
                    verb = 'compile'
                else:
                    verb = 'install'
                dest_multitier_name = dest_name.replace(destroot,
                        '*MULTITIER_TEMPLATES_ROOT*')
                LOGGER.debug("%s %s to %s", verb,
                    source_name.replace(
                        django_settings.BASE_DIR, '*APP_ROOT*'),
                    dest_multitier_name)
            except UnicodeDecodeError:
                LOGGER.warning("%s: Templates can only be constructed "
                    "from unicode or UTF-8 strings.", source_name)
        elif os.path.isdir(source_name):
            install_templates(srcroot, destroot, prefix=pathname,
                excludes=excludes, includes=includes, path_prefix=path_prefix)
1118150
function loadThemeTranslations() {
        // This function is called during theme initialization, and when switching language or theme.
        currentLocale = I18n.locale();
        activeTheme = settingsCache.get('active_theme');

        // Reading file for current locale and active theme and keeping its content in memory
        if (activeTheme) {
            // Reading translation file for theme .hbs templates.
            // Compatibility with both old themes and i18n-capable themes.
            // Preventing missing files.
            try {
                themeStrings = fs.readFileSync(path.join(config.getContentPath('themes'), activeTheme, 'locales', currentLocale + '.json'));
            } catch (err) {
                themeStrings = undefined;
                if (err.code === 'ENOENT') {
                    if (currentLocale !== 'en') {
                        logging.warn(`Theme's file locales/${currentLocale}.json not found.`);
                    }
                } else {
                    throw err;
                }
            }
            if (themeStrings === undefined && currentLocale !== 'en') {
                logging.warn('Falling back to locales/en.json.');
                try {
                    themeStrings = fs.readFileSync(path.join(config.getContentPath('themes'), activeTheme, 'locales', 'en.json'));
                } catch (err) {
                    themeStrings = undefined;
                    if (err.code === 'ENOENT') {
                        logging.warn('Theme\'s file locales/en.json not found.');
                    } else {
                        throw err;
                    }
                }
            }
            if (themeStrings !== undefined) {
                // if translation file is not valid, you will see an error
                try {
                    themeStrings = JSON.parse(themeStrings);
                } catch (err) {
                    themeStrings = undefined;
                    throw err;
                }
            }
        }

        if (themeStrings === undefined) {
            // even if empty, themeStrings must be an object for jp.value
            themeStrings = {};
        }

        _private.initializeIntl();
    }
64013
def compile_theme(theme, target, *, zip_=False):
    
    from jinja2 import Environment, FileSystemLoader
    env = Environment(loader=FileSystemLoader(theme))
    env.compile_templates(target, zip='deflated' if zip_ else None)
1187771
def __copy_template(self):
        
        import shutil

        template_filename = "settings.json.template"
        template_path = path.abspath(
            path.join(__file__, "..", "..", "config", template_filename))
        settings_path = self.file_path
        shutil.copyfile(template_path, settings_path)

        self.__ensure_file_exists()
999433
def from_file(cls, filename, source):
        
        _logger.info('Loading theme %s', filename)

        try:
            config = configparser.ConfigParser()
            config.optionxform = six.text_type  # Preserve case
            with codecs.open(filename, encoding='utf-8') as fp:
                config.readfp(fp)
        except configparser.ParsingError as e:
            raise ConfigError(e.message)

        if not config.has_section('theme'):
            raise ConfigError(
                'Error loading {0}:\n'
                '    missing [theme] section'.format(filename))

        theme_name = os.path.basename(filename)
        theme_name, _ = os.path.splitext(theme_name)

        elements = {}
        for element, line in config.items('theme'):
            if element not in cls.DEFAULT_ELEMENTS:
                # Could happen if using a new config with an older version
                # of the software
                _logger.info('Skipping element %s', element)
                continue
            elements[element] = cls._parse_line(element, line, filename)

        return cls(name=theme_name, source=source, elements=elements)
949934
def copy_templates(entry_point, py_entry_point, auto_write, output_dir):
    '''
    '''

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    scripts = []
    for f in os.listdir(bin_path()):
        ext = os.path.splitext(f)[-1]
        newline = NEWLINE_MAP.get(ext, '\n')
        template = bin_path(f)
        destination = output_dir + '/' + entry_point + ext
        scripts.append(destination)

        with io.open(template, 'r') as f:
            code = f.read()
        code = code.replace('{{entry_point}}', entry_point)
        code = code.replace('{{py_entry_point}}', py_entry_point)
        code = code.replace('{{auto_write}}', str(int(auto_write)))

        with io.open(destination, 'w', newline=newline) as f:
            f.write(code)

    return scripts
1082526
function() {
            var self = this;

            this.template = this.options.template;
            this.args = this.options.args || {};

            // Related view
            this.view = this.options.view || null;

            // Init template context
            _.extend(this.args, {
                "_": _,
                "hr": {
                    "configs": configs,
                    "urls": Urls,
                    "i18n": I18n,
                    "offline": Offline
                },
                "view": {
                    "component": function(cid, args, name, subid) {
                        name = name || cid;

                        if (!self.view) {
                            throw new Error("Error in template " + self.template + " : try to import component in a non view-related template ");
                        }

                        if (Template.components[cid] == null) {
                            throw new Error("Error in template " + self.template + " : try to import component "+cid);
                        }

                        var view = new Template.components[cid].Class(args || {}, self.view);
                        
                        self.view.addComponent(name, view);

                        var component = $("<component/>", {
                            "data-component": view.cid
                        });

                        return component[0].outerHTML;
                    }
                },
                "template": {
                    "args": this.args,
                    "name": this.template,
                    "import": function(name, args, cname) {
                        cname = cname || name;
                        return this.args.view.component("template", {template: name, args: args}, cname);
                    },
                    "htmlid": function(h) {
                        return _.escape(h);
                    }
                }
            }, Template.options);

            return this;
        }
341957
def get_template(self, template_name):
        """"""
        try:
            return self.loader.load(template_name, encoding=self.encoding)
        except self.not_found_exception, e:
            # catch the exception raised by Genshi, convert it into a werkzeug
            # exception (for the sake of consistency)
            raise TemplateNotFound(template_name)
357255
def load_template(self, template: str) -> Template:
        """"""
        env = dict(trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=False)
        jinja2_ext = ".jinja2"
        if not template.endswith(jinja2_ext):
            self._log.error("Template file name must end with %s" % jinja2_ext)
            raise ValueError
        if not template[:-len(jinja2_ext)].endswith(".md"):
            self._log.error("Template file should be a Markdown file.")
            raise ValueError
        if not os.path.isabs(template):
            template = os.path.join(os.path.dirname(__file__), template)
        with open(template, encoding="utf-8") as fin:
            template_obj = Template(fin.read(), **env)
        template_obj.filename = template
        self._log.info("Loaded %s", template)
        return template_obj
855723
function importThemes(req, res, next) {
  var options = req.connectionOptions;

  var themesToImport = req.body || [];

  if (!_.isArray(req.body)) {
    return next("Expected An Array Of Themes");
  }

  forms.importThemes(options, themesToImport, resultHandler(constants.resultTypes.themes, req, next));
}
87452
def generate_template(template_name, **context):
    """"""
    context.update(href=href, format_datetime=format_datetime)
    return template_loader.load(template_name).generate(**context)
276465
def load_template_source(template_name, template_dirs=None):
    """"""
    template_zipfiles = getattr(settings, "TEMPLATE_ZIP_FILES", [])

    # Try each ZIP file in TEMPLATE_ZIP_FILES.
    for fname in template_zipfiles:
        try:
            z = zipfile.ZipFile(fname)
            source = z.read(template_name)
        except (IOError, KeyError):
            continue
        z.close()
        # We found a template, so return the source.
        template_path = "%s:%s" % (fname, template_name)
        return (source, template_path)

    # If we reach here, the template couldn't be loaded
    raise TemplateDoesNotExist(template_name)
990619
def render_template(self):
        """"""
        self._parse_paths()
        context = dict(napp=self._napp.__dict__, paths=self._paths)
        self._save(context)
453232
def init(self, project_name='', template='base', quiet=False, debug=False):
        ''''''

        self.logger.setLevel(DEBUG if debug else WARNING)

        self.logger.info('Project creation started.')

        self.logger.debug(f'Template: {template}')

        template_path = Path(template)

        if not template_path.exists():
            self.logger.debug(
                f'Template not found in {template_path}, looking in installed templates.'
            )

            installed_templates_path = Path(Path(__file__).parent / 'templates')

            installed_templates = [
                item.name for item in installed_templates_path.iterdir() if item.is_dir()
            ]

            self.logger.debug(f'Available templates: {installed_templates}')

            if template in installed_templates:
                self.logger.debug('Template found.')

            else:
                self.logger.debug('Template not found, asking for user input.')

                try:
                    template = prompt(
                        f'Please pick a template from {installed_templates}: ',
                        completer=WordCompleter(installed_templates),
                        validator=BuiltinTemplateValidator(installed_templates)
                    )

                except KeyboardInterrupt:
                    self.logger.warning('Project creation interrupted.')
                    return

            template_path = installed_templates_path / template

            self.logger.debug(f'Template path: {template_path}')

        if not project_name:
            self.logger.debug('Project name not specified, asking for user input.')

            try:
                project_name = prompt('Enter the project name: ')

            except KeyboardInterrupt:
                self.logger.warning('Project creation interrupted.')
                return

        project_slug = slugify(project_name)
        project_path = Path(project_slug)

        properties = {
            'title': project_name,
            'slug': project_slug
        }

        self.logger.debug(f'Project properties: {properties}')

        result = None

        with spinner('Generating project', self.logger, quiet, debug):
            copytree(template_path, project_path)

            text_types = '*.md', '*.yml', '*.txt', '*.py'

            text_file_paths = reduce(
                lambda acc, matches: acc + [*matches],
                (project_path.rglob(text_type) for text_type in text_types),
                []
            )

            for text_file_path in text_file_paths:
                self.logger.debug(f'Processing content of {text_file_path}')
                replace_placeholders(text_file_path, properties)

            for item in project_path.rglob('*'):
                self.logger.debug(f'Processing name of {item}')
                item.rename(Template(item.as_posix()).safe_substitute(properties))

            result = project_path

        if result:
            self.logger.info(f'Result: {result}')

            if not quiet:
                print('─' * 20)
                print(f'Project "{project_name}" created in {result}')
            else:
                print(result)

        else:
            self.logger.critical('Project creation failed.')
            exit(1)
584050
def render_template(self):
        """"""
        self.import_mappings()
        self.create_template()
        if self.description:
            self.set_template_description(self.description)
        self.setup_parameters()
        rendered = self.template.to_json(indent=self.context.template_indent)
        version = hashlib.md5(rendered.encode()).hexdigest()[:8]
        return (version, rendered)
816097
def dbtemplate_save(sender, instance, created, **kwargs):
    

    if created:
        if 'widget' in instance.name:
            name = instance.name.split('/')[-1]
            kwargs = {
                'name': name.split('.')[0],
                'label': name.split('.')[0].capitalize(),
                'template': instance,
            }
            if 'base/widget' in instance.name:
                from leonardo.module.web.models import WidgetBaseTheme
                theme_cls = WidgetBaseTheme
            else:
                from leonardo.module.web.models import WidgetContentTheme
                theme_cls = WidgetContentTheme
                from leonardo.utils.widgets import find_widget_class
                w_cls_name = instance.name.split('/')[-2]
                w_cls = find_widget_class(w_cls_name)
                if w_cls is None:
                    raise Exception('widget class for %s not found' % w_cls_name)
                kwargs['widget_class'] = w_cls.__name__
            theme_cls(**kwargs).save()

        if 'base/page' in instance.name:
            from leonardo.module.web.models import PageTheme
            page_theme = PageTheme()
            page_theme.label = '{} layout'.format(
                instance.name.split("/")[-1].split('.')[0].title())
            page_theme.name = instance.name.split("/")[-1]
            page_theme.template = instance
            page_theme.save()