Skip to content

Latest commit

 

History

History
181 lines (127 loc) · 10.8 KB

tags.adoc

File metadata and controls

181 lines (127 loc) · 10.8 KB

pftag: the template reference

Abstract

This is the reference for writing pftag templates: text whose %{…​} tags are resolved when the text is used. It covers the grammar of a tag, how names resolve, how functions chain and take arguments, how literal text starts a chain, what the core tags and built-in functions do, how a program registers its own tags, and how commands are processed safely. It is written for the person typing a template on a command line, such as a pfdo_run --exec string, an output file name or a pflog URL, and for the developer registering tags for them.

A template

A template is ordinary text. A tag is %{ …​ }. Everything else passes through unchanged:

run-%{timestamp}-on-%{hostname}.log

becomes, when processed,

run-2026-10-13T21:40:12.118-04:00-on-pangea.log

Nothing outside %{…​} is a tag. printf "%s", date +%Y%m%d, 100% done and %20 in a URL are all literal text, because none of them contains %{. This is the deliberate difference from 1.x, where a bare %name was a tag and every % in a printf format or a URL was a near miss. Inside the braces % is an ordinary character, so %{timestamp|strftime(%Y%m%d)} works. The one escape is \%{, which produces a literal %{; a backslash anywhere else is a backslash.

Names

The head of a tag is a name: letters, digits and underscores, not starting with a digit. The braces delimit it, so a tag may run straight into other text, %{subject}_01 or %{subject}report.txt, and names may themselves contain underscores, %{input_working_dir}.

A name resolves against the core tags, listed below, and against the lookup dictionaries a program has registered. A registered name shadows a core tag of the same name; the core tag is still reachable as %{core.name}. Each dictionary has a name of its own, and a tag may be written qualified by it, %{secrets.user}, which is required when two dictionaries define the same tag and is otherwise optional.

A name that resolves to nothing is an unknown tag. It is left in the text exactly as written, %{nope}, and reported in the result’s unknownTags. Under --strict it fails the result instead. Unknown tags are kept rather than erased so that a template reaching a tool through several layers of quoting is debuggable: the tag that did not resolve is still visible in the output.

The core tags:

tag value

%{timestamp}

the current local time in ISO 8601 with its UTC offset, computed when the template is processed

%{date}

today’s date, YYYY-MM-DD

%{hostname}

the host name; inside a container, the container’s id

%{platform}

platform.system(), such as Linux

%{user}

the login name, or the numeric uid when the process has no passwd entry, as in many containers

%{pid}

the process id

Functions

A tag’s value can be piped through functions written after the head, each introduced by |:

%{timestamp|md5}
%{inputWorkingFile|rmext}.jpg
%{timestamp|replace(:,-)|md5(6)}

The order is the tag first, then what to do to it, left to right, each function receiving the previous one’s result: the order of a UNIX pipe. The last example reads: take the timestamp, replace each : with -, hash the result to six characters. Text after the closing } is kept, so an extension can follow a function.

Arguments are written in parentheses after the function’s name, separated by commas. An argument is either bare or quoted:

replace(:, -)              bare: trimmed of surrounding whitespace; may not contain , ) | or }
replace(":", "-")          double-quoted
replace(':', '-')          single-quoted, convenient inside a double-quoted shell string
replace(",", "\"")         inside quotes, \" \' and \\ escape

A function that takes no arguments may be written with or without empty parentheses: %{file|rmext} and %{file|rmext()} are the same.

A function that is given the wrong number of arguments, an argument it cannot use, or a name that is not registered fails the tag: the tag is left in the text as written, the result’s status is False, errors names the function and the problem, and the command exits 1. The rest of the template still resolves, so that one mistake does not hide the others.

The built-in functions:

function effect

rmext

drop the last extension: brain.nii.gz becomes brain.nii; apply twice for brain

ext

the last extension without its dot: brain.nii.gz gives gz

basename

the last path component: /a/b/c.txt gives c.txt

dirname

the path without its last component: /a/b/c.txt gives /a/b

replace(a, b)

replace every a with b, taken literally

re(pattern, repl)

replace every match of the regular expression pattern with repl; repl may use \1 groups

upper, lower

change case

strip / strip(chars)

drop leading and trailing whitespace, or the given characters

pad(width) / pad(width, char)

left-pad to width with char, default 0: 7 becomes 0007

slice(stop) / slice(start, stop)

characters by index, Python style, so slice(3) is the first three

md5 / md5(n), sha256 / sha256(n)

the hex digest, cut to its first n characters when given

strftime(format)

format an ISO 8601 timestamp with a strftime pattern: %{timestamp|strftime(%Y%m%d-%H%M)}

mask(pattern)

for each position of the pattern, keeps the value’s character and any other character replaces it; positions past the pattern are kept, so the result is never shorter than the value. %{platform|mask(l***)} turns Linux into linux

dcmname / dcmname(seed)

a DICOM-style LAST^FIRST name, see below

Pseudonyms

dcmname replaces a value with a LAST^FIRST name generated from a seed: the argument when given, the value itself otherwise. The same seed always gives the same name, so a subject can carry one pseudonym across a study, and a tail can follow the tag: %{PatientName|dcmname(study-1)}^ANON.

Be clear about what that is: a seeded hash wearing a surname. Anyone who holds the seed scheme can recompute the name from the identifier, and a name is no harder to join across datasets than the hash would be. It is a readable stand-in, not anonymization, and the mapping it implies must be governed like any other re-identification key. The function needs the faker package: pip install 'pftag[names]'; without it, using dcmname fails with a message saying so.

Literal heads

A quoted string can stand in the head’s place, so a chain can start from text that is not a tag:

%{"Subject12345"|sha256(8)}
%{'ses-01'|upper}

This is the way to carry protected text through a template safely: the identifier never appears in the output, only its hash, and anyone who knows the identifier can recompute the hash to find its records. The 1.x idiom for this, %literal_echo|Subject12345,md5|5_, needed two pseudo-functions; a literal head needs none.

Commands

Substituting into a command line as text is unsafe: a value with a space or a quote changes how the shell, or the splitter, reads the command. pftag therefore offers two entry points:

process(template)

Text in, text out. For file names, URLs and messages.

argv_process(argv)

For commands. The caller splits the user’s command first, with shlex.split, and pftag then processes each argument as a template of its own. A value with a space stays inside its argument; a value with a quote is just characters. pfdo_run uses this for its --exec string. The result carries a status; a command whose status is False must not be run, because one of its arguments still contains an unresolved or failed tag.

Values are substituted once. A value that itself contains %{…​} is not processed again, so a value cannot inject tags.

Registering tags from a program

from pftag import Pftag, TagOptions

tagger = Pftag(TagOptions(lookups={"pfdo": {
    "inputWorkingDir": "/in/sub-01",
    "outputWorkingDir": "/out/sub-01",
    "inputWorkingFile": "T1.nii.gz",
}}))
tagger("%{inputWorkingDir}/%{inputWorkingFile}").result
tagger.argv_process(shlex.split("convert %{inputWorkingDir}/%{inputWorkingFile} %{outputWorkingDir}/%{inputWorkingFile|rmext}.jpg")).argv

lookup_add(name, values) registers a dictionary after construction; registering a dictionary again replaces it. A dictionary’s name and its tag names are identifiers; a tag name already defined by a different dictionary is an error at registration, since a silent shadow would be a bug in the program, not a choice by the user. Values are stringified. lookups_addFromJson(text) takes the command line’s JSON, {"name": {"tag": "value"}} or a list of such objects.

Functions are added through a FunctionRegistry passed to Pftag:

registry = FunctionRegistry()
registry.add("shout", lambda value, args: value.upper() + "!")
Pftag(registry=registry)("%{'hi'|shout}").result   # 'HI!'

A function receives the value so far and the list of arguments as written, and returns text; it raises FunctionError for arguments it cannot use, which pftag reports as a failed tag.

Reading a result

The command prints the processed text and, with --json, the whole result. The library returns a TagResult:

field meaning

status

False when strict met an unknown or 1.x-style tag, a tag did not parse, or a function failed

result

the processed text; a failing tag is left as written

template

the text as given

tagsFound

every tag head met, in order

unknownTags

heads that resolved to nothing

legacyTags

bare %name occurrences of known names outside braces: 1.x templates that need %{name}

functionsApplied

name(arg,arg) for every function run, in order

errors

one message per failure

argv_process returns an ArgvResult: status, the processed argv, and the TagResult of each argument.

Moving a 1.x template

A 1.x template, run-%timestamp_chrplc|:|-.log, contains no %{, so under 3.0 it passes through untouched, which would be a silent failure. pftag therefore recognises a bare % followed by a known name, or by a known name and , as a probable 1.x tag: it is reported in legacyTags, warned about at verbosity 1 and above, and fails the run under --strict. The rewrite is mechanical:

%timestamp                        →  %{timestamp}
%file_rmext_.jpg                  →  %{file|rmext}.jpg
%timestamp_chrplc|:|-,md5|6_      →  %{timestamp|replace(:,-)|md5(6)}
%literal_echo|Subject12345,md5|5_ →  %{"Subject12345"|md5(5)}
%NAME_dcmname|seed|^ANON_         →  %{NAME|dcmname(seed)}^ANON
%platform_strmsk|l****_           →  %{platform|mask(l****)}

chrplc and strrepl became replace (literal) and re (regular expression); strmsk became mask; echo and %literal are replaced by a quoted head; os, release, machine and arch are gone, and hostname, user, pid and date are new.