def test_compile(self): # test bare=True jscode = coffeescript.compile(coffee_code, bare=True) ctx = execjs.compile(jscode) self.assertExprsSuccess(ctx) # test bare=False jscode = coffeescript.compile(coffee_code, bare=False) ctx = execjs.compile(jscode) self.assertExprsFail(ctx)
def runTest(request, fullpath): path = contrib.normpath(request.REQUEST["path"]) context_name = request.REQUEST.get("context", None) ctx = context.get(fullpath, section=context_name) log.info('run test %s with context %s' % (path, context_name)) server = request.get_host() contextjs = context.render(path, ctx, server) log.debug('contextJS: '+ contextjs) clean_path = contrib.get_relative_clean_path(path) target = contrib.get_runner_url(ctx, server) log.info('target of test %s is %s' % (clean_path, target)) tools.savetest(request.REQUEST.get('content', None), fullpath) test_content = request.REQUEST.get("content", open(fullpath, 'r').read()) #if contrib.target_is_remote( target, server): # log.debug('TARGET: %s, %s' % ( target, server )) # url = "http://%s/%s" % (target, settings.UPLOAD_TESTS_CMD) # saveRemoteContext(os.path.dirname(clean_path), contextjs, url, ctx) # distributor.saveTestSatelliteScripts(url, path, ctx) # distributor.sendContentToRemote(clean_path, test_content, url, ctx) # url = "http://%s/%s?path=/%s" % (target, settings.EXEC_TESTS_CMD, clean_path) #else: # saveLocalContext(fullpath, contextjs) # url = "http://%s/%s?path=/%s" % (target, settings.EXEC_TESTS_CMD, clean_path) saveLocalContext(fullpath, contextjs) if coffee(path): path = coffeescript.compile(test_content, path, fullpath) url = "http://%s/%s?server=%s&path=/%s" % (target, settings.EXEC_TESTS_CMD, server, path) log.info("redirect to run test %s" % url) return HttpResponseRedirect(url)
def compileSuiteCoffee(path, fullpath): #document_root = contrib.get_document_root(path) #enumroot = contrib.get_full_path(document_root, path) tests = contrib.enum_files_in_folders(fullpath, lambda file_: not file_.endswith(coffeescript.ext)) for test in tests: path = coffeescript.compile(None, None, os.path.join(fullpath, test)) log.info(path)
def script(fn): try: if not fn.endswith('.js'): return '' fn = 'scripts/' + fn[:-3] if os.path.exists(fn + '.js'): return file(fn + '.js', 'rb').read() try: jstat = os.stat(fn + '.cjs').st_mtime except: jstat = None try: cstat = os.stat(fn + '.coffee').st_mtime except: cstat = None if jstat == None and cstat == None: return '' elif jstat != None and cstat == None or jstat > cstat: return file(fn + '.cjs', 'rb').read() source = file(fn + '.coffee', 'rb').read() try: source = coffeescript.compile(source) except Exception, e: return 'window.location = "/_coffee_error?fn=" + encodeURIComponent(%r) + "&error=" + encodeURIComponent(%r);' % (str(fn + '.coffee'), str(e.message)) file(fn + '.cjs', 'wb').write(source) return source
def compile_coffee_to_js (self, coffee_name, code): # Compilation compiled_js = None try: compiled_js = coffeescript.compile(code) except Exception as e: self.stdout.write('A problem occurred while preparing your coffee...') print(e) exit(1) # Getting the output file js_file_name = coffee_name + '.js' js_output_file_name = os.path.join(JS_DIR, js_file_name) # Compare new content with the previous one if os.path.isfile(js_output_file_name): js_file = open(js_output_file_name, 'r') js_content = js_file.read() js_file.close() if compiled_js == js_content: # Content unchanged return # Content changed self.stdout.write('Serving coffee... '+js_file_name) self.contentChanged = True # => update the content of the output file js_file = open(js_output_file_name, 'w') # Write the js compiled from coffee js_file.write(compiled_js) js_file.close()
def script(fn): try: if not fn.endswith('.js'): return '' fn = 'scripts/' + fn[:-3] if os.path.exists(fn + '.js'): return file(fn + '.js', 'rb').read() try: jstat = os.stat(fn + '.cjs').st_mtime except: jstat = None try: cstat = os.stat(fn + '.coffee').st_mtime except: cstat = None if jstat == None and cstat == None: return '' elif jstat != None and cstat == None or jstat > cstat: return file(fn + '.cjs', 'rb').read() source = file(fn + '.coffee', 'rb').read() try: source = coffeescript.compile(source) except Exception, e: return 'window.location = "/_coffee_error?fn=" + encodeURIComponent(%r) + "&error=" + encodeURIComponent(%r);' % ( str(fn + '.coffee'), str(e.message)) file(fn + '.cjs', 'wb').write(source) return source
def prepare_file(file_path, build_dir): """ Move file into build folder before launching actual command (also compile coffeescript) """ logger.info("Preparing file {0}".format(file_path)) if file_path.endswith(".coffee"): logger.info("Compiling coffee script") f = open(file_path, 'r') js_content = "" coffee_content = "" for line in f: content_to_add = "{0}\n".format(line) if line.strip().startswith("#import"): js_content += content_to_add else: coffee_content += content_to_add compiled_content = coffeescript.compile(coffee_content).split('\n') js_content += '\n'.join(compiled_content[1:-2]) logger.debug(js_content) file_name = path.splitext(path.basename(file_path))[0] + ".js" build_path = path.join(build_dir, file_name) f = open(build_path, 'w') f.write(js_content) return build_path else: logger.info("Copy JS file to build dir") build_path = path.join(build_dir, path.basename(file_path)) sh.cp(file_path, build_path) return build_path
def _compile_coffee(url, compile): js_url = url.replace('.coffee', '.js') if not compile: return js_url names = url.split('/') names = names[1:] ofname = names[:-1] + [names[-1].replace('.coffee', '.js')] path = file_path(*names) ofpath = file_path(*ofname) if os.access(ofpath, os.F_OK): stat = os.stat(path) ofstat = os.stat(ofpath) if stat.st_mtime < ofstat.st_mtime: return js_url try: import coffeescript except ImportError: return url.replace('.coffee', '.js') src = open(path, 'r') dst = open(ofpath, 'w') try: dst.write(coffeescript.compile(src.read())) except Exception as e: print e return js_url
def output(self, _in, out, **kw): binary = self.coffee_bin or self.coffee_deprecated or 'coffee' if self.coffee_deprecated: import warnings warnings.warn( 'The COFFEE_PATH option of the "coffeescript" ' + 'filter has been deprecated and will be removed.' + 'Use COFFEE_BIN instead.', ImminentDeprecationWarning) args = "-sp" + ("" if self.no_bare else 'b') try: proc = subprocess.Popen( [binary, args], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=(os.name == 'nt')) except OSError: # if we don't have coffescript bin installed, use the js compiler rv = coffeescript.compile(_in.read()) out.write(rv) return stdout, stderr = proc.communicate(_in.read().encode('utf-8')) if proc.returncode != 0: raise FilterError( ('coffeescript: subprocess had error: stderr=%s, stdout=%s, ' + 'returncode=%s') % (stderr, stdout, proc.returncode)) elif stderr: print("coffeescript filter has warnings:", stderr) out.write(stdout.decode('utf-8'))
def script(fn): try: if not fn.endswith(".js"): return "" fn = "scripts/" + fn[:-3] if os.path.exists(fn + ".js"): return file(fn + ".js", "rb").read() try: jstat = os.stat(fn + ".cjs").st_mtime except: jstat = None try: cstat = os.stat(fn + ".coffee").st_mtime except: cstat = None if jstat == None and cstat == None: return "" elif jstat != None and cstat == None or jstat > cstat: return file(fn + ".cjs", "rb").read() source = file(fn + ".coffee", "rb").read() try: source = coffeescript.compile(source) except Exception, e: return ( 'window.location = "/_coffee_error?fn=" + encodeURIComponent(%r) + "&error=" + encodeURIComponent(%r);' % (str(fn + ".coffee"), str(e.message)) ) file(fn + ".cjs", "wb").write(source) return source
def compile_coffee_to_js(self, coffee_name, code): # Compilation compiled_js = None try: compiled_js = coffeescript.compile(code) except Exception as e: self.stdout.write( 'A problem occurred while preparing your coffee...') print(e) exit(1) # Getting the output file js_file_name = coffee_name + '.js' js_output_file_name = os.path.join(JS_DIR, js_file_name) # Compare new content with the previous one if os.path.isfile(js_output_file_name): js_file = open(js_output_file_name, 'r') js_content = js_file.read() js_file.close() if compiled_js == js_content: # Content unchanged return # Content changed self.stdout.write('Serving coffee... ' + js_file_name) self.contentChanged = True # => update the content of the output file js_file = open(js_output_file_name, 'w') # Write the js compiled from coffee js_file.write(compiled_js) js_file.close()
def javascripts(): # scripts = [ # 'assets/javascripts/jquery.js', # 'assets/javascripts/es5-shim.js', # 'assets/javascripts/d3.v2.min.js', # 'assets/javascripts/batman.js', # 'assets/javascripts/batman.jquery.js', # 'assets/javascripts/jquery.gridster.js', # 'assets/javascripts/jquery.leanModal.min.js', # 'assets/javascripts/dashing.coffee', # 'assets/javascripts/jquery.knob.js', # 'assets/javascripts/rickshaw.min.js', # 'assets/javascripts/application.coffee', # 'assets/javascripts/dashing.gridster.coffee' # ] scripts = ['assets/javascripts/application.js'] base_directory = os.getcwd() full_paths = [os.path.join(base_directory, script_name) for script_name in scripts] output = '' for path in full_paths: if '.coffee' in path: print('Compiling Coffee on %s ' % path) output = output + coffeescript.compile(open(path).read()) else: output = output + open(path).read() return Response(output, mimetype='application/javascript')
def quiz_static(file): def read_file(file): base_dir = os.path.dirname(inspect.getabsfile(STORE.quiz_class.wrapped_class)) path = os.path.join(base_dir, file) return open(path).read() if os.path.isfile(path) else None mime_map = [ ({'show.js', 'edit.js', 'show.coffee', 'edit.coffee'}, 'application/javascript'), ({'show.hbs', 'edit.hbs'}, 'text/x-handlebars-template'), ({'style.css'}, 'text/css') ] for files, mime in mime_map: if file in files: mimetype = mime break else: mimetype = None if not mimetype: abort(404) body = read_file(file) if body is None and file.endswith('.js'): coffee_source = read_file(file.replace('.js', '.coffee')) if coffee_source is not None: if not coffeescript: raise Exception("coffeescript module is required to compile coffeescript") body = coffeescript.compile(coffee_source) if body is None: return Response("Can't find {} file!".format(file), status=404, mimetype='text/plain') return Response(body, mimetype=mimetype)
def _convert(src, dst): source = codecs.open(src, 'r', encoding='utf-8').read() output = coffeescript.compile(source) outfile = codecs.open(dst, 'w', encoding='utf-8') outfile.write(output) outfile.close() print 'compiled "%s" into "%s"' % (src, dst)
def js(name): try: code = file('scripts/' + name + '.js').read() except: code = coffeescript.compile(file('scripts/' + name + '.coffee').read(), bare=True) with file('build/%s.js' % name, 'w') as fp: fp.write(code) return code
def main(): global files, requirements for r in requirements: add_lib(r) for f in files: add_script(f) get_imports() script = coffeescript.compile(source) print " ".join(str(libs).split()) + "\n" + " ".join( str(header + script).split())
def compile_coffee(coffee_path='scripts', output_path='static'): path = Path(app.root_path, coffee_path) out_path = Path(app.root_path, output_path) for file in path.iterdir(): if file.suffix == ('.coffee'): out_file = Path(out_path, file.stem + '.js') with file.open() as coffeefile: js_text = coffeescript.compile(coffeefile.read()) with out_file.open('w') as outfile: outfile.write(js_text)
def _(name='index'): try: return [ pyjade.simple_convert(ropen(name,'jade')) ] except IOError: pass try: return [ markdown.markdown(ropen(name,'md')) ] except IOError: pass try: return [ coffeescript.compile(ropen(name,'cs')) ] except IOError: pass try: return [ ropen(name,'html') ] except IOError: pass try: return [ ropen(name,'js') ] except IOError: pass return static_file(name, root='./static/')
def __init__(self, node, **options): if settings.configured: options.update(getattr(settings,'PYJADE',{})) filters = options.get('filters',{}) if 'markdown' not in filters: filters['markdown'] = lambda x, y: markdown(x) if COFFEESCRIPT_AVIABLE and 'coffeescript' not in filters: filters['coffeescript'] = lambda x, y: '<script>%s</script>' % coffeescript.compile(x) self.filters = filters super(Compiler, self).__init__(node, **options)
def getScript(name=''): response.content_type = 'text/javascript' path = 'web/scripts/' + name coffeePath = re.sub('.js', '.coffee', path) print("ispath: " + path + " : " + str(os.path.isfile(path))) if os.path.isfile(path): return static_file(name, 'web/scripts/') elif os.path.isfile(coffeePath): with open(coffeePath) as f: return coffeescript.compile(f.read()) abort(404)
def compile_coffee(event): file_name = get_filename(event) coffee_file = open(event.src_path, 'r').read() compiled_js = coffeescript.compile(coffee_file) compiled_path = event.src_path[:-len(file_name)] compiled_file_name = file_name.split('.') compiled_file_name = compiled_file_name[0] + '.js' css_file = open(compiled_path + compiled_file_name, 'w') css_file.write(compiled_js) css_file.close()
def javascripts(): scripts = ['assets/javascripts/application.js'] base_directory = os.getcwd() full_paths = [os.path.join(base_directory, script_name) for script_name in scripts] output = '' for path in full_paths: if '.coffee' in path: print('Compiling Coffee on %s ' % path) output = output + coffeescript.compile(open(path).read()) else: output = output + open(path).read() return Response(output, mimetype='application/javascript')
def compileStatic(self): for directory, nextDir, files in os.walk(staticDir): # Skip hidden directories if '/.' in directory: continue currentDir = os.path.join(outputDir, directory) if os.path.exists(currentDir) == False: os.mkdir(currentDir) for file in files: # Skip hidden files if file[0] == '.': continue source = os.path.join(directory, file) if file.endswith('.sass') or file.endswith('.scss'): name = file if file.endswith('.sass'): name = name.replace('.sass', '.css') elif file.endswith('.scss'): name = name.replace('.scss', '.css') destination = os.path.join(currentDir, name) if self.shouldCompile(source, destination): print('Compiling:', source) data = sass.compile(string=open(source, 'r').read()) open(destination, 'w+').write(data) os.chmod(destination, 0o644) elif file.endswith('.coffee'): name = file.replace('.coffee', '.js') destination = os.path.join(currentDir, name) if self.shouldCompile(source, destination): print('Compiling:', source) data = coffeescript.compile(open(source, 'r').read()) open(destination, 'w+').write(data) os.chmod(destination, 0o644) else: destination = os.path.join(currentDir, file) if self.shouldCompile(source, destination): print('Copying:', source) shutil.copy(source, destination) os.chmod(destination, 0o644)
def _coffee(file,root): source_path = root + "/" + file destination_directory = "static/js/" + root.replace("templates/","") destination_path = destination_directory + "/" + file.replace(".coffee",".js") # Create directories if they don't exist if not os.path.exists(destination_directory): os.makedirs(destination_directory) source_data = codecs.open(source_path,"r",encoding="utf-8").read() compiled_data = coffeescript.compile(source_data) destination_data = codecs.open(destination_path,"w",encoding="utf-8") destination_data.write(compiled_data) destination_data.close()
def compile_asset(asset_path): relative_path, absolute_path = get_filesystem_paths(asset_path) with current_app.open_resource(relative_path) as fp: file_contents = fp.read() if asset_path.endswith(".styl"): content = stylus_compiler.compile(file_contents) content_type = "text/css" elif asset_path.endswith(".coffee"): content = coffeescript.compile(file_contents) content_type = "application/javascript" else: content = file_contents content_tuple = mimetypes.guess_type(asset_path) content_type = content_tuple[0] or "text/plain" fingerprint = hashlib.md5(content.encode("utf-8")).hexdigest() last_modified = path.getmtime(absolute_path) return CompiledAsset(content, fingerprint, last_modified, content_type)
def coffee_compile(src, dst_dir, site): dst = os.path.join(dst_dir, os.path.basename(src)) dst = os.path.splitext(dst)[0] + '.js' if not has_extensions(src, '.coffee'): return False if not site['force'] and is_uptodate(src, dst): return False try: in_text = read_text(src) out_text = coffeescript.compile(in_text) if os.path.isfile(out_text): os.remove(out_text) write_text(dst, out_text) logger.info('compiled .coffee file: "{0}" -> "{1}"'.format(src, dst)) except Exception, e: logger.error('coffeescript:in file "{0}"'.format(src)) logger.error('coffeescript:' + str(e))
def plugins(): seer = SeerProxy2() result = [] for ptype, plugins in seer.plugins.items(): for name, plugin in plugins.items(): for requirement, cs in plugin.coffeescript(): result.append('(function(plugin){') try: result.append(coffeescript.compile(cs, True)) except Exception, e: print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" print "COFFEE SCRIPT ERROR" print e print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" result.append('}).call(require(%r), require("lib/plugin"));\n' % requirement)
def coffee_encode(d): # 'action' encodes action names in a way python can receive it coffee = """ action = (s)->'+action|'+s+'|o+' subst = (s)->'+o post|'+s+'|o+' a = action ps = subst u=%s return u""" % d #print('>COFEEE>\n',coffee) js = coffeescript.compile(coffee) #print('>JS>\n',js) obj = js2py.eval_js(js) d = obj.to_dict() s = str(obj) #print(s) #d = json.loads(s.replace('\'','\"')) return d
def plugins(): useCache = False if os.path.exists('./cached.js'): cacheTime = os.path.getmtime('./cached.js') useCache = True for ptype, plugins in util.all_plugins().items(): for name, plugin in plugins.items(): stem = plugin.__name__.split('.')[-1] plugin_path = __import__(plugin.__module__).__file__ s = plugin_path.split('/') plugin_path = plugin_path[0:len(plugin_path)-len(s[-1])] #pull of the filename plugin_path = plugin_path + "plugins/"+stem+"/cs/"+stem #add the plugin name mpath = plugin_path+"Inspection.coffee" if os.path.exists(mpath): plugTime = os.path.getmtime(mpath) if plugTime > cacheTime: useCache = False if not useCache: result = [] for ptype, plugins in util.all_plugins().items(): for name, plugin in plugins.items(): #print plugin.__name__, name if 'coffeescript' in dir(plugin): for requirement, cs in plugin.coffeescript(): #result.append('(function(plugin){') pluginType = requirement.split('/')[1] if True: result.append("window.require.define({{\"plugins/{0}/{1}\": function(exports, require, module) {{(function() {{".format(pluginType,name)) try: result.append(coffeescript.compile(cs, True)) except Exception, e: print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" print "COFFEE SCRIPT ERROR" print e print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" #result.append('}).call(require(%r), require("lib/plugin"));\n' % requirement) result.append("}).call(this);}});") js = "\n".join(result) f = open('./cached.js', 'w') log.info('Writing new javascript cache') f.write(js)
def compile(self): if not os.path.exists(self.OUTPUT_DIR): os.mkdir(self.OUTPUT_DIR) for root, dirnames, filenames in os.walk("./"): for dirname in dirnames: for filename in glob(os.path.join(root, dirname, "*.coffee")): file = open(filename, "r") basename = os.path.basename(filename) filename = filename.replace(self.dir, self.OUTPUT_DIR) dirname = os.path.dirname(filename) if not os.path.exists(dirname): os.mkdir(dirname) print(filename) output = open(os.path.join(os.path.splitext(filename)[0] + ".js"), "w") output.write(coffeescript.compile(file.read()))
def add_snippet(self, name, coffee): #logging.debug("Trying to insert this gloubiboulga [%s]" % coffee) logging.debug("Creating a face Hubot context...") def require(module_name): logging.debug("Trying to load " + module_name) module = HubotModule() cx = self.rt.new_context() cx.add_global("module", module) cx.add_global("process", self.process) cx.add_global("require", require) cx.add_global("JSON", JSONStub()) logging.debug("Compiling coffeescript...") js = coffeescript.compile(coffee, bare=True) nummed_js = numerotatedJS(js) self.js_cache[name] = nummed_js logging.debug("Translated JS:\n" + nummed_js) logging.debug("Executing Hubot script...") cx.execute(code = js, filename = name) module.exports(self) # triggers the listening callbacks
def add_snippet(self, name, coffee): #logging.debug("Trying to insert this gloubiboulga [%s]" % coffee) logging.debug("Creating a face Hubot context...") def require(module_name): logging.debug("Trying to load " + module_name) module = HubotModule() cx = self.rt.new_context() cx.add_global("module", module) cx.add_global("process", self.process) cx.add_global("require", require) cx.add_global("JSON", JSONStub()) logging.debug("Compiling coffeescript...") js = coffeescript.compile(coffee, bare=True) nummed_js = numerotatedJS(js) self.js_cache[name] = nummed_js logging.debug("Translated JS:\n" + nummed_js) logging.debug("Executing Hubot script...") cx.execute(code=js, filename=name) module.exports(self) # triggers the listening callbacks
def _(name='index'): try: return [pyjade.simple_convert(ropen(name, 'jade'))] except IOError: pass try: return [markdown.markdown(ropen(name, 'md'))] except IOError: pass try: return [coffeescript.compile(ropen(name, 'cs'))] except IOError: pass try: return [ropen(name, 'html')] except IOError: pass try: return [ropen(name, 'js')] except IOError: pass return static_file(name, root='./static/')
def get(self): timer = Timer() times = dict() # render template into coffeescript cs = self.template_string(self.args) times['Rendering template'] = timer.lap() if cs in self.CACHE: js = self.CACHE[cs] times['Retrieving from cache'] = timer.lap() else: # then compile to javascript js = coffeescript.compile(cs) times['Compiling coffeescript'] = timer.lap() self.CACHE[cs] = js # and we're done! self.write(js) times['Writing JS to wire'] = timer.lap() self.finish('/* finished! time stats: \n' + pretty_json(times) + '*/')
def quiz_static(file): def read_file(file): base_dir = os.path.dirname( inspect.getabsfile(STORE.quiz_class.wrapped_class)) path = os.path.join(base_dir, file) return open(path).read() if os.path.isfile(path) else None mime_map = [({'show.js', 'edit.js', 'show.coffee', 'edit.coffee'}, 'application/javascript'), ({'show.hbs', 'edit.hbs'}, 'text/x-handlebars-template'), ({'style.css'}, 'text/css')] for files, mime in mime_map: if file in files: mimetype = mime break else: mimetype = None if not mimetype: abort(404) body = read_file(file) if body is None and file.endswith('.js'): coffee_source = read_file(file.replace('.js', '.coffee')) if coffee_source is not None: if not coffeescript: raise Exception( "coffeescript module is required to compile coffeescript") body = coffeescript.compile(coffee_source) if body is None: return Response("Can't find {} file!".format(file), status=404, mimetype='text/plain') return Response(body, mimetype=mimetype)
def coffee(path): """ Template tag to compile coffeescript files if needed and return its url. """ filename = 'js/%s.js' % os.path.splitext(os.path.basename(path))[0] coffee_file = os.path.join(STATIC_ROOT, path) js_file = os.path.join(STATIC_ROOT, filename) if not os.path.isfile(js_file): js_mtime = -1 else: js_mtime = os.path.getmtime(js_file) if os.path.getmtime(coffee_file) >= js_mtime and settings.COFFEE_REBUILD: try: compiled = coffeescript.compile(open(coffee_file).read()) with open(js_file, 'w') as f: f.write(compiled) logger.info('Compiled coffee script file: %s' % coffee_file) except Exception as e: logger.debug("Can't compile coffee script file: %s" % coffee) logger.debug(e) return static(filename)
def coffeescript_filter(x,y): return '<script>%s</script>' % coffeescript.compile(x)
import coffeescript, generator, glob, os, os.path, shutil if not os.path.exists('build'): os.makedirs('build') generator.build() for fn in glob.glob('scripts/*.js'): bn = os.path.basename(fn) shutil.copyfile(fn, 'build/' + bn) for fn in glob.glob('scripts/*.coffee'): bn = os.path.basename(fn) with file('build/' + bn, 'w') as fp: fp.write(coffeescript.compile(file(fn, 'r').read(), bare=True)) for fn in glob.glob('static/*'): bn = os.path.basename(fn) shutil.copyfile(fn, 'build/' + bn)
def save(self, force_insert=False, force_update=False, using=False): js = coffeescript.compile(self.coffee_input) compiler = Scss() css = compiler.compile(self.scss_input) #self.html_output = markdown.markdown(self.content) super(Template, self).save(force_insert, force_update)
def prepare(): if os.path.exists(app.static_folder): rmtree(app.static_folder) os.makedirs(app.static_folder) compiler = scss.Scss( scss_opts={'style': 'compressed' if not app.debug else None}, search_paths=[os.path.join(os.getcwd(), 'styles')]) # Compile styles (scss) d = os.walk('styles') for f in list(d)[0][2]: if os.path.splitext(f)[1] == ".scss": with open(os.path.join('styles', f)) as r: output = compiler.compile(r.read()) parts = f.rsplit('.') css = '.'.join(parts[:-1]) + ".css" with open(os.path.join(app.static_folder, css), "w") as w: w.write(output) w.flush() else: copyfile(os.path.join('styles', f), os.path.join(app.static_folder, f)) # Compile scripts (coffeescript) d = os.walk('scripts') for f in list(d)[0][2]: outputpath = os.path.join(app.static_folder, os.path.basename(f)) inputpath = os.path.join('scripts', f) if os.path.splitext(f)[1] == ".js": copyfile(inputpath, outputpath) elif os.path.splitext(f)[1] == ".manifest": with open(inputpath) as r: manifest = r.read().split('\n') javascript = '' for script in manifest: script = script.strip(' ') if script == '' or script.startswith('#'): continue bare = False if script.startswith('bare: '): bare = True script = script[6:] with open(os.path.join('scripts', script)) as r: coffee = r.read().replace("{{ support_mail }}", _cfg('support-mail')) if script.endswith('.js'): javascript += coffee # straight up copy else: javascript += coffeescript.compile(coffee, bare=bare) output = '.'.join(f.rsplit('.')[:-1]) + '.js' # TODO: Bug the slimit guys to support python 3 #if not app.debug: # javascript = minify(javascript) with open(os.path.join(app.static_folder, output), "w") as w: w.write(javascript) w.flush() d = os.walk('images') for f in list(d)[0][2]: outputpath = os.path.join(app.static_folder, os.path.basename(f)) inputpath = os.path.join('images', f) copyfile(inputpath, outputpath)
def prepare(): if os.path.exists(app.static_folder): rmtree(app.static_folder) os.makedirs(app.static_folder) compiler = scss.Scss(scss_opts = { 'style': 'compressed' if not app.debug else None }, search_paths=[ os.path.join(os.getcwd(), 'styles') ]) # Compile styles (scss) d = os.walk('styles') for f in list(d)[0][2]: if os.path.splitext(f)[1] == ".scss": with open(os.path.join('styles', f)) as r: output = compiler.compile(r.read()) parts = f.rsplit('.') css = '.'.join(parts[:-1]) + ".css" with open(os.path.join(app.static_folder, css), "w") as w: w.write(output) w.flush() else: copyfile(os.path.join('styles', f), os.path.join(app.static_folder, f)) # Compile scripts (coffeescript) d = os.walk('scripts') for f in list(d)[0][2]: outputpath = os.path.join(app.static_folder, os.path.basename(f)) inputpath = os.path.join('scripts', f) if os.path.splitext(f)[1] == ".js": copyfile(inputpath, outputpath) elif os.path.splitext(f)[1] == ".manifest": with open(inputpath) as r: manifest = r.read().split('\n') javascript = '' for script in manifest: script = script.strip(' ') if script == '' or script.startswith('#'): continue bare = False if script.startswith('bare: '): bare = True script = script[6:] with open(os.path.join('scripts', script)) as r: coffee = r.read() if script.endswith('.js'): javascript += coffee # straight up copy else: javascript += coffeescript.compile(coffee, bare=bare) output = '.'.join(f.rsplit('.')[:-1]) + '.js' # TODO: Bug the slimit guys to support python 3 #if not app.debug: # javascript = minify(javascript) with open(os.path.join(app.static_folder, output), "w") as w: w.write(javascript) w.flush() d = os.walk('images') for f in list(d)[0][2]: outputpath = os.path.join(app.static_folder, os.path.basename(f)) inputpath = os.path.join('images', f) copyfile(inputpath, outputpath)
def compile_one(self, filename): return coffeescript.compile(open(filename, 'r').read())
def save(self, force_insert=False, force_update=False, using=False): self.javascript_output = coffeescript.compile(self.coffee_input) compiler = Scss() self.css_output = compiler.compile(self.scss_input) self.content_html = markdown.markdown(self.content) super(Content, self).save(force_insert, force_update)
def prepare(): path = tempfile.mkdtemp() compiler = scss.Scss( scss_opts={'style': 'compressed' if not app.debug else None}) # Compile styles (scss) d = os.walk('styles') for f in list(d)[0][2]: if extension(f) == "scss": print("[scss] %s" % f) with open(os.path.join('styles', f)) as r: output = compiler.compile(r.read()) parts = f.rsplit('.') css = '.'.join(parts[:-1]) + ".css" with open(os.path.join(path, css), "w") as w: w.write(output) w.flush() # Compile scripts (coffeescript) d = os.walk('scripts') preprocess = ['scripts/mediacrush.js'] for f in list(d)[0][2]: outputpath = os.path.join(path, os.path.basename(f)) inputpath = os.path.join('scripts', f) if extension(f) == "js": if inputpath in preprocess: with open(inputpath, "rb") as r: output = r.read().decode("utf-8") output = output.replace("{{ protocol }}", _cfg("protocol")) output = output.replace("{{ domain }}", _cfg("domain")) with open(outputpath, "wb") as w: w.write(output.encode("utf-8")) w.flush() else: copyfile(inputpath, outputpath) elif extension(f) == "manifest": with open(inputpath, "rb") as r: manifest = r.read().decode("utf-8").split('\n') javascript = '' for script in manifest: script = script.strip(' ') if script == '' or script.startswith('#'): continue bare = False if script.startswith('bare: '): bare = True script = script[6:] print("[coffee] %s" % script) with open(os.path.join('scripts', script)) as r: coffee = r.read() if script.endswith('.js'): javascript += coffee # straight up copy else: javascript += coffeescript.compile(coffee, bare=bare) output = '.'.join(f.rsplit('.')[:-1]) + '.js' if not app.debug: # FIXME https://github.com/rspivak/slimit/issues/64 if sys.version_info.major == 3: sys.stderr.write( "WARNING: Minifying is not supported on Python 3 yet\n" ) else: javascript = minify(javascript) with open(os.path.join(path, output), "wb") as w: w.write(javascript.encode("utf-8")) w.flush() if os.path.exists(app.static_folder): rmtree(app.static_folder) os.makedirs(app.static_folder) d = os.walk(path) for f in list(d)[0][2]: inputpath = os.path.join(path, os.path.basename(f)) outputpath = os.path.join(app.static_folder, f) copyfile(inputpath, outputpath) d = os.walk('images') for f in list(d)[0][2]: outputpath = os.path.join(app.static_folder, os.path.basename(f)) inputpath = os.path.join('images', f) copyfile(inputpath, outputpath)
def prepare(): if os.path.exists(app.static_folder): rmtree(app.static_folder) os.makedirs(app.static_folder) compiler = scss.Scss( scss_opts={'style': 'compressed' if not app.debug else None}) # Compile styles (scss) d = os.walk('styles') for f in list(d)[0][2]: if extension(f) == "scss": with open(os.path.join('styles', f)) as r: output = compiler.compile(r.read()) parts = f.rsplit('.') css = '.'.join(parts[:-1]) + ".css" with open(os.path.join(app.static_folder, css), "w") as w: w.write(output) w.flush() # Compile scripts (coffeescript) d = os.walk('scripts') preprocess = ['scripts/mediacrush.js'] for f in list(d)[0][2]: outputpath = os.path.join(app.static_folder, os.path.basename(f)) inputpath = os.path.join('scripts', f) if extension(f) == "js": if inputpath in preprocess: with open(inputpath) as r: output = r.read().decode("utf-8") output = output.replace("{{ protocol }}", _cfg("protocol")) output = output.replace("{{ domain }}", _cfg("domain")) with open(outputpath, "w") as w: w.write(output.encode("utf-8")) w.flush() else: copyfile(inputpath, outputpath) elif extension(f) == "manifest": with open(inputpath) as r: manifest = r.read().decode("utf-8").split('\n') javascript = '' for script in manifest: script = script.strip(' ') if script == '' or script.startswith('#'): continue bare = False if script.startswith('bare: '): bare = True script = script[6:] with open(os.path.join('scripts', script)) as r: coffee = r.read() if script.endswith('.js'): javascript += coffee # straight up copy else: javascript += coffeescript.compile(coffee, bare=bare) output = '.'.join(f.rsplit('.')[:-1]) + '.js' if not app.debug: javascript = minify(javascript) with open(os.path.join(app.static_folder, output), "w") as w: w.write(javascript.encode("utf-8")) w.flush() d = os.walk('images') for f in list(d)[0][2]: outputpath = os.path.join(app.static_folder, os.path.basename(f)) inputpath = os.path.join('images', f) copyfile(inputpath, outputpath)
def py_coffeescript(_in, out, **kw): out.write(coffeescript.compile(_in.read()))
def coffeescript_filter(text, ast): return coffeescript.compile(text)
def coffee(fn): return coffeescript.compile(file("scripts/" + fn + ".coffee", "r").read(), bare=True)
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()
def coffeec(name): bname, ext = path.splitext(name) coffee_code = get(name) js_code = coff.compile(coffee_code) dest = (bname + '.js') put(dest, js_code)
def coffeescript_filter(x, y): return '<script>%s</script>' % coffeescript.compile(x)
def coffee(fn): return coffeescript.compile(file('scripts/' + fn + '.coffee', 'r').read(), bare=True)