comparison piecrust/commands/builtin/scaffolding.py @ 1152:74c0c7483986

copyasset: Add `copyasset` command.
author Ludovic Chabant <ludovic@chabant.com>
date Sat, 19 Jan 2019 17:40:13 -0800
parents a85b2827ba1a
children aad9b5a0a809
comparison
equal deleted inserted replaced
1151:0d699f04968c 1152:74c0c7483986
1 import os 1 import os
2 import os.path 2 import os.path
3 import logging 3 import logging
4 from piecrust.commands.base import ExtendableChefCommand, ChefCommandExtension 4 from piecrust.commands.base import (
5 ChefCommand, ExtendableChefCommand, ChefCommandExtension)
5 6
6 7
7 logger = logging.getLogger(__name__) 8 logger = logging.getLogger(__name__)
8 9
9 10
223 "\n" + 224 "\n" +
224 "You can add user-defined templates by creating pages in a " 225 "You can add user-defined templates by creating pages in a "
225 "`scaffold/pages` sub-directory in your website.") 226 "`scaffold/pages` sub-directory in your website.")
226 return help_txt 227 return help_txt
227 228
229
230 class CopyAssetCommand(ChefCommand):
231 """ Chef command for copying files into a page's assets folder.
232 """
233 def __init__(self):
234 super().__init__()
235 self.name = 'copyasset'
236 self.description = "Copies files into a page's assets folder."
237
238 def setupParser(self, parser, app):
239 parser.add_argument('path',
240 help="The path to the asset file.")
241 parser.add_argument('page',
242 help="The path to the page file.")
243 parser.add_argument('-n', '--rename',
244 help=("Rename the file so that it will be known "
245 "by this name in the `{{assets}}` syntax."))
246
247 def checkedRun(self, ctx):
248 # TODO: suppor other types of sources...
249 import shutil
250 from piecrust.sources import mixins
251
252 item = None
253 spec = ctx.args.page
254 for src in ctx.app.sources:
255 if not isinstance(src, mixins.SimpleAssetsSubDirMixin):
256 logger.warning(
257 "Ignoring source '%s' because it's not supported yet." %
258 src.name)
259 continue
260
261 try:
262 item = src.findContentFromSpec(spec)
263 break
264 except Exception as ex:
265 logger.warning(
266 "Ignoring source '%s' because it raised an error: %s" %
267 src.name, ex)
268 continue
269
270 if item is None:
271 raise Exception("No such page: %s" % ctx.args.page)
272
273 spec_no_ext, _ = os.path.splitext(item.spec)
274 assets_dir = spec_no_ext + mixins.assets_suffix
275 if not os.path.isdir(assets_dir):
276 logger.info("Creating directory: %s" % assets_dir)
277 os.makedirs(assets_dir)
278
279 dest_name, dest_ext = os.path.splitext(os.path.basename(ctx.args.path))
280 dest_name = ctx.args.rename or dest_name
281
282 dest_path = os.path.join(assets_dir, dest_name + dest_ext)
283 logger.info("Copying '%s' to '%s'." % (ctx.args.path, dest_path))
284 shutil.copy2(ctx.args.path, dest_path)