Skip to content

API_Reference

Léo Flaventin Hauchecorne edited this page Nov 25, 2021 · 1 revision

User API Reference

plugin.py and single file templates

invokeTemplate(template_name:str, dest:str, args:list[str], out_f:file | None: None)

Invoke another template (template_name) generating to dest, with args passed to it. If specified, and if the template is single-file, then out_f can optionally be passed to generate to a file like.

plugin.py

You can use the from . import module_name to import module in the same directory as the plugin.py file

plugin.py (and single file template)

Symbols available in plugin.py and symbols you can define

args : [arg1, arg2, ...]

Argument list for the template. Basically everything following the double dash ( -- ) in the command line.

ask_help : bool

If --help was passed as first argument or dest is @help, then this flag will be set. The plugin is then expected to define a __doc__ variable (automatic with a docstring as file header) or a help variable.

C : <class skbs.pluginutils.Config>

skbs.pluginutils.Config class alias to create quickly dict-compatible javascript-like object objects.

click : <module click>

click module as if you imported it with import click. Permits to define advance CLI-like argument parser (see Click integration)

invokeCmd(cmd, args)

Invoke a click command with args as if they came from a command line. You should not call yourself a click command and always use this function, since it does some handling of click exceptions and file redirection to get the usage string.

EndOfPlugin : Exception

You should raise this exception as you would use a return if you were in a function : it will stop the plugin.py execution without an error and start parsing the template.

Could be used if ask_help is true to return immediately (don't forget to either put a docstring or a define a help variable...

PluginError : Exception

Raise it to inform skbs an error occurred (for example incompatible arguments). You should pass to it as first argument the help message.

pluginError(help_msg)

Shortcut to raise a PluginError

inside_skbs_plugin : bool

Will be set to True when the plugin is called from skbs, else, it won't be define.

As a Best-practice, you can use this snippet to prevent execution of the plugin outside skbs

try:
  inside_skbs_plugin
except:
  from skbs.pluginutils import IsNotAModuleOrScriptError
  raise IsNotAModuleOrScriptError()

Note : it is already included in the skbs plugin template

Tempiny : <class Tempiny>

Tempiny as if you had imported it like

from tempiny import Tempiny

Used to pass configuration and change the dialect depending to the file pattern.

dest : str | None

Root output directory. None if ask_help is True

parseCmd(click_opts_or_args...) : C

Parse the command line using the click option / arg decorators in argument, and produces a Dict-like with all option values. The options are also added to _p


conf = ...

User defined configuration. Use the following structure

conf = C(
  # Predefined template syntax are Tempiny.PY, Tempiny.C and Tempiny.TEX :
  # Tempiny.C  = dict(stmt_line_start=r'//#', begin_expr=', end_expr=')
  # Tempiny.PY = dict(stmt_line_start=r'##', begin_expr=', end_expr=')
  # Tempiny.TEX = dict(stmt_line_start=r'%#', begin_expr='<<', end_expr='>>')
  tempiny = [
    ('*' : Tempiny.PY), # '*' : glob-like pattern, Tempiny dialect to use if a file match the pattern
    # ...
  ],
  opt_prefix = '_opt.', # if a file starts with this prefix, it will not overwrite an existing file
  force_prefix = '_force.', # if a file starts with this prefix, it will overwrite an existing file
  raw_prefix = '_raw.', # if a file starts with this prefix, it will be copied as is
  template_prefix = '_template.', # if a file starts with this prefix, it will be parsed by Tempiny
  pathmod_filename = '__pathmod.py', # file name for pathmod scripts (always prefer in template new_path to change file name / location)
)
conf.dir_template_filename = conf.tamplte_prefix

__doc__ = ...

Prefer a header docstring that python will automatically recognize and assign this variable with. Script documentation.

Note : with click integration, the command usage will be used instead of this variable.

help = ...

Same as __doc__. Prefer __doc__

plugin = ...

This variable will be available everywhere else under the reference _p and plugin.


Template files

plugin

Alias for the plugin variable defined in plugin.py.

_p

Same as plugin, another shorter alias.

dest : pathlib.Path

Path of the current file relative to the destination

C : <class skbs.pluginutils.Config>

skbs.pluginutils.Config class alias to create quickly dict-compatible javascript-like object objects.

This class has a method register that can be used as a function or class decorator to insert it into the dict.

include(path)

Permits to include path.

path should be relative to an __include/ directory. It should be full relative real to __include path (including the _template. prefixed if necessary).

Return : a str containing the content of the file, parsed if it begins with __template_.

Hint : use if in an expression

{{include('_template.file.py')}}

exclude()

To abort reading the current file template, so that this file will not be copied to the destination.

endOfTemplate()

Same as function return : stop reading the template here, but keep and copy to destination what has been read.

beginSection(m=0, n=1, cb=None, placeholder=None, overwrite=None)

Start an overwritten section.

cb is a callback function cb(lines, i) where lines is a list of the lines in the original file, and i is the index of the current line being checked. The function should return true if lines[i] is the first line inside the section.

If cb is None, Then the section begin will try to match lines[cur + m : cur + n] in both the virtual output template and the original file.

If a placeholder is specified and the original file does not have this section, then it will be put just before the placeholder (so that further added sections go always to the end)

If overwrite is True, use the content from the template's virtual output, else, use the content of the original file. If left unset or None, will have not keep_only_sections as value to get an intuitive behavior It can also be to a callable object with this signature : overwrite(original: list[str], virtual: list[str], ctx: Callable[[], 'Context']) -> list[str]. Where origninal and virtual are respectively the content of the matched section. ctx is a callable to obtain the context, it returns an object with the following attributes read-only:

  • o : Original file :
    • o.lines : original file lines
    • o.sec_b : begin of section
    • o.sec_e : end of section
  • v Virtual output :
    • o.lines : original file lines
    • o.sec_b : begin of section
    • o.sec_e : end of section
  • keep_only_sections

endSection(m=-1, n=0, cb=None)

End an overwritten section.

cb is a callback function cb(lines, i) where lines is a list of the lines in the original file, and i is the index of the current line being checked. The function should return true if lines[i] is the last line (inclusive) inside the section.

If cb is None, Then the section end will try to match lines[cur + m : cur + n] in both the virtual output template and the original file.

placeholder(name, n=1, f=None)

Defines a placeholder

name is the name of the placeholder cb is a callback function cb(lines, i) where lines is a list of the lines in the original file, and i is the index of the current line being checked. The function should return true if the section should be inserted between lines[i] and lines[i+1]

If cb is None, Then the placeholder will try to match lines[cur + m : cur + n] in both the virtual output template and the original file.

sls, be, ee

Tempiny token configuration : - sls : Stmt_Line_Start - be : Begin of Expression - ee : End of Expression


new_path = ...

Path in the destination directory the file should have. Typically used like this to rename dynamically the file

## new_path = dest.with_name('new_name')

is_opt = ...

Changes the optionnal aspect of the template. Overrides the prefix in the template file name

use_sections = ...

If true force usage of sections. If None, use section if at least one section is defined. (default : None)

keep_only_sections = ...

If true, will overwrite the original only keeping its sections, else, only the sections will be replaced in the original file. (default : True)


_template. (or what conf.dir_template_filename contains)

This file is read as python code (not tempiny).

The same symbols than in file templates are defined except include.

Permit to define new_path for a directory. exclude() works also to prevent it to be copied (and entered).


Included templates

Same as regular files except dest is not defined and exclude() will exclude file template being parsed.


__pathmod.py

Deprecated. Used in previous version to change file name. Always prefer new_path variable in each template instead

removePrefix(p:Pathlib.Path) -> pathlib.Path

Function to remove prefixes from the filename

License

Copyright © 2018-2020 Léo Flaventin Hauchecorne

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.