def load(self): self.last_load = time.time() self._load_custom_mod() self._call_custom_hook('pre_load') self.html_renderer = AshesEnv(paths=[self.theme_path]) self.html_renderer.load_all() self.md_renderer = AshesEnv(paths=[self.theme_path], exts=['md'], keep_whitespace=False) self.md_renderer.autoescape_filter = '' self.md_renderer.load_all() entries_path = self.paths['entries_path'] entry_paths = [] for entry_path in iter_find_files(entries_path, ENTRY_PATS): entry_paths.append(entry_path) entry_paths.sort() for ep in entry_paths: with chlog.info('entry load') as rec: try: entry = self._entry_type.from_path(ep) rec['entry_title'] = entry.title rec['entry_length'] = round(entry.get_reading_time(), 1) except IOError: rec.exception('unopenable entry path: {}', ep) continue except: rec['entry_path'] = ep rec.exception( 'entry {entry_path} load error: {exc_message}') continue else: rec.success('entry loaded:' ' {entry_title} ({entry_length}m)') if entry.is_draft: self.draft_entries.append(entry) elif entry.is_special: self.special_entries.append(entry) else: self.entries.append(entry) # Sorting the EntryLists self.entries.sort() # sorting drafts/special pages doesn't do much self.draft_entries.sort(key=lambda e: os.path.getmtime(e.source_path)) self.special_entries.sort() self._rebuild_tag_map() for i, entry in enumerate(self.entries, start=1): start_next = max(0, i - NEXT_ENTRY_COUNT) entry.next_entries = self.entries[start_next:i - 1][::-1] entry.prev_entries = self.entries[i:i + PREV_ENTRY_COUNT] self._call_custom_hook('post_load')
def get_test_results(test_cases, raise_on=None): env = AshesEnv(keep_whitespace=False) ret = [] for tc in test_cases: env.register(Template(tc.name, tc.template, env=env, lazy=True)) for tc in test_cases: raise_exc = (tc.name == raise_on) ret.append(tc.get_test_result(env, raise_exc=raise_exc)) return ret
def directory(cmgs, env, title=DIR_TITLE, formats=None): """ Generate HTML directory of multiple CMGroups and write to file. """ # TODO: doc items = [{'cmg_id': cmg.cmg_id, 'name': cmg.name, 'notes': get_notes(cmg)} for cmg in cmgs] formats = formats or [] context = {'title': title, 'items': items, 'formats': formats} path = pjoin(env.results_path, 'index.html') templater = AshesEnv([TEMPLATES_DIR]) html = templater.render('directory.html', context) with open(path, 'w') as html_file: html_file.write(html)
def cids_to_html(cids, path, title='PubChem images', info=None, size=500): """ Generate HTML file displaying PubChem structures and CMGroup info. """ # TODO: Options to add links to JSON, CSV, Excel files. # Something like: formats=['csv', 'json', 'excel'] if info: info_list = info_to_context(info) else: info_list = [] context = {'size': size, 'title': title, 'info': info_list, 'items': [{'cid': cid, 'image': pc_img(cid, size=size)} for cid in cids]} templater = AshesEnv([TEMPLATES_DIR]) html = templater.render('display_cids.html', context) with open(path, 'w') as html_file: html_file.write(html)
def __init__(self): super().__init__() self.export = {'router': None, 'model': None} @cp.model() class ExportApis: node = cp.boolean(1, [cp.input, cp.optional], "生成 logic.node 使用的api") php = cp.boolean(2, [cp.input, cp.optional], "生成 logic.php 使用的api") h5g = cp.boolean(3, [cp.input, cp.optional], "生成 game.h5 游戏使用api") vue = cp.boolean(4, [cp.input, cp.optional], "生成 vue 项目中使用的api") # 预先准备渲染模板 DIR_TEMPLATES = os.path.dirname(__file__) TEMPLATES = AshesEnv([DIR_TEMPLATES]) class Router(r.IRouter): def __init__(self): super().__init__() self._cfg = None self.action = 'api' self._page = get_file_content( url.expand("~/nnt/server/apidoc/apidoc.volt")) @r.action(Null, [r.expose], "文档") def doc(self, trans: Transaction): srv: IRouterable = trans.server if len(srv.routers): # 收集routers的信息
def render(plist, pdir, pfile): "generate the list markdown from the yaml listing" normalize(pfile=pfile, plist=plist) topic_map = plist.get_projects_by_type('topic') topic_toc_text = format_tag_toc(topic_map) projects_by_topic = format_all_categories(topic_map) plat_map = plist.get_projects_by_type('platform') plat_toc_text = format_tag_toc(plat_map) projects_by_plat = format_all_categories(plat_map) context = { 'TOPIC_TOC': topic_toc_text, 'TOPIC_TEXT': projects_by_topic, 'PLATFORM_TOC': plat_toc_text, 'PLATFORM_TEXT': projects_by_plat, 'TOTAL_COUNT': len(plist.project_list) } templates_path = pdir + '/templates/' if not os.path.isdir(templates_path): raise APACLIError('expected "templates" directory at %r' % templates_path) for filename in iter_find_files(templates_path, '*.tmpl.md'): tmpl_text = open(filename).read() target_filename = os.path.split(filename)[1].replace('.tmpl', '') output_text = tmpl_text.format(**context) with atomic_save(pdir + '/' + target_filename) as f: f.write(output_text.encode('utf8')) feed_tmpl_path = templates_path + '/atom.xml' if os.path.exists(feed_tmpl_path): def _stderr_log_func(level, name, message): import sys sys.stderr.write('%s - %s - %s\n' % (level.upper(), name, message)) sys.stderr.flush() ashes_env = AshesEnv([templates_path], log_func=_stderr_log_func) proj_dict_list = [] for proj in plist.project_list: cur = proj.to_dict() cur['name_slug'] = proj.name_slug cur['date_added_utc'] = proj.date_added.isoformat() + 'Z' cur['urls'] = get_url_list(proj) proj_dict_list.append(cur) cur_dt = datetime.datetime.utcnow().replace( microsecond=0).isoformat() + 'Z' res = ashes_env.render( 'atom.xml', { 'projects': sorted(proj_dict_list, key=lambda x: x['date_added'], reverse=True), 'last_generated_utc': cur_dt }) with atomic_save(pdir + '/atom.xml') as f: f.write(res.encode('utf8')) return
""" ESLint validation plugin for TextMate """ from __future__ import print_function import os import sys import time import re import subprocess import validator from ashes import AshesEnv THIS_DIR = os.path.abspath(os.path.dirname(__file__)) BASE_PATH = 'tm-file://' + os.environ['TM_BUNDLE_SUPPORT'] ASHES_ENV = AshesEnv([os.path.join(THIS_DIR, 'templates')]) IGNORE_ISSUES = ['^File ignored because of a matching ignore pattern'] def get_cwd(): """ What directory should we cd to before running eslint? """ cwd = os.environ.get('TM_PROJECT_DIRECTORY', None) if not cwd: cwd = os.environ.get('TM_DIRECTORY', None) return cwd def should_ignore(issue_reason): """ Given the reason text for an issue, should we ignore it? """ for rx in IGNORE_ISSUES: if re.match(rx, issue_reason):
STATIC_PATH = PROJECT_PATH + '/static/' RUN_UUID = uuid.uuid4() UPDATED_DT_FORMAT = '%Y-%m-%d %H:%M:%S' DEBUG = False DEFAULT_CARD = 'https://upload.wikimedia.org/wikipedia/commons/8/81/WikiSplat.png' # these paths are relative to the campaign directory STATE_FULL_PATH_TMPL = '/data/%Y%m/state_full_%Y%m%d_%H%M%S.json.gz' STATE_PATH_TMPL = '/data/%Y%m/state_%Y%m%d_%H%M%S.json' STATE_FULL_FN_GLOB = 'state_full_*.json.gz' STATE_FN_GLOB = 'state_*.json' ASHES_ENV = AshesEnv(TEMPLATE_PATH, filters={'percentage': lambda n: round(n * 100, 2)}) ASHES_ENV.load_all() def to_unicode(obj): try: return unicode(obj) except UnicodeDecodeError: return unicode(obj, encoding='utf8') @attr.s class PTArticle(object): lang = attr.ib() title = attr.ib() timestamp = attr.ib()