comparison piecrust/commands/builtin/info.py @ 1134:986ecdaa2a36

url: New `url` command to get the URL of a page from its path.
author Ludovic Chabant <ludovic@chabant.com>
date Mon, 23 Apr 2018 21:37:27 -0700
parents 6462c4a87532
children
comparison
equal deleted inserted replaced
1133:fe0af94ca757 1134:986ecdaa2a36
1 import os
1 import os.path 2 import os.path
2 import logging 3 import logging
3 from piecrust.commands.base import ( 4 from piecrust.commands.base import (
4 ChefCommand, ChefCommandExtension, _ResourcesHelpTopics) 5 ChefCommand, ChefCommandExtension, _ResourcesHelpTopics)
5 6
231 logger.info(name) 232 logger.info(name)
232 else: 233 else:
233 if pattern is None or fnmatch.fnmatch(name, pattern): 234 if pattern is None or fnmatch.fnmatch(name, pattern):
234 logger.info(item.spec) 235 logger.info(item.spec)
235 236
237
238 class UrlCommand(ChefCommand):
239 def __init__(self):
240 super().__init__()
241 self.name = 'url'
242 self.description = "Gets the URL to a given page."
243
244 def setupParser(self, parser, app):
245 parser.add_argument(
246 'path',
247 help="The path to the page.")
248 parser.add_argument(
249 '-f', '--func',
250 dest='tpl_func',
251 action='store_true',
252 help="Return the template function call instead of the URL.")
253
254 def run(self, ctx):
255 from piecrust.sources.fs import FSContentSourceBase
256 from piecrust.routing import RouteParameter
257
258 # Find which source this page might belong to.
259 full_path = os.path.join(ctx.app.root_dir, ctx.args.path)
260 for src in ctx.app.sources:
261 if not isinstance(src, FSContentSourceBase):
262 continue
263
264 if full_path.startswith(src.fs_endpoint_path + os.sep):
265 parent_src = src
266 break
267 else:
268 raise Exception("Can't find which source this page belongs to.")
269
270 route = ctx.app.getSourceRoute(parent_src.name)
271 content_item = parent_src.findContentFromSpec(full_path)
272 route_params = content_item.metadata['route_params']
273
274 if ctx.args.tpl_func:
275 if not route.func_name:
276 raise Exception("Source '%s' doesn't have a route with "
277 "a template function name defined." %
278 parent_src.name)
279
280 url = '%s(' % route.func_name
281 for i, p in enumerate(route.uri_params):
282 if i > 0:
283 url += ', '
284 pinfo = route.getParameter(p)
285 if pinfo.param_type == RouteParameter.TYPE_INT2:
286 url += '%02d' % route_params[p]
287 elif pinfo.param_type == RouteParameter.TYPE_INT4:
288 url += '%04d' % route_params[p]
289 else:
290 url += str(route_params[p])
291 url += ')'
292 logger.info(url)
293 else:
294 url = route.getUri(route_params)
295 logger.info(url)