本文整理汇总了Python中nikola.utils.get_theme_path函数的典型用法代码示例。如果您正苦于以下问题:Python get_theme_path函数的具体用法?Python get_theme_path怎么用?Python get_theme_path使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_theme_path函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: gen_tasks
def gen_tasks(self):
"""Generate CSS out of LESS sources."""
kw = {
'cache_folder': self.site.config['CACHE_FOLDER'],
'themes': self.site.THEMES,
}
# Find where in the theme chain we define the LESS targets
# There can be many *.less in the folder, but we only will build
# the ones listed in less/targets
targets_path = utils.get_asset_path(os.path.join(self.sources_folder, "targets"), self.site.THEMES)
try:
with codecs.open(targets_path, "rb", "utf-8") as inf:
targets = [x.strip() for x in inf.readlines()]
except Exception:
targets = []
for theme_name in kw['themes']:
src = os.path.join(utils.get_theme_path(theme_name), self.sources_folder)
for task in utils.copy_tree(src, os.path.join(kw['cache_folder'], self.sources_folder)):
task['basename'] = 'prepare_less_sources'
yield task
# Build targets and write CSS files
base_path = utils.get_theme_path(self.site.THEMES[0])
dst_dir = os.path.join(self.site.config['OUTPUT_FOLDER'], 'assets', 'css')
# Make everything depend on all sources, rough but enough
deps = glob.glob(os.path.join(
base_path,
self.sources_folder,
"*{0}".format(self.sources_ext)))
def compile_target(target, dst):
utils.makedirs(dst_dir)
src = os.path.join(kw['cache_folder'], self.sources_folder, target)
try:
compiled = subprocess.check_output([self.compiler_name, src])
except OSError:
utils.req_missing([self.compiler_name],
'build LESS files (and use this theme)',
False, False)
with open(dst, "wb+") as outf:
outf.write(compiled)
yield self.group_task()
for target in targets:
dst = os.path.join(dst_dir, target.replace(self.sources_ext, ".css"))
yield {
'basename': self.name,
'name': dst,
'targets': [dst],
'file_dep': deps,
'task_dep': ['prepare_less_sources'],
'actions': ((compile_target, [target, dst]), ),
'uptodate': [utils.config_changed(kw)],
'clean': True
}
示例2: _execute
def _execute(self, options, args):
"""Install theme into current site."""
listing = options['list']
url = options['url']
if args:
name = args[0]
else:
name = None
if options['getpath'] and name:
path = utils.get_theme_path(name)
if path:
print(path)
else:
print('not installed')
return 0
if name is None and not listing:
LOGGER.error("This command needs either a theme name or the -l option.")
return False
try:
data = requests.get(url).json()
except requests.exceptions.SSLError:
LOGGER.warning("SSL error, using http instead of https (press ^C to abort)")
time.sleep(1)
url = url.replace('https', 'http', 1)
data = requests.get(url).json()
if listing:
print("Themes:")
print("-------")
for theme in sorted(data.keys()):
print(theme)
return True
else:
# `name` may be modified by the while loop.
origname = name
installstatus = self.do_install(name, data)
# See if the theme's parent is available. If not, install it
while True:
parent_name = utils.get_parent_theme_name(name)
if parent_name is None:
break
try:
utils.get_theme_path(parent_name)
break
except: # Not available
self.do_install(parent_name, data)
name = parent_name
if installstatus:
LOGGER.notice('Remember to set THEME="{0}" in conf.py to use this theme.'.format(origname))
示例3: gen_tasks
def gen_tasks(self):
"""Generate CSS out of LESS sources."""
kw = {"cache_folder": self.site.config["CACHE_FOLDER"], "themes": self.site.THEMES}
# Find where in the theme chain we define the LESS targets
# There can be many *.less in the folder, but we only will build
# the ones listed in less/targets
targets_path = utils.get_asset_path(os.path.join(self.sources_folder, "targets"), self.site.THEMES)
try:
with codecs.open(targets_path, "rb", "utf-8") as inf:
targets = [x.strip() for x in inf.readlines()]
except Exception:
targets = []
for theme_name in kw["themes"]:
src = os.path.join(utils.get_theme_path(theme_name), self.sources_folder)
for task in utils.copy_tree(src, os.path.join(kw["cache_folder"], self.sources_folder)):
# task['basename'] = self.name
yield task
# Build targets and write CSS files
base_path = utils.get_theme_path(self.site.THEMES[0])
dst_dir = os.path.join(self.site.config["OUTPUT_FOLDER"], "assets", "css")
# Make everything depend on all sources, rough but enough
deps = glob.glob(os.path.join(base_path, self.sources_folder, "*{0}".format(self.sources_ext)))
def compile_target(target, dst):
if not os.path.isdir(dst_dir):
os.makedirs(dst_dir)
src = os.path.join(kw["cache_folder"], self.sources_folder, target)
compiled = subprocess.check_output([self.compiler_name, src])
with open(dst, "wb+") as outf:
outf.write(compiled)
for target in targets:
dst = os.path.join(dst_dir, target.replace(self.sources_ext, ".css"))
yield {
"basename": self.name,
"name": dst,
"targets": [dst],
"file_dep": deps,
"actions": ((compile_target, [target, dst]),),
"uptodate": [utils.config_changed(kw)],
"clean": True,
}
if not targets:
yield {"basename": self.name, "actions": []}
示例4: do_install
def do_install(self, name, data):
if name in data:
utils.makedirs(self.output_dir)
LOGGER.notice('Downloading: ' + data[name])
zip_file = BytesIO()
zip_file.write(requests.get(data[name]).content)
LOGGER.notice('Extracting: {0} into themes'.format(name))
utils.extract_all(zip_file)
dest_path = os.path.join('themes', name)
else:
try:
theme_path = utils.get_theme_path(name)
except:
LOGGER.error("Can't find theme " + name)
return False
utils.makedirs(self.output_dir)
dest_path = os.path.join(self.output_dir, name)
if os.path.exists(dest_path):
LOGGER.error("{0} is already installed".format(name))
return False
LOGGER.notice('Copying {0} into themes'.format(theme_path))
shutil.copytree(theme_path, dest_path)
confpypath = os.path.join(dest_path, 'conf.py.sample')
if os.path.exists(confpypath):
LOGGER.notice('This plugin has a sample config file.')
print('Contents of the conf.py.sample file:\n')
with codecs.open(confpypath, 'rb', 'utf-8') as fh:
print(indent(pygments.highlight(
fh.read(), PythonLexer(), TerminalFormatter()), 4 * ' '))
return True
示例5: generate_css
def generate_css():
# Compass compile
for theme_name in self.site.THEMES:
theme_root = os.path.abspath(utils.get_theme_path(theme_name))
compass_root = os.path.abspath(os.path.join(theme_root, 'style'))
tmp_dir = os.path.abspath(os.path.join(theme_root, '_tmp'))
if os.path.exists(compass_root):
LOGGER.notice("PYGMENTS CSS CODE")
create_code_css(self.site.config['CODE_COLOR_SCHEME'],
os.path.join(compass_root, 'css', 'code.css'))
LOGGER.notice("COMPASS COMPILE")
run('compass clean', cwd=compass_root)
run('compass compile', cwd=compass_root)
LOGGER.notice("AUTOPREFIXER")
LOGGER.notice("CWD: {}".format(theme_root))
run('autoprefixer -o _tmp/all.pre.css _tmp/all.css', cwd=theme_root)
LOGGER.notice("CSSO (CSS optimizer)")
LOGGER.notice("CWD: {}".format(theme_root))
run('csso _tmp/all.pre.css _tmp/all.min.css', cwd=theme_root)
LOGGER.notice("Move CSS to output")
css_output_dir = os.path.join(os.path.abspath(self.site.config['OUTPUT_FOLDER']), 'assets', 'css')
utils.makedirs(css_output_dir)
shutil.copy2(os.path.join(tmp_dir, 'all.min.css'), css_output_dir)
示例6: gen_tasks
def gen_tasks(self):
"""Create tasks to copy the assets of the whole theme chain.
If a file is present on two themes, use the version
from the "youngest" theme.
"""
kw = {
"themes": self.site.THEMES,
"output_folder": self.site.config['OUTPUT_FOLDER'],
"filters": self.site.config['FILTERS'],
}
flag = True
tasks = {}
for theme_name in kw['themes']:
src = os.path.join(utils.get_theme_path(theme_name), 'assets')
dst = os.path.join(kw['output_folder'], 'assets')
for task in utils.copy_tree(src, dst):
if task['name'] in tasks:
continue
tasks[task['name']] = task
task['uptodate'] = [utils.config_changed(kw)]
task['basename'] = self.name
flag = False
yield utils.apply_filters(task, kw['filters'])
if flag:
yield {
'basename': self.name,
'name': 'None',
'uptodate': [True],
'actions': [],
}
示例7: do_install
def do_install(self, name, data):
if name in data:
utils.makedirs(self.output_dir)
LOGGER.info("Downloading '{0}'".format(data[name]))
zip_file = io.BytesIO()
zip_file.write(requests.get(data[name]).content)
LOGGER.info("Extracting '{0}' into themes/".format(name))
utils.extract_all(zip_file)
dest_path = os.path.join(self.output_dir, name)
else:
dest_path = os.path.join(self.output_dir, name)
try:
theme_path = utils.get_theme_path(name)
LOGGER.error("Theme '{0}' is already installed in {1}".format(name, theme_path))
except Exception:
LOGGER.error("Can't find theme {0}".format(name))
return False
confpypath = os.path.join(dest_path, 'conf.py.sample')
if os.path.exists(confpypath):
LOGGER.notice('This theme has a sample config file. Integrate it with yours in order to make this theme work!')
print('Contents of the conf.py.sample file:\n')
with io.open(confpypath, 'r', encoding='utf-8') as fh:
if self.site.colorful:
print(utils.indent(pygments.highlight(
fh.read(), PythonLexer(), TerminalFormatter()),
4 * ' '))
else:
print(utils.indent(fh.read(), 4 * ' '))
return True
示例8: get_path
def get_path(self, name):
"""Get path for an installed theme."""
try:
path = utils.get_theme_path(name)
print(path)
except Exception:
print("not installed")
return 0
示例9: gen_tasks
def gen_tasks(self):
"""Create tasks to copy the assets of the whole theme chain.
If a file is present on two themes, use the version
from the "youngest" theme.
"""
kw = {
"themes": self.site.THEMES,
"output_folder": self.site.config['OUTPUT_FOLDER'],
"filters": self.site.config['FILTERS'],
"code_color_scheme": self.site.config['CODE_COLOR_SCHEME'],
}
flag = True
has_code_css = False
tasks = {}
code_css_path = os.path.join(kw['output_folder'], 'assets', 'css', 'code.css')
for theme_name in kw['themes']:
src = os.path.join(utils.get_theme_path(theme_name), 'assets')
dst = os.path.join(kw['output_folder'], 'assets')
for task in utils.copy_tree(src, dst):
if task['name'] in tasks:
continue
if task['targets'][0] == code_css_path:
has_code_css = True
tasks[task['name']] = task
task['uptodate'] = [utils.config_changed(kw)]
task['basename'] = self.name
flag = False
yield utils.apply_filters(task, kw['filters'])
if flag:
yield {
'basename': self.name,
'name': 'None',
'uptodate': [True],
'actions': [],
}
if not has_code_css: # Generate it
def create_code_css():
from pygments.formatters import get_formatter_by_name
formatter = get_formatter_by_name('html', style=kw["code_color_scheme"])
utils.makedirs(os.path.dirname(code_css_path))
with codecs.open(code_css_path, 'wb+', 'utf8') as outf:
outf.write(formatter.get_style_defs('.code'))
outf.write("table.codetable { width: 100%;} td.linenos {text-align: right; width: 4em;}")
task = {
'basename': self.name,
'name': code_css_path,
'targets': [code_css_path],
'uptodate': [utils.config_changed(kw)],
'actions': [(create_code_css, [])],
'clean': True,
}
yield utils.apply_filters(task, kw['filters'])
示例10: _execute
def _execute(self, options, args):
"""Install theme into current site."""
listing = options['list']
url = options['url']
if args:
name = args[0]
else:
name = None
if options['getpath'] and name:
path = utils.get_theme_path(name)
if path:
print(path)
else:
print('not installed')
exit(0)
if name is None and not listing:
LOGGER.error("This command needs either a theme name or the -l option.")
return False
data = requests.get(url).text
data = json.loads(data)
if listing:
print("Themes:")
print("-------")
for theme in sorted(data.keys()):
print(theme)
return True
else:
# `name` may be modified by the while loop.
origname = name
installstatus = self.do_install(name, data)
# See if the theme's parent is available. If not, install it
while True:
parent_name = utils.get_parent_theme_name(name)
if parent_name is None:
break
try:
utils.get_theme_path(parent_name)
break
except: # Not available
self.do_install(parent_name, data)
name = parent_name
if installstatus:
LOGGER.notice('Remember to set THEME="{0}" in conf.py to use this theme.'.format(origname))
示例11: do_install_deps
def do_install_deps(self, url, name):
"""Install themes and their dependencies."""
data = self.get_json(url)
# `name` may be modified by the while loop.
origname = name
installstatus = self.do_install(name, data)
# See if the theme's parent is available. If not, install it
while True:
parent_name = utils.get_parent_theme_name(name)
if parent_name is None:
break
try:
utils.get_theme_path(parent_name)
break
except: # Not available
self.do_install(parent_name, data)
name = parent_name
if installstatus:
LOGGER.notice('Remember to set THEME="{0}" in conf.py to use this theme.'.format(origname))
示例12: gen_tasks
def gen_tasks(self):
"""Create tasks to copy the assets of the whole theme chain.
If a file is present on two themes, use the version
from the "youngest" theme.
"""
kw = {
"themes": self.site.THEMES,
"output_folder": self.site.config["OUTPUT_FOLDER"],
"filters": self.site.config["FILTERS"],
"code_color_scheme": self.site.config["CODE_COLOR_SCHEME"],
}
has_code_css = False
tasks = {}
code_css_path = os.path.join(kw["output_folder"], "assets", "css", "code.css")
yield self.group_task()
for theme_name in kw["themes"]:
src = os.path.join(utils.get_theme_path(theme_name), "assets")
dst = os.path.join(kw["output_folder"], "assets")
for task in utils.copy_tree(src, dst):
if task["name"] in tasks:
continue
if task["targets"][0] == code_css_path:
has_code_css = True
tasks[task["name"]] = task
task["uptodate"] = [utils.config_changed(kw)]
task["basename"] = self.name
yield utils.apply_filters(task, kw["filters"])
if not has_code_css: # Generate it
def create_code_css():
from pygments.formatters import get_formatter_by_name
formatter = get_formatter_by_name("html", style=kw["code_color_scheme"])
utils.makedirs(os.path.dirname(code_css_path))
with codecs.open(code_css_path, "wb+", "utf8") as outf:
outf.write(formatter.get_style_defs(["pre.code", "div.code pre"]))
outf.write("\ntable.codetable { width: 100%;} td.linenos {text-align: right; width: 4em;}\n")
task = {
"basename": self.name,
"name": code_css_path,
"targets": [code_css_path],
"uptodate": [utils.config_changed(kw)],
"actions": [(create_code_css, [])],
"clean": True,
}
yield utils.apply_filters(task, kw["filters"])
示例13: get_theme_bundles
def get_theme_bundles(themes):
"""Given a theme chain, return the bundle definitions."""
bundles = {}
for theme_name in themes:
bundles_path = os.path.join(utils.get_theme_path(theme_name), "bundles")
if os.path.isfile(bundles_path):
with open(bundles_path) as fd:
for line in fd:
name, files = line.split("=")
files = [f.strip() for f in files.split(",")]
bundles[name.strip()] = files
break
return bundles
示例14: _execute
def _execute(self, options, args):
"""Install theme into current site."""
if requests is None:
utils.LOGGER.error('This command requires the requests package be installed.')
return False
listing = options['list']
url = options['url']
if args:
name = args[0]
else:
name = None
if name is None and not listing:
utils.LOGGER.error("This command needs either a theme name or the -l option.")
return False
data = requests.get(url).text
data = json.loads(data)
if listing:
print("Themes:")
print("-------")
for theme in sorted(data.keys()):
print(theme)
return True
else:
self.do_install(name, data)
# See if the theme's parent is available. If not, install it
while True:
parent_name = utils.get_parent_theme_name(name)
if parent_name is None:
break
try:
utils.get_theme_path(parent_name)
break
except: # Not available
self.do_install(parent_name, data)
name = parent_name
示例15: do_uninstall
def do_uninstall(self, name):
"""Uninstall a theme."""
try:
path = utils.get_theme_path(name)
except Exception:
LOGGER.error('Unknown theme: {0}'.format(name))
return 1
LOGGER.warning('About to uninstall theme: {0}'.format(name))
LOGGER.warning('This will delete {0}'.format(path))
sure = utils.ask_yesno('Are you sure?')
if sure:
LOGGER.warning('Removing {0}'.format(path))
shutil.rmtree(path)
return 0
return 1