def __compile_css(*args, **kwargs): output = os.path.join(PROJECT_PATH, kwargs['output']) if kwargs['output'] else OUT_PATH __create_dir_if_not_exists(output) try: import lesscpy print 'Compiling AnyChart UI css' css_src_path = os.path.join(PROJECT_PATH, 'css', 'anychart.less') css_out_path = os.path.join(output, 'anychart-ui.css') css_min_out_path = os.path.join(output, 'anychart-ui.min.css') # Less with open(css_out_path, 'w') as f: f.write(lesscpy.compile(css_src_path)) # Minify with open(css_min_out_path, 'w') as f: f.write(lesscpy.compile(css_src_path, xminify=True)) if kwargs['gzip']: __gzip_file(css_out_path) __gzip_file(css_min_out_path) except ImportError: raise ImportError('Please install lesscpy manually first.')
def test_compile_from_stream(self): """ It can compile input from a file-like object """ output = compile(StringIO("a { border-width: 2px * 3; }"), minify=True) self.assertEqual(output, "a{border-width:6px;}");
def css(self): content = None path = '.'+self.req.path if os.path.isfile(path): f = open(path) content = f.read() f.close() else: path = re.sub('(\.css)', '.less', path, flags=re.IGNORECASE) if os.path.isfile(path): f = open(path) f_content = f.read() f.close() for l in thorinService.less_list: if l['path'] == path: content = l['css'] break if not content: content = lesscpy.compile(StringIO(f_content), minify=True) if thorinService.env.get('location') and thorinService.env['location'] == 'prod': thorinService.less_list.append({ 'path': path, 'css': content }) return content
def handle_less(less_str): """ 编译less字符串 :param less_str: less字符串 :return: """ return lesscpy.compile(StringIO(less_str))
def preProcessCSS(cnt, partial=""): """ Apply css-preprocessing on css rules (according css.type) using a partial or not return the css pre-processed """ if cnt.type in ["scss", "sass"]: if hasSass: from scss.compiler import compile_string #lang="scss" return compile_string(partial + "\n" + cnt.value) else: print( "***WARNING*** : miss 'sass' preprocessor : sudo pip install pyscss" ) return cnt.value elif cnt.type in ["less"]: if hasLess: import lesscpy, six return lesscpy.compile(six.StringIO(partial + "\n" + cnt.value), minify=True) else: print( "***WARNING*** : miss 'less' preprocessor : sudo pip install lesscpy" ) return cnt.value else: return cnt.value
def write_to_css(): """ write less-compiled css file to css_fpath in jupyter_dir""" os.chdir(package_dir) css_content = lesscpy.compile(less_tempfile) with open(css_fpath, 'w') as f: f.write(css_content) os.remove(less_tempfile)
def catch_all(path): # Verify the file exists, then send it to the client if not isfile(path): return (Helpers.fourohfour(path), 404) else: # Let's be adventurous: just run Python! The script being run # should set output content into `globals()['output']` and, if # necessary, the MIME type in `globals()['output_type']` if path.endswith('.py'): gDict = {'output': None, 'output_type': 'text/html'} execfile(path, gDict) if gDict['output'] is None: msg = 'ERROR: globals()["output"] not set by {}'.format(path) return (Helpers.fiveohoh(path, msg), 500) else: return Response(gDict['output'], mimetype=gDict['output_type']) # Run SASS/SCSS/LESS files through the appropriate compiler if path.endswith('.scss') or path.endswith('.sass'): return sass.compile(string=Helpers.returncontent(path), output_style='compressed') if path.endswith('.less'): return lesscpy.compile(Helpers.returncontent(path), minify=True) # For everything else, just send it content = Helpers.returncontent(path) mtype = Helpers.gettype(path) return Response(content, mimetype=mtype)
def convert_all_less_to_css(): for fn_less in glob('**/*.less', recursive=True): print(fn_less) with open(fn_less) as f: css = lesscpy.compile(f) with open(fn_less.replace('.less', '.css'), 'w') as f: f.write(css)
def test_compile(self): """ It can compile input from a file-like object """ output = compile(StringIO("a { border-width: 2px * 3; }"), minify=True) self.assertEqual(output, "a{border-width:6px;}")
def compile_styles(file=join_path(ROOT, 'less', 'default.less')): with open(file, encoding='utf-8') as raw_file: raw_text = raw_file.read() css = lesscpy.compile(StringIO(raw_text)) with open(join_path(ROOT, 'css', 'default.css'), 'w', encoding='utf-8') as css_file: css_file.write(css)
def compile_styles(file=join_path(ROOT, "less", "default.less")): with open(file, encoding="utf-8") as raw_file: raw_text = raw_file.read() css = lesscpy.compile(StringIO(raw_text)) with open(join_path(ROOT, "css", "default.css"), "w", encoding="utf-8") as css_file: css_file.write(css)
def test_raises_exception(self): """ Test if a syntax error raises an exception """ from lesscpy.exceptions import CompilationError fail_func = lambda: compile(StringIO("a }"), minify=True) self.assertRaises(CompilationError, fail_func)
def render_styles(self): stylertl = open(self.indexpath+"/css/style-rtl.css", 'w') styleltr = open(self.indexpath+"/css/style-ltr.css", 'w') rtlvars = jsonmerge.merge(self.siteconfig['stylevars'], {"dir": "rtl", "side": "right", "oposide": "left" }) srtl = lesscpy.compile(six.StringIO(stache.render(stache.load_template('authorsite.less'),rtlvars).encode('utf-8')),minify=True) if srtl: stylertl.write(srtl) stylertl.close() logger.info('rtl styles done') ltrvars = jsonmerge.merge(self.siteconfig['stylevars'],{ "dir": "ltr", "side": "left", "oposide": "right" }) sltr = lesscpy.compile(six.StringIO(stache.render(stache.load_template('authorsite.less'),ltrvars).encode('utf-8')),minify=True) if sltr: styleltr.write(sltr) if not sltr or not srtl: logger.error("could not compile authorsite.less") styleltr.close() logger.info('ltr styles done')
def _compile(self): inputs = self._raw with Temp('temp.css') as f: f.write(inputs) # TODO: this and JS should really have a common base class import lesscpy return lesscpy.compile(f.abspath, minify=False)
def less_to_css(style_less): """ write less-compiled css file to jupyter_customcss in jupyter_dir """ with open(tempfile, 'w') as f: f.write(style_less) os.chdir(package_dir) style_css = lesscpy.compile(tempfile) style_css += '\n\n' return style_css
def generate_css(): import lesscpy from io import StringIO less = "" for f in os.listdir(pthjoin(STATICFOLDER, "less")): with open(pthjoin(STATICFOLDER, "less", f), "r") as lessf: less += lessf.read() css = lesscpy.compile(StringIO(less), minify=True) return css
def test_compile_from_file(self): """ It can compile input from a file object """ import tempfile in_file = tempfile.NamedTemporaryFile(mode='w+') in_file.write("a { border-width: 2px * 3; }") in_file.seek(0) output = compile(in_file, minify=True) self.assertEqual(output, "a{border-width:6px;}");
def _add_style_to_svg(klass): """ Compile the assets/svg.less file and return an svg Style object that contains the css formatting. Returns None """ if not klass.css_style: klass.css_style = lesscpy.compile("assets/svg.less") klass.svg.add(klass.svg.style(klass.css_style))
def storeMinifed(self, css, text, toReplace): """ to minify and store in history with hash key """ if self.cache and self.getHashed(text) in self.history.keys(): return self.history[self.getHashed(text)] else: minifed = compile( StringIO(toReplace), minify=True, xminify=True ) if css else jsmin(toReplace).replace('\n', ';') if self.cache and self.getHashed(text) not in self.history.keys(): self.history[self.getHashed(text)] = minifed return minifed
def processElement(self, ctx:Context, f): rawText = f.readText() rawText = lesscpy.compile( io.StringIO(rawText), minify=self.__minify, tabs=True, ) assert isinstance(rawText, str) f2 = InMemoryFile(f.relFilePathWithoutExt + ".css", LessC.__FILE_TYPE_INFO, rawText) return f2
def test_compile_from_file(self): """ It can compile input from a file object """ import tempfile in_file = tempfile.NamedTemporaryFile(mode='w+') in_file.write("a { border-width: 2px * 3; }") in_file.seek(0) output = compile(in_file, minify=True) self.assertEqual(output, "a{border-width:6px;}")
def render(self, environment): print("Render %s" % self) directory = os.path.split(self.target_path)[0] os.makedirs(directory, exist_ok=True) if os.path.isfile(self.source_path): if os.path.exists(self.target_path): os.remove(self.target_path) with open(self.source_path, "r") as pre: with open(self.target_path, "w") as compiled: compiled.write(lesscpy.compile(pre, minify=True))
def less_compile(content=None): p = os.path.abspath('') + '\\test.less' with open(p, 'r') as less_src: less_src = less_src.read() less_src = re.sub('(((?<!:)//.+)|(/\*[\S\s]+?\*\/))', '', less_src) # убирает комментарии content = re.sub(r'url\("([\w\d\.\:\_\-\/]+)"\)', 'url(\1)', less_src) # убирает кавычки внутри url() css = lesscpy.compile(StringIO(content)) p = os.path.abspath('') + '\\test.css' with open(p, 'w') as cssfl: cssfl.write(css)
def compileAndWrite(v, settings, content=None): STYLES = settings.get('styles', 'styles') CSS = settings.get('css', 'css') LESS = settings.get('less', 'less') v = v or view_from_sublime() lessfile = v.file_name() sm("less2css: Compiling {}".format(lessfile)) if not lessfile: return em('You must save this view to compile it!') ext = os.path.splitext(lessfile)[1] if ext != '.less': return em("Can only compile '.less' files, not '{}'!".format(ext)) style_dir, cssfile = dirnameUntil(lessfile, STYLES) if style_dir is False: return em("All your style must be put in a {} folders. See README.md for more infos".format(STYLES)) cssfile = CSS + os.path.sep + os.path.sep.join(cssfile.split(os.path.sep)[1:]) cssfile = os.path.dirname(cssfile) cssfile = os.path.join(style_dir, cssfile, os.path.splitext(os.path.basename(lessfile))[0] + '.css') if content is None: with open(lessfile, 'r') as fp: content = fp.read() try: less = lesscpy.compile(io.StringIO(content)) except lesscpy.exceptions.CompilationError as e: em(e.msg) else: dirname = os.path.dirname(cssfile) if not os.path.exists( dirname ): os.makedirs(dirname) with open(cssfile, 'w') as fp: fp.write(less) sm("less2css: Finished compiling {}".format(cssfile))
def less_compile(less_src, tgt, o='w'): less_src = re.sub('(((?<!:)//.+)|(/\*[\S\s]+?\*\/))','', less_src) # убирает комментари # less_src = re.sub(r'url\(([\w\d\.\:\_\-\/]+)\)', 'url("\1")', less_src) # добавляет кавычки внутри url() with open(r'C:\Users\admin\Desktop\test.less', 'w') as p: p.write(less_src) css = lesscpy.compile(StringIO(less_src)) # minify=True # lesscpy.compile(StringIO(u"a { border-width: 2px * 3; }"), minify=True) # css = re.sub(r'url\("([\w\d\.\:\_\-\/]+)"\)', 'url(\1)', css) # убирает кавычки внутри url() css = '\n\n' + css with open(tgt, o) as tgt_file: tgt_file.write(css) print "less compiled to {}".format(tgt)
def create_theme_styles(theme_id, install_sticker): with open_file(os.path.join(styles_dir, 'themes', theme_id + '.less'), 'r') as base_styles: styles = base_styles.read() + '\n' with open_file(os.path.join(styles_dir, 'base.less'), 'r') as base_styles: styles += base_styles.read() + '\n' if install_sticker: with open_file(os.path.join(styles_dir, 'sticker.less'), 'r') as base_styles: styles += base_styles.read() + '\n' with open_file(evaluated_less_file, 'w') as evaluated_less: evaluated_less.write(styles) return lesscpy.compile(evaluated_less_file) + '\n\n'
def resource_handler(flask, resdir, path): fname, ext = os.path.splitext(path) filepath = os.path.join(resdir, path) if filepath in resources_cache: return resources_cache[filepath] if ext == '.less': f = open(filepath, 'r') lessfile = f.read() f.close() cssfile = lesscpy.compile(StringIO(lessfile), minify=True) response = flask.Response(str(cssfile)) response.headers['Content-Type'] = 'text/css' resources_cache[filepath] = response return resources_cache[filepath] return None
def saveHtml(self, filename): file = self.basedir + "/" + filename + ".html" self.saveScripts() imgdata = pkgutil.get_data('ivwpy', 'regression/resources/inviwo.png') imgdir = mkdir(self.basedir, "_images") with open(toPath(imgdir, "inviwo.png"), 'wb') as f: f.write(imgdata) cssdata = pkgutil.get_data('ivwpy', 'regression/resources/report.css') with open(toPath(self.basedir, "report.css"), 'w') as f: f.write(lesscpy.compile(io.StringIO(cssdata.decode("utf-8")))) with open(file, 'w') as f: f.write(yattag.indent(self.doc.getvalue())) return file
def compile_less_code(self, less_code, minify=False): """Compiles less code via the lesscpy compiler. This procedure returns the compiled css code that results of the compilation of the code as a string. Errors are discarded and not returned back. """ output = '' try: less_code = less_code.encode('utf-8') output = lesscpy.compile( StringIO(less_code), xminify=minify ) except Exception as e: self.logger.error(e) return None return output
def set_vim_style(theme): """ add style and compatibility with vim notebook extension """ vim_jupyter_nbext = os.path.join(jupyter_nbext, 'vim_binding') if not os.path.isdir(vim_jupyter_nbext): os.makedirs(vim_jupyter_nbext) vim_less = '@import "styles{}";\n'.format(''.join([os.sep, theme])) with open(vim_style, 'r') as vimstyle: vim_less += vimstyle.read() + '\n' with open(vimtemp, 'w') as vtemp: vtemp.write(vim_less) os.chdir(package_dir) vim_css = lesscpy.compile(vimtemp) vim_css += '\n\n' # install vim_custom_css to ...nbextensions/vim_binding/vim_binding.css vim_custom_css = os.path.join(vim_jupyter_nbext, 'vim_binding.css') with open(vim_custom_css, 'w') as vim_custom: vim_custom.write(vim_css)
def set_vim_style(theme): """Add style and compatibility with vim notebook extension""" vim_jupyter_nbext = os.path.join(jupyter_nbext, 'vim_binding') if not os.path.isdir(vim_jupyter_nbext): os.makedirs(vim_jupyter_nbext) vim_less = '@import "styles{}";\n'.format(''.join([os.sep, theme])) with open(vim_style, 'r') as vimstyle: vim_less += vimstyle.read() + '\n' with open(vimtemp, 'w') as vtemp: vtemp.write(vim_less) os.chdir(package_dir) vim_css = lesscpy.compile(vimtemp) vim_css += '\n\n' # install vim_custom_css to ...nbextensions/vim_binding/vim_binding.css vim_custom_css = os.path.join(vim_jupyter_nbext, 'vim_binding.css') with open(vim_custom_css, 'w') as vim_custom: vim_custom.write(vim_css) os.remove(vimtemp)
def compile_less(): root = os.path.dirname(__file__) dir_name = os.path.abspath(os.path.join(root, 'src/restfx/internal_assets/styles')) import lesscpy for file in os.listdir(dir_name): file_path = os.path.join(dir_name, file) if not os.path.isfile(file_path) or not file.lower().endswith('.less'): continue print('Compiling file %s' % file) with open(file_path, encoding='utf8') as fp: output_content = lesscpy.compile(fp, minify=True) output_file = os.path.splitext(file_path)[0] + '.css' with open(output_file, mode='w', encoding='utf8') as fp: fp.write(output_content) print('Compiled!')
def statics(): os.makedirs(os.path.join(OUTPUT_DIR, 'statics')) copyfile(os.path.join(STATICS_DIR, 'edb.pdf'), os.path.join(OUTPUT_DIR, 'statics', 'edb.pdf')) copyfile( os.path.join(STATICS_DIR, 'friction-loss-materials.json'), os.path.join(OUTPUT_DIR, 'statics', 'friction-loss-materials.json')) copyfile( os.path.join(STATICS_DIR, 'friction-loss-materials-full.json'), os.path.join(OUTPUT_DIR, 'statics', 'friction-loss-materials-full.json')) copyfile(os.path.join(STATICS_DIR, 'unit-conversions.json'), os.path.join(OUTPUT_DIR, 'statics', 'unit-conversions.json')) copyfile(os.path.join(STATICS_DIR, 'viscosity.json'), os.path.join(OUTPUT_DIR, 'statics', 'viscosity.json')) css = lesscpy.compile(os.path.join(STATICS_DIR, 'style.less'), minify=True) with io.open(os.path.join(OUTPUT_DIR, 'statics', 'style.css'), 'w', encoding='utf8') as f: f.write(css)
def fail_func(): compile(StringIO("a }"), minify=True)
def build_css(app): """Build css files. Include app.css. """ static_path = app.static_folder libs = G.css_config['libs'] layout = G.css_config['layout'] page_root_path = G.css_config['page'] app_css_string = "" # Build app.css # libs for lib in libs: lib_path = os.path.join(static_path, lib) with open(lib_path) as css_file: file_content = css_file.read() # Rewrite relative path to absolute path file_content = _rewrite_relative_url(file_content, lib_path, static_path) app_css_string += file_content # layout for relative_layout_path in layout: absolute_layout_path = os.path.join(static_path, relative_layout_path) # 支持通配符 if '*' in absolute_layout_path: for path in glob2.iglob(absolute_layout_path): with open(path) as css_file: app_css_string += cssmin(css_file.read()) else: with open(absolute_layout_path) as css_file: app_css_string += cssmin(css_file.read()) # page blueprints = app.blueprints.keys() page_css_prefix = "#%s{" page_css_suffix = "}" page_root_path = os.path.join(static_path, page_root_path) for subdir in _get_immediate_subdirectories(page_root_path): if subdir in blueprints: subdir_path = os.path.join(page_root_path, subdir) for file in os.listdir(subdir_path): if file.endswith('.css'): action = file[:-4] page_id = "page-%s-%s" % (subdir, action) file_path = os.path.join(subdir_path, file) with open(file_path) as css_file: page_css_string = page_css_prefix % page_id page_css_string += css_file.read() page_css_string += page_css_suffix page_css_string = lesscpy.compile(StringIO(page_css_string), minify=True) app_css_string += page_css_string # print(file) app_css_string = app_css_string.replace('\n', '').replace('\r', '') with open(os.path.join(static_path, APP_CSS), "w") as text_file: text_file.write(app_css_string) print('app.css builded.')
def build_css(app): """Build css files. Include app.css. """ static_path = app.static_folder libs = G.css_config['libs'] layout = G.css_config['layout'] page_root_path = G.css_config['page'] app_css_string = "" # Build app.css # libs for lib in libs: lib_path = os.path.join(static_path, lib) with open(lib_path) as css_file: file_content = css_file.read() # Rewrite relative path to absolute path file_content = _rewrite_relative_url(file_content, lib_path, static_path) app_css_string += file_content # layout for relative_layout_path in layout: absolute_layout_path = os.path.join(static_path, relative_layout_path) # 支持通配符 if '*' in absolute_layout_path: for path in glob2.iglob(absolute_layout_path): with open(path) as css_file: app_css_string += cssmin(css_file.read()) else: with open(absolute_layout_path) as css_file: app_css_string += cssmin(css_file.read()) # page blueprints = app.blueprints.keys() page_css_prefix = "#%s{" page_css_suffix = "}" page_root_path = os.path.join(static_path, page_root_path) for subdir in _get_immediate_subdirectories(page_root_path): if subdir in blueprints: subdir_path = os.path.join(page_root_path, subdir) for file in os.listdir(subdir_path): if file.endswith('.css'): action = file[:-4] page_id = "page-%s-%s" % (subdir, action) file_path = os.path.join(subdir_path, file) with open(file_path) as css_file: page_css_string = page_css_prefix % page_id page_css_string += css_file.read() page_css_string += page_css_suffix page_css_string = lesscpy.compile( StringIO(page_css_string), minify=True) app_css_string += page_css_string # print(file) app_css_string = app_css_string.replace('\n', '').replace('\r', '') with open(os.path.join(static_path, APP_CSS), "w") as text_file: text_file.write(app_css_string) print('app.css builded.')
def write_to_css(): """ write less-compiled css file to css_fpath in jupyter_dir""" os.chdir(package_dir) css_content = lesscpy.compile(less_tempfile) css_content += '\n\n' return css_content
def generate_styles(): with open('docs/styles.css', 'w') as css_file: less = open('core/styles/main.less', 'r') css = lesscpy.compile(less, minify=True) css_file.write(css)
def _to_html_(self): div_id = u'i' + unicode(uuid.uuid4()) HTML_ = Template(u"""<div id="{{div_id}}"> {{html}} </div> """).render(div_id=div_id, html=self.html) # compute nested css div_css_wrapped = Template( """ #{{div_id}} { {{div_css}} } """).render(div_id=div_id, div_css=self.div_css) div_css_expanded = lesscpy.compile(StringIO(div_css_wrapped), minify=True) CSS = Template(u"""<style type="text/css"> {{css}} {{div_css_expanded}} </style> """).render(css=self.css, div_css_expanded=div_css_expanded) # JS JS = u""" <script type="text/javascript"> {% if csslibs %} // load css if it's not already there: http://stackoverflow.com/a/4724676/7782 function loadcss(url) { if (!$("link[href='" + url + "']").length) $('<link href="' + url + '" rel="stylesheet">').appendTo("head"); } {% endif %} {% for item in csslibs %} loadcss('{{item}}'); {% endfor %} require.config({ paths: { {% for item in jslibs %} '{{item.0}}': "{{item.1}}", {% endfor %} } }); require({{jslibs_names}}, function({{jslibs_objs}}) { var element = $('#{{div_id}}'); """ + self.js + u""" }); </script> """ template = Template(HTML_ + CSS + JS) return template.render(div_id=div_id, csslibs = self.csslibs, jslibs = self.jslibs, jslibs_names = "[{}]".format(",".join(['"{}"'.format(jslib[0]) for jslib in self.jslibs])), jslibs_objs = ",".join([jslib[2] for jslib in self.jslibs]), **self.extra_vars )
for i, line in enumerate(code.split('\n'), 1): if i in to_insert: res.append(to_insert[i]) if i not in del_lines: res.append(line) return "\n".join(res) for fn_py in glob("*/*.py"): if fn_py.endswith("utils.py"): continue fn_js = fn_py.replace(".py", ".js") if True or not path.exists(fn_js) or os.stat(fn_js).st_mtime < os.stat(fn_py).st_mtime: print(fn_py) with open(fn_py) as f: code_py = f.read() code_py = replace_utils_ast(fn_py, code_py) code_js = py2js(code_py, inline_stdlib=True) with open(fn_js, "wb") as f: f.write((wrap_code % code_js).encode('utf-8')) for fn_less in glob('**/*.less', recursive=True): print(fn_less) with open(fn_less) as f: css = lesscpy.compile(f) with open(fn_less.replace('.less', '.css'), 'w') as f: f.write(css)
def build_files(outdir): """Build the files!""" # Make sure there is actually a configuration file config_file_dir = os.path.join(cwd, "config.py") if not os.path.exists(config_file_dir): sys.exit( "There dosen't seem to be a configuration file. Have you run the init command?" ) else: sys.path.insert(0, cwd) try: from config import website_name, website_description, website_language, home_page_list except: sys.exit( "ERROR: Some of the crucial configuration values could not be found! Maybe your config.py is too old. Run 'blended init' to fix." ) try: from config import website_description_long, website_license, website_url, author_name, author_bio, plugins, minify_css, minify_js, custom_variables except: website_description_long = "" website_license = "" website_url = "" author_name = "" author_bio = "" plugins = [] custom_variables = {} minify_css = False minify_js = False print( "WARNING: Some of the optional configuration values could not be found! Maybe your config.py is too old. Run 'blended init' to fix.\n" ) # Create the build folder build_dir = os.path.join(cwd, outdir) if "." not in outdir and ".." not in outdir and "..." not in outdir and "...." not in outdir and "....." not in outdir: replace_folder(build_dir) # Make sure there is actually a header template file header_file_dir = os.path.join(cwd, "templates", "header.html") if not os.path.exists(header_file_dir): sys.exit( "There dosen't seem to be a header template file. You need one to generate." ) # Make sure there is actually a footer template file footer_file_dir = os.path.join(cwd, "templates", "footer.html") if not os.path.exists(footer_file_dir): sys.exit( "There dosen't seem to be a footer template file. You need one to generate." ) # Open the header and footer files for reading header_file = open(header_file_dir, "r") footer_file = open(footer_file_dir, "r") # Create the HTML page listing page_list_item_file = os.path.join(cwd, "templates", "page_list_item.html") if not os.path.exists(page_list_item_file): page_list = '<ul class="page-list">\n' for root, dirs, files in os.walk(os.path.join(cwd, "content")): for filename in files: top = os.path.dirname(os.path.join(root, filename)) top2 = top.replace(os.path.join(cwd, "content"), "", 1) if platform != "win32": subfolder = top2.replace("/", "", 1) else: subfolder = top2.replace("\\", "", 1) if subfolder == "": subfolder_link = "" else: subfolder_link = subfolder + "/" file_modified = time.ctime( os.path.getmtime(os.path.join(root, filename))) newFilename = get_html_filename(filename) newFilename2 = get_html_clear_filename(filename) page_list = page_list + '<li class="page-list-item"><a href="' + subfolder_link + newFilename + \ '">' + newFilename2 + '</a><span class="page-list-item-time"> - ' + \ str(file_modified) + '</span></li>\n' page_list = page_list + '</ul>' else: with open(page_list_item_file, 'r') as f: page_list_item = f.read() page_list = "" for root, dirs, files in os.walk(os.path.join(cwd, "content")): dirs[:] = [d for d in dirs if "_" not in d] for filename in files: p_content = convert_text(os.path.join(root, filename)) top = os.path.dirname(os.path.join(root, filename)) top2 = top.replace(os.path.join(cwd, "content"), "", 1) if platform != "win32": subfolder = top2.replace("/", "", 1) else: subfolder = top2.replace("\\", "", 1) if subfolder == "": subfolder_link = "" else: subfolder_link = subfolder + "/" file_modified = time.ctime( os.path.getmtime(os.path.join(root, filename))) file_modified_day = str( datetime.strptime(file_modified, "%a %b %d %H:%M:%S %Y"))[8:10] file_modified_year = str( datetime.strptime(file_modified, "%a %b %d %H:%M:%S %Y"))[:4] file_modified_month = str( datetime.strptime(file_modified, "%a %b %d %H:%M:%S %Y"))[5:7] month_name = calendar.month_name[int(file_modified_month)] newFilename = get_html_filename(filename) newFilename2 = get_html_clear_filename(filename) page_list = page_list + page_list_item.replace( "{path}", subfolder_link + newFilename).replace( "{name}", newFilename2).replace( "{date}", str(file_modified)).replace( "{content}", p_content).replace( "{content_short}", p_content[:250] + "..." ).replace("{day}", file_modified_day).replace( "{month}", file_modified_month).replace( "{month_name}", month_name).replace( "{year}", file_modified_year) if home_page_list == "yes" or home_page_list: # Open the home page file (index.html) for writing home_working_file = open(os.path.join(cwd, outdir, "index.html"), "w") home_working_file.write(header_file.read()) # Make sure there is actually a home page template file home_templ_dir = os.path.join(cwd, "templates", "home_page.html") if os.path.exists(home_templ_dir): home_templ_file = open(home_templ_dir, "r") home_working_file.write(home_templ_file.read()) else: print( "\nNo home page template file found. Writing page list to index.html" ) home_working_file.write(page_list) home_working_file.write(footer_file.read()) home_working_file.close() for root, dirs, files in os.walk(os.path.join(cwd, "content")): dirs[:] = [d for d in dirs if "_" not in d] for filename in files: if not filename.startswith("_"): header_file = open(header_file_dir, "r") footer_file = open(footer_file_dir, "r") newFilename = get_html_filename(filename) top = os.path.dirname(os.path.join(root, filename)) top2 = top.replace(os.path.join(cwd, "content"), "", 1) if platform != "win32": subfolder = top2.replace("/", "", 1) else: subfolder = top2.replace("\\", "", 1) if subfolder == "": currents_working_file = open( os.path.join(cwd, outdir, newFilename), "w") else: create_folder(os.path.join(cwd, outdir, subfolder)) currents_working_file = open( os.path.join(cwd, outdir, subfolder, newFilename), "w") # Write the header currents_working_file.write(header_file.read()) text_cont1 = convert_text(os.path.join(root, filename)) if "+++++" in text_cont1.splitlines()[1]: page_template_file = text_cont1.splitlines()[0] text_cont1 = text_cont1.replace(text_cont1.splitlines()[0], "") text_cont1 = text_cont1.replace(text_cont1.splitlines()[1], "") else: page_template_file = "content_page" # Write the text content into the content template and onto the # build file content_templ_dir = os.path.join(cwd, "templates", page_template_file + ".html") if os.path.exists(content_templ_dir): content_templ_file = open(content_templ_dir, "r") content_templ_file1 = content_templ_file.read() content_templ_file2 = content_templ_file1.replace( "{page_content}", text_cont1) currents_working_file.write(content_templ_file2) else: currents_working_file.write(text_cont1) # Write the footer to the build file currents_working_file.write("\n" + footer_file.read()) # Close the build file currents_working_file.close() # Find all the nav(something) templates in the `templates` folder and # Read their content to the dict navs = {} for file in os.listdir(os.path.join(cwd, "templates")): if "nav" in file: nav_cont = open(os.path.join(cwd, "templates", file), "r") navs[file.replace(".html", "")] = nav_cont.read() nav_cont.close() forbidden_dirs = set(["assets", "templates"]) blended_version_message = "Built with Blended v" + \ str(app_version) build_date = str(datetime.now().date()) build_time = str(datetime.now().time()) build_datetime = str(datetime.now()) # Replace global variables such as site name and language for root, dirs, files in os.walk(os.path.join(cwd, outdir)): dirs[:] = [d for d in dirs if d not in forbidden_dirs] for filename in files: if filename != "config.pyc" and filename != "config.py": newFilename = get_html_clear_filename(filename) page_file = filename.replace(".html", "") page_folder = os.path.basename( os.path.dirname(os.path.join(root, filename))).replace( "-", "").replace("_", "").title() page_folder_orig = os.path.basename( os.path.dirname(os.path.join(root, filename))) top = os.path.dirname(os.path.join(root, filename)) top2 = top.replace(os.path.join(cwd, outdir), "", 1) if platform != "win32": subfolder = top2.replace("/", "", 1) else: subfolder = top2.replace("\\", "", 1) if subfolder == "": subfolder_folder = os.path.join(cwd, outdir, filename) else: subfolder_folder = os.path.join(cwd, outdir, subfolder, filename) file_modified = time.ctime( os.path.getmtime(os.path.join(root, filename))) file_modified_day = str( datetime.strptime(file_modified, "%a %b %d %H:%M:%S %Y"))[8:10] file_modified_year = str( datetime.strptime(file_modified, "%a %b %d %H:%M:%S %Y"))[:4] file_modified_month = str( datetime.strptime(file_modified, "%a %b %d %H:%M:%S %Y"))[5:7] month_name = calendar.month_name[int(file_modified_month)] # The Loop! for line in fileinput.input(subfolder_folder, inplace=1): for var in custom_variables: line = line.replace("{" + var + "}", custom_variables[var]) if len(plugins) != 0: for i in range(len(plugins)): if sys.version_info[0] < 2: main = importlib.import_module(plugins[i]) elif sys.version_info[0] < 3: main = __import__(plugins[i]) content = main.main() line = line.replace("{" + plugins[i] + "}", content) if "{nav" in line: navname = line.split("{")[1].split("}")[0] line = line.replace( "{" + navname + "}", navs[(line.split("{"))[1].split("}")[0]]) line = line.replace("{website_description}", website_description) line = line.replace("{website_description_long}", website_description_long) line = line.replace("{website_license}", website_license) line = line.replace("{website_language}", website_language) line = line.replace("{website_url}", website_url) line = line.replace("{author_name}", author_name) line = line.replace("{author_bio}", author_bio) line = line.replace("{random_number}", str(randint(0, 100000000))) line = line.replace("{build_date}", build_date) line = line.replace("{build_time}", build_time) line = line.replace("{build_datetime}", build_datetime) line = line.replace("{page_list}", page_list) line = line.replace("{page_name}", newFilename) line = line.replace("{page_filename}", page_file) line = line.replace("{page_file}", filename) line = line.replace("{" + filename + "_active}", "active") if page_folder != outdir.title(): line = line.replace("{page_folder}", page_folder) else: line = line.replace("{page_folder}", "") if page_folder_orig != outdir: line = line.replace("{page_folder_orig}", page_folder_orig) else: line = line.replace("{page_folder_orig}", "") line = line.replace("{page_date}", str(file_modified)) line = line.replace("{page_day}", str(file_modified_day)) line = line.replace("{page_year}", str(file_modified_year)) line = line.replace("{page_month}", str(file_modified_month)) line = line.replace("{page_month_name}", str(month_name)) line = line.replace("{blended_version}", str(app_version)) line = line.replace("{blended_version_message}", blended_version_message) line = line.replace("{website_name}", website_name) top = os.path.join(cwd, outdir) startinglevel = top.count(os.sep) relative_path = "" level = root.count(os.sep) - startinglevel for i in range(level): relative_path = relative_path + "../" line = line.replace("{relative_root}", relative_path) print(line.rstrip('\n')) fileinput.close() # Copy the asset folder to the build folder if os.path.exists(os.path.join(cwd, "templates", "assets")): if os.path.exists(os.path.join(cwd, outdir, "assets")): shutil.rmtree(os.path.join(cwd, outdir, "assets")) shutil.copytree(os.path.join(cwd, "templates", "assets"), os.path.join(cwd, outdir, "assets")) for root, dirs, files in os.walk(os.path.join(cwd, outdir, "assets")): for file in files: if not file.startswith("_"): if (file.endswith(".sass")) or (file.endswith(".scss")): sass_text = open(os.path.join(root, file)).read() text_file = open(os.path.join(root, file[:-4] + "css"), "w") if sass_text != "": text_file.write(sass.compile(string=sass_text)) else: print(file + " is empty! Not compiling Sass.") text_file.close() if file.endswith(".less"): less_text = open(os.path.join(root, file)).read() text_file = open(os.path.join(root, file[:-4] + "css"), "w") if less_text != "": text_file.write(lesscpy.compile(StringIO(less_text))) else: print(file + " is empty! Not compiling Less.") text_file.close() if file.endswith(".styl"): try: styl_text = open(os.path.join(root, file)).read() text_file = open(os.path.join(root, file[:-4] + "css"), "w") if styl_text != "": text_file.write(Stylus().compile(styl_text)) else: print(file + " is empty! Not compiling Styl.") text_file.close() except: print( "Not able to build with Stylus! Is it installed?") try: subprocess.call["npm", "install", "-g", "stylus"] except: print("NPM (NodeJS) not working. Is it installed?") if file.endswith(".coffee"): coffee_text = open(os.path.join(root, file)).read() text_file = open(os.path.join(root, file[:-6] + "js"), "w") if coffee_text != "": text_file.write(coffeescript.compile(coffee_text)) else: print(file + " is empty! Not compiling CoffeeScript.") text_file.close() if minify_css: if file.endswith(".css"): css_text = open(os.path.join(root, file)).read() text_file = open(os.path.join(root, file), "w") if css_text != "": text_file.write(cssmin(css_text)) text_file.close() if minify_js: if file.endswith(".js"): js_text = open(os.path.join(root, file)).read() text_file = open(os.path.join(root, file), "w") if js_text != "": text_file.write(jsmin(js_text)) text_file.close()