pfdo-run 4.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pfdo_run/__init__.py ADDED
@@ -0,0 +1,39 @@
1
+ """pfdo_run: run a command in every directory of a tree.
2
+
3
+ The member of the pfdo family whose per-directory operation is a command the user
4
+ writes as a pftag template. ``%{inputWorkingDir}``, ``%{outputWorkingDir}`` and
5
+ ``%{inputWorkingFile}`` name the current directory's paths and file; functions such as
6
+ ``%{inputWorkingFile|rmext}`` derive output names.
7
+
8
+ Key components:
9
+ - PfdoRun: the engine
10
+ - PfdoRunOptions, FileJob: options in, job records out
11
+ - __main__: the ``pfdo_run`` command and the parts pl-shexec composes its own from
12
+
13
+ Typical usage:
14
+ pfdo_run --inputDir /data --outputDir /out --fileFilter 'glob:*.dcm' --analyzeFileIndex f \\
15
+ --exec "mri_convert %{inputWorkingDir}/%{inputWorkingFile} %{outputWorkingDir}/T1.nii.gz"
16
+
17
+ Dependencies:
18
+ - pfdo, pftag, hostlib
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ __version__: str = "4.0.0"
24
+
25
+ from pfdo_run.models import DirNode, FileJob, JobResult, PfdoRunOptions, RunResult, StageResult
26
+ from pfdo_run.pfdo_run import PfdoRun, lookups_forJob, sink_build
27
+
28
+ __all__ = [
29
+ "DirNode",
30
+ "FileJob",
31
+ "JobResult",
32
+ "PfdoRun",
33
+ "PfdoRunOptions",
34
+ "RunResult",
35
+ "StageResult",
36
+ "__version__",
37
+ "lookups_forJob",
38
+ "sink_build",
39
+ ]
pfdo_run/__main__.py ADDED
@@ -0,0 +1,338 @@
1
+ """The ``pfdo_run`` command line and its manual.
2
+
3
+ The parser and the manual are assembled from pftree's and pfdo's parts plus
4
+ pfdo_run's own, and are exposed in parts again for pl-shexec.
5
+
6
+ Key components:
7
+ - CLI_SELF, ARGS_SYNOPSIS_SELF, TAG_HELP, EXAMPLES: pfdo_run's manual pieces
8
+ - CLI_FULL, CLI_DS, ARGS_SYNOPSIS_FULL, ARGS_SYNOPSIS_DS: the assembled pieces
9
+ - synopsis, manual_build: the manual
10
+ - parserSelf_build / parser_build: the parsers
11
+ - main: the entry point
12
+
13
+ Typical usage:
14
+ pfdo_run --inputDir /in --outputDir /out --fileFilter jpg \\
15
+ --exec "convert %{inputWorkingDir}/%{inputWorkingFile} %{outputWorkingDir}/out.png"
16
+ pfdo_run --man
17
+
18
+ Dependencies:
19
+ - pftree, pfdo (their CLI parts and the manual renderer)
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import json
26
+ import sys
27
+ from collections.abc import Sequence
28
+
29
+ from pfdo.__main__ import ARGS_SYNOPSIS_SELF as PFDO_ARGS_SYNOPSIS_SELF
30
+ from pfdo.__main__ import CLI_SELF as PFDO_CLI_SELF
31
+ from pfdo.__main__ import parserSelf_build as pfdoParserSelf_build
32
+ from pftree.__main__ import (
33
+ ARGS_SYNOPSIS_CORE,
34
+ ARGS_SYNOPSIS_DS,
35
+ ARGS_SYNOPSIS_IO,
36
+ CLI_CORE,
37
+ CLI_DS_IO,
38
+ CLI_IO_CORE,
39
+ logging_configure,
40
+ parserCore_build,
41
+ parserIO_build,
42
+ )
43
+ from pftree.manual import Manual, manual_print
44
+
45
+ from pfdo_run import __version__
46
+ from pfdo_run.models import PfdoRunOptions, RunResult
47
+ from pfdo_run.pfdo_run import PfdoRun
48
+
49
+ BANNER_ART: str = r"""
50
+
51
+ __ _
52
+ / _| | |
53
+ _ __ | |_ __| | ___ _ __ _ _ _ __
54
+ | '_ \| _/ _` |/ _ \ | '__| | | | '_ \
55
+ | |_) | || (_| | (_) || | | |_| | | | |
56
+ | .__/|_| \__,_|\___/ |_| \__,_|_| |_|
57
+ | | ______
58
+ |_| |______|
59
+
60
+ """
61
+
62
+ BANNER_TITLE: str = "Path-File Do Run"
63
+
64
+ BANNER_TEXT: str = """
65
+ Path-File Do Run
66
+
67
+ Recursively walk down a directory tree and run a CLI spec'd app
68
+ on files in each directory (optionally filtered by some simple
69
+ expression). Results of each operation are saved in an output tree
70
+ that preserves the input directory structure.
71
+
72
+ -- version {version} --
73
+
74
+ 'pfdo_run' demonstrates how to use pftree to traverse
75
+ directory trees and execute some user specified CLI operation
76
+ at each directory level (that optionally contains files of interest).
77
+
78
+ As part of the "pf*" suite of applications, it is geared to IO as
79
+ directories. Nested directory trees within some input directory
80
+ are reconstructed in an output directory, preserving directory
81
+ structure.
82
+
83
+ """
84
+
85
+ CLI_SELF: str = """
86
+ --exec <commandTemplate> \\
87
+ [--noJobLogging] \\"""
88
+
89
+ ARGS_SYNOPSIS_SELF: str = """
90
+ --exec <commandTemplate>
91
+ The command to run for each selected file of each directory in the
92
+ input tree, written as a pftag template. See the TAGS section. The
93
+ template is split like a shell command line, each argument has its
94
+ tags resolved, and the result is run directly, without a shell: a
95
+ path with a space in it stays one argument, and shell features such
96
+ as pipes and redirection are not available.
97
+
98
+ [--noJobLogging]
99
+ If specified, suppress the per-job record. Usually each job that is
100
+ run leaves, in the output directory, four files:
101
+
102
+ <inputWorkingFile>-cmd
103
+ <inputWorkingFile>-stdout
104
+ <inputWorkingFile>-stderr
105
+ <inputWorkingFile>-returncode
106
+
107
+ The stream files are written as the command runs and, when it ends,
108
+ rendered as a terminal would have shown them: a progress bar redrawn
109
+ a hundred times is one line. By specifying this option, the above
110
+ files are not recorded.
111
+
112
+ At --verbosity 2 and above each command's output is also streamed to
113
+ the console while it runs, so a long job can be watched. Under
114
+ --threads the streams of concurrent jobs interleave.
115
+ """
116
+
117
+ TAG_HELP: str = """
118
+ TAGS
119
+
120
+ The --exec template is resolved by pftag (see pftag --man or the
121
+ pftag docs/tags.adoc). A tag is %{name}, optionally piped through
122
+ functions: %{name|function|function(arg, arg)}. Three tags describe
123
+ the job:
124
+
125
+ %{inputWorkingDir} the input directory being processed
126
+ %{outputWorkingDir} its counterpart in the output tree
127
+ %{inputWorkingFile} the file being processed
128
+
129
+ and every option of pfdo_run is a tag by name, so %{outputDir} is
130
+ the output tree's root. The core tags %{timestamp}, %{date},
131
+ %{hostname}, %{platform}, %{user} and %{pid} are available too.
132
+
133
+ Functions derive one name from another:
134
+
135
+ %{inputWorkingFile|rmext} brain.nii.gz -> brain.nii
136
+ %{inputWorkingFile|rmext|rmext}.jpg brain.nii.gz -> brain.jpg
137
+ %{inputWorkingFile|replace(.,-)} a.b.c -> a-b-c
138
+ %{inputWorkingFile|re([0-9]+,N)} im001.dcm -> imN.dcm
139
+ %{inputWorkingDir|basename} the directory's own name
140
+ %{inputWorkingFile|sha256(8)} a stable hash of the name
141
+
142
+ Nothing outside %{...} is a tag, so a literal % in the command is
143
+ fine. A tag that does not resolve fails that job before it runs;
144
+ the job's record says why.
145
+ """
146
+
147
+ EXAMPLES: str = """
148
+
149
+ EXAMPLES
150
+
151
+ Convert every jpg in a tree to png in a parallel tree:
152
+
153
+ pfdo_run \\
154
+ --inputDir /var/www/html/data --fileFilter 'glob:*.jpg' \\
155
+ --outputDir /var/www/html/png \\
156
+ --exec "convert %{inputWorkingDir}/%{inputWorkingFile}
157
+ %{outputWorkingDir}/%{inputWorkingFile|rmext}.png" \\
158
+ --threads 4 --printElapsedTime
159
+
160
+ Each conversion's command, stdout, stderr and return code are written
161
+ beside the png as <file>-cmd, <file>-stdout, <file>-stderr and
162
+ <file>-returncode. Add --verbosity 2 to watch the conversions as they run.
163
+
164
+ Run one command per DICOM series, started on the first file:
165
+
166
+ pfdo_run \\
167
+ --inputDir /data --outputDir /out \\
168
+ --fileFilter 'glob:*.dcm' --analyzeFileIndex f \\
169
+ --exec "mri_convert %{inputWorkingDir}/%{inputWorkingFile}
170
+ %{outputWorkingDir}/%{inputWorkingDir|basename}.nii.gz"
171
+
172
+ Copy one file out of each directory whose path names a subject:
173
+
174
+ pfdo_run \\
175
+ --inputDir $PWD/raw --outputDir $PWD/out \\
176
+ --dirFilter 100307 \\
177
+ --exec "cp %{inputWorkingDir}/brain.mgz %{outputWorkingDir}/brain.mgz" \\
178
+ --analyzeFileIndex f --noJobLogging --json
179
+
180
+ """
181
+
182
+ CLI_FULL: str = CLI_IO_CORE + CLI_SELF + PFDO_CLI_SELF + CLI_CORE
183
+ ARGS_SYNOPSIS_FULL: str = ARGS_SYNOPSIS_IO + ARGS_SYNOPSIS_SELF + PFDO_ARGS_SYNOPSIS_SELF + ARGS_SYNOPSIS_CORE
184
+ CLI_DS: str = CLI_DS_IO + CLI_SELF + PFDO_CLI_SELF + CLI_CORE
185
+ ARGS_SYNOPSIS_DS: str = ARGS_SYNOPSIS_DS + ARGS_SYNOPSIS_SELF + PFDO_ARGS_SYNOPSIS_SELF + ARGS_SYNOPSIS_CORE
186
+
187
+ DESCRIPTION: str = """
188
+ DESCRIPTION
189
+
190
+ ``pfdo_run`` walks the input tree with pftree, selects files in each
191
+ directory with the pfdo filters and --analyzeFileIndex, and runs the
192
+ --exec command once per selected file, with the command's tags
193
+ resolved against that directory and file. The output tree mirrors
194
+ the input tree; each directory's results and job logs land in its
195
+ counterpart. Directories run in parallel under --threads.
196
+ """
197
+
198
+
199
+ def synopsis(shortOnly: bool = False, command: str = "pfdo_run") -> str:
200
+ """Assemble the manual text.
201
+
202
+ Args:
203
+ shortOnly: NAME, SYNOPSIS and a brief example only.
204
+ command: the command name shown, for a package built on pfdo_run.
205
+
206
+ Returns:
207
+ The manual text, without the banner.
208
+ """
209
+ shortSynopsis: str = (
210
+ f"""
211
+ NAME
212
+
213
+ {command}
214
+
215
+ SYNOPSIS
216
+
217
+ {command} \\"""
218
+ + CLI_FULL
219
+ + f"""
220
+
221
+ BRIEF EXAMPLE
222
+
223
+ {command} \\
224
+ --inputDir /var/www/html/data --fileFilter jpg \\
225
+ --outputDir /var/www/html/png \\
226
+ --exec "convert %{{inputWorkingDir}}/%{{inputWorkingFile}}
227
+ %{{outputWorkingDir}}/%{{inputWorkingFile|rmext}}.png" \\
228
+ --threads 4 --printElapsedTime
229
+ """
230
+ )
231
+ if shortOnly:
232
+ return shortSynopsis
233
+ return shortSynopsis + DESCRIPTION + "\n ARGS " + ARGS_SYNOPSIS_FULL + TAG_HELP + EXAMPLES
234
+
235
+
236
+ def manual_build() -> Manual:
237
+ """The pfdo_run manual page."""
238
+ return Manual(
239
+ command="pfdo_run",
240
+ art=BANNER_ART,
241
+ title=BANNER_TITLE,
242
+ text=BANNER_TEXT,
243
+ version=__version__,
244
+ synopsisShort=synopsis(shortOnly=True),
245
+ synopsisFull=synopsis(shortOnly=False),
246
+ )
247
+
248
+
249
+ def parserSelf_build() -> argparse.ArgumentParser:
250
+ """pfdo_run's own options.
251
+
252
+ Returns:
253
+ A parent parser with ``--exec`` and ``--noJobLogging``.
254
+ """
255
+ parser: argparse.ArgumentParser = argparse.ArgumentParser(add_help=False)
256
+ parser.add_argument(
257
+ "--exec", dest="exec", default="", help="the command template to run per file (required)"
258
+ )
259
+ parser.add_argument(
260
+ "--noJobLogging",
261
+ dest="noJobLogging",
262
+ action="store_true",
263
+ help="do not write per-job cmd/stdout/stderr/rc",
264
+ )
265
+ return parser
266
+
267
+
268
+ def parser_build(standalone: bool = True) -> argparse.ArgumentParser:
269
+ """Assemble the full parser.
270
+
271
+ Args:
272
+ standalone: include ``--inputDir`` / ``--outputDir``. A ChRIS DS plugin
273
+ passes False and adds its own positional directories.
274
+
275
+ Returns:
276
+ The parser.
277
+ """
278
+ parents: list[argparse.ArgumentParser] = [
279
+ parserCore_build("pfdo_run", __version__),
280
+ pfdoParserSelf_build(),
281
+ parserSelf_build(),
282
+ ]
283
+ if standalone:
284
+ parents.insert(0, parserIO_build())
285
+ return argparse.ArgumentParser(
286
+ prog="pfdo_run",
287
+ description="Run a command in every directory of a tree. Full manual: pfdo_run --man",
288
+ formatter_class=argparse.RawDescriptionHelpFormatter,
289
+ parents=parents,
290
+ )
291
+
292
+
293
+ def options_fromArgs(args: argparse.Namespace) -> PfdoRunOptions:
294
+ """Turn parsed arguments into options."""
295
+ return PfdoRunOptions.fromDict(vars(args))
296
+
297
+
298
+ def result_report(args: argparse.Namespace, result: RunResult) -> None:
299
+ """Print what the arguments asked for."""
300
+ if args.json:
301
+ print(json.dumps(result.toDict(), indent=4, sort_keys=True))
302
+ if args.printElapsedTime:
303
+ print(f"Elapsed time = {result.runTime:.6f} seconds")
304
+
305
+
306
+ def main(argv: Sequence[str] | None = None) -> int:
307
+ """Run the command.
308
+
309
+ Args:
310
+ argv: arguments without the program name; ``None`` reads ``sys.argv``.
311
+
312
+ Returns:
313
+ 0 when at least one directory's jobs all succeeded (pftree's stage rule);
314
+ 1 when the run failed everywhere or could not start; 2 on bad arguments.
315
+ """
316
+ parser: argparse.ArgumentParser = parser_build()
317
+ args: argparse.Namespace = parser.parse_args(argv)
318
+ if args.man or args.synopsis:
319
+ manual_print(manual_build(), shortOnly=not args.man)
320
+ return 0
321
+ if not args.inputDir:
322
+ parser.error("--inputDir is required")
323
+ if not args.exec:
324
+ parser.error("--exec is required")
325
+ try:
326
+ options: PfdoRunOptions = options_fromArgs(args)
327
+ except ValueError as err:
328
+ parser.error(str(err))
329
+ logging_configure(options.verbosity)
330
+ result: RunResult = PfdoRun(options).run()
331
+ result_report(args, result)
332
+ if result.error:
333
+ print(result.error, file=sys.stderr)
334
+ return 0 if result.status else 1
335
+
336
+
337
+ if __name__ == "__main__":
338
+ sys.exit(main())
pfdo_run/models.py ADDED
@@ -0,0 +1,92 @@
1
+ """The data models of pfdo_run.
2
+
3
+ pfdo_run adds two options to pfdo's: the command template to run in every directory,
4
+ and whether each job's record is written beside its results. A job is one run of the
5
+ command for one file; its record names the file, the command as built, and carries the
6
+ hostlib envelope of the run when the command ran.
7
+
8
+ pfdo's and hostlib's models are re-exported here so that a tool built on pfdo_run
9
+ imports from pfdo_run alone.
10
+
11
+ Key components:
12
+ - PfdoRunOptions: ``PfdoOptions`` plus ``exec`` and ``noJobLogging``
13
+ - FileJob: one file's job: the command built for it and, if it ran, the run's envelope
14
+ - DirNode, StageResult, ProcessResult, RunResult, PfdoOptions, TreeOptions: pfdo's models
15
+ - JobResult, JobSpec, HostFacts: hostlib's models
16
+
17
+ Typical usage:
18
+ options = PfdoRunOptions.fromDict(vars(args))
19
+ PfdoRun(options).run()
20
+
21
+ Dependencies:
22
+ - pfdo.models, hostlib.models
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from dataclasses import dataclass, field
28
+
29
+ from hostlib.models import HostFacts, JobResult, JobSpec
30
+ from pfdo.models import DirNode, PfdoOptions, ProcessResult, RunResult, StageResult, TreeOptions
31
+
32
+
33
+ @dataclass
34
+ class PfdoRunOptions(PfdoOptions):
35
+ """pfdo's options plus pfdo_run's own.
36
+
37
+ Attributes:
38
+ exec: the command template, a pftag template split like a shell command.
39
+ Its tags name the current directory's paths and file:
40
+ ``%{inputWorkingDir}``, ``%{outputWorkingDir}``, ``%{inputWorkingFile}``,
41
+ plus every option by name, ``%{outputDir}``.
42
+ noJobLogging: do not write each job's command, stdout, stderr and return code
43
+ beside its results.
44
+
45
+ Example:
46
+ >>> PfdoRunOptions.fromDict({"inputDir": "/in", "exec": "ls %{inputWorkingDir}"}).exec
47
+ 'ls %{inputWorkingDir}'
48
+ """
49
+
50
+ exec: str = ""
51
+ noJobLogging: bool = False
52
+
53
+
54
+ @dataclass
55
+ class FileJob:
56
+ """One file's job: the command built for it and, when it ran, the run.
57
+
58
+ Attributes:
59
+ file: the input file the job was built for.
60
+ argv: the command as built, after tag substitution; the template's own
61
+ arguments when it could not be resolved; empty when there was no template.
62
+ status: the command was built, started and exited 0.
63
+ errors: why not: a tag that did not resolve, a program that could not start,
64
+ a non-zero exit status.
65
+ run: hostlib's envelope of the run, with both streams, exit status, host facts
66
+ and timing; ``None`` when the command was never run.
67
+
68
+ Example:
69
+ >>> FileJob("a.txt", ["true"], True).run is None
70
+ True
71
+ """
72
+
73
+ file: str
74
+ argv: list[str]
75
+ status: bool
76
+ errors: list[str] = field(default_factory=list)
77
+ run: JobResult | None = None
78
+
79
+
80
+ __all__: list[str] = [
81
+ "DirNode",
82
+ "FileJob",
83
+ "HostFacts",
84
+ "JobResult",
85
+ "JobSpec",
86
+ "PfdoOptions",
87
+ "PfdoRunOptions",
88
+ "ProcessResult",
89
+ "RunResult",
90
+ "StageResult",
91
+ "TreeOptions",
92
+ ]
pfdo_run/pfdo_run.py ADDED
@@ -0,0 +1,168 @@
1
+ """pfdo_run: run a command in every directory of a tree.
2
+
3
+ ``PfdoRun`` is the member of the pfdo family whose per-directory operation is a command
4
+ written by the user as a pftag template. For every file the directory's
5
+ ``--analyzeFileIndex`` selects, the template is split like a shell command, each
6
+ argument has its tags resolved against that directory's paths and the file, and the
7
+ result is run through hostlib: without a shell, both streams read as they arrive, the
8
+ record kept beside the results and, at ``--verbosity 2`` and above, streamed to the
9
+ console while the command runs.
10
+
11
+ Key components:
12
+ - PfdoRun: the engine; ``job_run`` builds and runs one command
13
+ - lookups_forJob: the tags a job can use
14
+ - sink_build: where a job's output goes while it runs
15
+
16
+ Typical usage:
17
+ PfdoRun(PfdoRunOptions(inputDir=Path("/in"), outputDir=Path("/out"),
18
+ exec="convert %{inputWorkingDir}/%{inputWorkingFile} "
19
+ "%{outputWorkingDir}/%{inputWorkingFile|rmext}.jpg")).run()
20
+
21
+ Dependencies:
22
+ - pfdo, pftag, hostlib
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import dataclasses
28
+ import logging
29
+ import shlex
30
+
31
+ from hostlib.proc.run import job_run as host_jobRun
32
+ from hostlib.sink import ConsoleSink, FileSink, JobSink, NullSink, TeeSink
33
+ from pfdo.pfdo import Pfdo
34
+ from pftag.models import ArgvResult, TagOptions
35
+ from pftag.pftag import Pftag
36
+
37
+ from pfdo_run.models import DirNode, FileJob, JobResult, JobSpec, PfdoRunOptions, StageResult
38
+
39
+ logger: logging.Logger = logging.getLogger("pfdo_run")
40
+
41
+ OPTIONS_LOOKUP: str = "options"
42
+ JOB_LOOKUP: str = "pfdo"
43
+ STREAM_VERBOSITY: int = 2
44
+
45
+
46
+ def lookups_forJob(options: PfdoRunOptions, node: DirNode, fileName: str) -> dict[str, dict[str, str]]:
47
+ """The tag dictionaries one job can resolve against.
48
+
49
+ Args:
50
+ options: the run's options; every field becomes a tag in the ``options``
51
+ dictionary, so ``%{outputDir}`` works.
52
+ node: the directory being processed.
53
+ fileName: the file the job is built for.
54
+
55
+ Returns:
56
+ ``options`` and ``pfdo`` (``inputWorkingDir``, ``outputWorkingDir``,
57
+ ``inputWorkingFile``), the latter also reachable qualified.
58
+ """
59
+ optionTags: dict[str, str] = {
60
+ name: str(value) for name, value in dataclasses.asdict(options).items() if name not in ("exec",)
61
+ }
62
+ jobTags: dict[str, str] = {
63
+ "inputWorkingDir": str(node.path),
64
+ "outputWorkingDir": str(node.outputPath),
65
+ "inputWorkingFile": fileName,
66
+ }
67
+ return {OPTIONS_LOOKUP: optionTags, JOB_LOOKUP: jobTags}
68
+
69
+
70
+ def sink_build(options: PfdoRunOptions, node: DirNode, fileName: str) -> JobSink:
71
+ """Where one job's output goes while it runs.
72
+
73
+ Args:
74
+ options: ``noJobLogging`` turns the file record off; ``verbosity`` of
75
+ ``STREAM_VERBOSITY`` or more streams to the console.
76
+ node: the directory; the record lands in its ``outputPath``.
77
+ fileName: the file; the record is ``<file>-cmd``, ``-stdout``, ``-stderr``,
78
+ ``-returncode``, the stream files rendered as a terminal would show them.
79
+
80
+ Returns:
81
+ A file sink, a console sink, both, or nothing.
82
+ """
83
+ sinks: list[JobSink] = []
84
+ if not options.noJobLogging:
85
+ sinks.append(FileSink(node.outputPath / fileName, rendered=True))
86
+ if options.verbosity >= STREAM_VERBOSITY:
87
+ sinks.append(ConsoleSink())
88
+ if not sinks:
89
+ return NullSink()
90
+ return sinks[0] if len(sinks) == 1 else TeeSink(*sinks)
91
+
92
+
93
+ class PfdoRun(Pfdo):
94
+ """Run a command template in every directory of the input tree.
95
+
96
+ Attributes:
97
+ options: the PfdoRunOptions in force.
98
+ argvTemplate: the ``--exec`` template split like a shell command, once.
99
+
100
+ Example:
101
+ >>> tool = PfdoRun(PfdoRunOptions(inputDir=Path("."), outputDir=Path("/tmp/o"), exec="true"))
102
+ >>> tool.argvTemplate
103
+ ['true']
104
+ """
105
+
106
+ def __init__(self, options: PfdoRunOptions) -> None:
107
+ super().__init__(options)
108
+ self.options: PfdoRunOptions = options
109
+ self.argvTemplate: list[str] = shlex.split(options.exec) if options.exec else []
110
+
111
+ def inputRead_callback(self, node: DirNode) -> StageResult:
112
+ """Create the directory's output path and pass its files on.
113
+
114
+ Args:
115
+ node: the directory.
116
+
117
+ Returns:
118
+ Success with the files; failure if there are none.
119
+ """
120
+ node.outputPath.mkdir(parents=True, exist_ok=True)
121
+ return StageResult(status=bool(node.files), files=list(node.files))
122
+
123
+ def inputAnalyze_callback(self, node: DirNode, read: StageResult) -> StageResult:
124
+ """Run the command for every file ``--analyzeFileIndex`` selects.
125
+
126
+ Args:
127
+ node: the directory.
128
+ read: the read stage's result.
129
+
130
+ Returns:
131
+ The files run, with every FileJob in ``payload["jobs"]``; ``status`` is
132
+ True only when every job was built, started and exited 0.
133
+ """
134
+ jobs: list[FileJob] = [self.job_run(node, fileName) for fileName in self.filesToAnalyze(node)]
135
+ return StageResult(
136
+ status=bool(jobs) and all(job.status for job in jobs),
137
+ files=[job.file for job in jobs],
138
+ payload={"jobs": [dataclasses.asdict(job) for job in jobs]},
139
+ )
140
+
141
+ def job_run(self, node: DirNode, fileName: str) -> FileJob:
142
+ """Build and run the command for one file.
143
+
144
+ The template's tags are resolved per argument, so a path with a space stays
145
+ one argument; the command then runs through hostlib, without a shell, its
146
+ output going to the sink ``sink_build`` chooses while it runs.
147
+
148
+ Args:
149
+ node: the directory.
150
+ fileName: the file the command is built for.
151
+
152
+ Returns:
153
+ The job's record. A template that fails to resolve is a job that was
154
+ never run; a program that cannot start or exits non-zero is a failed run.
155
+ """
156
+ if not self.argvTemplate:
157
+ return FileJob(fileName, [], False, ["--exec is empty"])
158
+ tagger: Pftag = Pftag(TagOptions(lookups=lookups_forJob(self.options, node, fileName), strict=True))
159
+ resolved: ArgvResult = tagger.argv_process(self.argvTemplate)
160
+ if not resolved.status:
161
+ logger.error("%s/%s: %s", node.relPath, fileName, "; ".join(resolved.errors()))
162
+ return FileJob(fileName, resolved.argv, False, resolved.errors())
163
+ logger.debug("%s/%s: %s", node.relPath, fileName, shlex.join(resolved.argv))
164
+ sink: JobSink = sink_build(self.options, node, fileName)
165
+ run: JobResult = host_jobRun(JobSpec(argv=resolved.argv), sink=sink)
166
+ if not run.status:
167
+ logger.warning("%s/%s: %s", node.relPath, fileName, "; ".join(run.errors))
168
+ return FileJob(fileName, resolved.argv, run.status, list(run.errors), run)
@@ -0,0 +1,110 @@
1
+ Metadata-Version: 2.4
2
+ Name: pfdo_run
3
+ Version: 4.0.0
4
+ Summary: Run a command, written as a pftag template, in every directory of a tree
5
+ Author-email: FNNDSC <dev@babyMRI.org>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/FNNDSC/pfdo_run
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Classifier: Programming Language :: Python :: 3.14
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: OS Independent
15
+ Requires-Python: >=3.11
16
+ Description-Content-Type: text/x-rst
17
+ License-File: LICENSE
18
+ Requires-Dist: pfdo>=6.1.0
19
+ Requires-Dist: pftag>=3.1.0
20
+ Requires-Dist: hostlib>=1.1.0
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest>=8; extra == "dev"
23
+ Requires-Dist: ruff>=0.6; extra == "dev"
24
+ Dynamic: license-file
25
+
26
+ pfdo_run
27
+ ========
28
+
29
+ .. image:: https://github.com/FNNDSC/pfdo_run/actions/workflows/ci.yml/badge.svg
30
+ :target: https://github.com/FNNDSC/pfdo_run/actions/workflows/ci.yml
31
+
32
+ .. image:: https://img.shields.io/pypi/v/pfdo_run.svg
33
+ :target: https://pypi.org/project/pfdo_run/
34
+
35
+ .. image:: https://img.shields.io/badge/python-3.11%2B-blue.svg
36
+ :target: https://pypi.org/project/pfdo_run/
37
+
38
+ Run a command, written as a pftag template, in every directory of a tree.
39
+
40
+ .. contents:: Table of Contents
41
+
42
+ Overview
43
+ --------
44
+
45
+ ``pfdo_run`` walks an input directory with ``pftree``, selects files in each directory with the ``pfdo`` filters and ``--analyzeFileIndex``, and runs the ``--exec`` command once per selected file. The command is a ``pftag`` template: ``%{inputWorkingDir}``, ``%{outputWorkingDir}`` and ``%{inputWorkingFile}`` name the directory being processed, its counterpart in the output tree, and the file; functions derive names, ``%{inputWorkingFile|rmext}.png``. The output tree mirrors the input tree, and each job leaves its command, stdout, stderr and return code beside its results. Directories run in parallel under ``--threads``.
46
+
47
+ The template is split like a shell command line and each argument has its tags resolved on its own, so a path with a space stays one argument and nothing a file name contains can change the command. The command runs without a shell.
48
+
49
+ Installation
50
+ ------------
51
+
52
+ .. code:: bash
53
+
54
+ pip install pfdo_run
55
+
56
+ Python 3.11 or newer; depends on ``pfdo`` and ``pftag``.
57
+
58
+ Command line
59
+ ------------
60
+
61
+ .. code:: bash
62
+
63
+ pfdo_run --inputDir /data --outputDir /png --fileFilter 'glob:*.jpg' --threads 4 \
64
+ --exec "convert %{inputWorkingDir}/%{inputWorkingFile} %{outputWorkingDir}/%{inputWorkingFile|rmext}.png"
65
+
66
+ pfdo_run --inputDir /dicom --outputDir /nifti --fileFilter 'glob:*.dcm' --analyzeFileIndex f \
67
+ --exec "mri_convert %{inputWorkingDir}/%{inputWorkingFile} %{outputWorkingDir}/%{inputWorkingDir|basename}.nii.gz"
68
+
69
+ pfdo_run --man
70
+
71
+ All of ``pftree``'s and ``pfdo``'s options apply. ``pfdo_run`` adds:
72
+
73
+ ``--exec <commandTemplate>``
74
+ The command to run per selected file. Tags: ``%{inputWorkingDir}``, ``%{outputWorkingDir}``, ``%{inputWorkingFile}``, every option by name (``%{outputDir}``), and pftag's core tags. Functions: ``rmext``, ``ext``, ``basename``, ``dirname``, ``replace``, ``re``, ``upper``, ``lower``, ``strip``, ``pad``, ``slice``, ``md5``, ``sha256``, ``strftime``, ``mask``. A tag that does not resolve fails that job before it runs.
75
+
76
+ ``--noJobLogging``
77
+ Do not write ``<file>-cmd``, ``<file>-stdout``, ``<file>-stderr`` and ``<file>-returncode`` beside each job's results. The stream files are written live and rendered as a terminal would show them when the job ends.
78
+
79
+ A job whose command exits non-zero fails its directory; the run continues and the directory's record says why. ``--json`` prints the whole result, each directory's jobs included.
80
+
81
+ Library
82
+ -------
83
+
84
+ .. code:: python
85
+
86
+ from pathlib import Path
87
+ from pfdo_run import PfdoRun, PfdoRunOptions
88
+
89
+ options = PfdoRunOptions(
90
+ inputDir=Path("/data"), outputDir=Path("/png"), fileFilter="glob:*.jpg", threads=4,
91
+ exec="convert %{inputWorkingDir}/%{inputWorkingFile} %{outputWorkingDir}/%{inputWorkingFile|rmext}.png",
92
+ )
93
+ result = PfdoRun(options).run()
94
+ for key, stage in result.process.analyze.items():
95
+ for job in stage.payload["jobs"]:
96
+ print(key, job["file"], job["run"]["returncode"] if job["run"] else job["errors"])
97
+
98
+ ``pfdo_run.__main__`` exposes its parser and manual in parts (``parser_build(standalone=False)``, ``synopsis(command=...)``, ``CLI_DS``, ``ARGS_SYNOPSIS_DS``) so that a ChRIS plugin such as ``pl-shexec`` composes its own command around them.
99
+
100
+ Changes in 4.0
101
+ --------------
102
+
103
+ - Built on ``pfdo`` 6 and ``pftag`` 3; ``pfmisc``, ``pudb`` and ``Faker`` are no longer dependencies.
104
+ - The template grammar is pftag's: ``%{name}`` and ``%{name|fn(arg)}``. The 3.x forms ``%name`` and ``%_fn_name`` are gone; a bare ``%name`` of a known tag is reported as a 1.x template and fails the job.
105
+ - The command is split before substitution and run without a shell; 3.x substituted into the string and split on whitespace, so a path with a space broke it.
106
+ - The command runs through ``hostlib``: no shell, both streams read concurrently as they arrive, so nothing is dropped and nothing can deadlock; 3.x read stdout line by line, lost the last line, and could deadlock on stderr. At ``--verbosity 2`` and above the output also streams to the console while the job runs.
107
+ - Per-job records are written by default and ``--noJobLogging`` exists; in 3.x the option was documented but undefined, so logs were never written. The stream files are rendered as a terminal would have shown them, so a redrawn progress bar is one line; the record in ``--json`` keeps every frame.
108
+ - Each job's record is ``FileJob``: the file, the command as built, status, errors, and ``run``, hostlib's envelope of the run (both streams, exit status, host facts, timing) when the command ran.
109
+ - A non-zero exit status fails the job and its directory; the run's status is truthful (3.x reported False always).
110
+ - ``main(argv)`` honours ``argv``; ``--version``, ``--man`` and ``--synopsis`` exit 0; packaging is ``pyproject.toml`` only, published from CI on a ``v*`` tag.
@@ -0,0 +1,10 @@
1
+ pfdo_run/__init__.py,sha256=QJGTGgOJw-lqucqSOGh-mwkr3NUR7WLXD-pG8yaIiOI,1225
2
+ pfdo_run/__main__.py,sha256=FNDIhZ99gVFi2Ght7EthEH9BcmvRM3SYpBbkMDaS7OY,12470
3
+ pfdo_run/models.py,sha256=MnUfCDqJDQaBc3_X8jAd9bw4Eg3GDUvSzH9AP47i5wE,3000
4
+ pfdo_run/pfdo_run.py,sha256=QfdA6EuJaHyWk4SOvqhEpkpR4eqdBgwQ-F8cZMH_QDk,6843
5
+ pfdo_run-4.0.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
6
+ pfdo_run-4.0.0.dist-info/METADATA,sha256=xp24R6Ldd4GNt_xG5en69qVNPIovjziWoQdofcIrY-s,6231
7
+ pfdo_run-4.0.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
8
+ pfdo_run-4.0.0.dist-info/entry_points.txt,sha256=2tAd_KG6g-xH-_F5XRX56byHGHirdVZrscY9LV-h-Lw,52
9
+ pfdo_run-4.0.0.dist-info/top_level.txt,sha256=sws_cVZI7zNCzMd4FswHSKRE0TR3VIcWL6Rwg-2LuI4,9
10
+ pfdo_run-4.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pfdo_run = pfdo_run.__main__:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ pfdo_run