machinefile 0.0.1__tar.gz → 0.1.4__tar.gz

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.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Alan Justino
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,88 @@
1
+ Metadata-Version: 2.4
2
+ Name: machinefile
3
+ Version: 0.1.4
4
+ Summary: Compile a Machinefile (Dockerfile-syntax) into an Ansible playbook with Docker layer-cache semantics
5
+ Keywords: machinefile,ansible,dockerfile,provisioning,reproducible
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Classifier: Environment :: Console
9
+ Classifier: Intended Audience :: System Administrators
10
+ Classifier: Operating System :: POSIX :: Linux
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: System :: Installation/Setup
13
+ Classifier: Topic :: System :: Systems Administration
14
+ Requires-Dist: pyyaml>=6.0.3
15
+ Requires-Dist: rich-click>=1.9.9
16
+ Requires-Dist: ansible-core>=2.21.5 ; extra == 'ansible'
17
+ Requires-Python: >=3.13
18
+ Provides-Extra: ansible
19
+ Description-Content-Type: text/markdown
20
+
21
+ # machinefile
22
+
23
+ Describe a system setup as a `Machinefile` (Dockerfile syntax), compile it
24
+ to an Ansible playbook, apply it locally or over ssh. Docker's layer cache
25
+ on a mutable machine, with no custom executor.
26
+
27
+ ## Hello world
28
+
29
+ Create `Machinefile` (`chmod +x` optional), then `./Machinefile apply`:
30
+
31
+ ```
32
+ #!/usr/bin/env -S uvx --from machinefile[ansible] machine
33
+ FROM ubuntu
34
+ RUN echo hello > /tmp/hello
35
+ RUN wc -c < /tmp/hello
36
+ ```
37
+
38
+ The only prerequisite is [uv](https://docs.astral.sh/uv/): the shebang lets
39
+ uvx fetch the tool ephemerally (no install step); the `[ansible]` extra
40
+ adds ansible-core, the executor. Bare `./Machinefile`
41
+ prints help; `./Machinefile plan|apply|reset` do the work. Re-apply is a
42
+ no-op; re-runs resume at your edit. `./Machinefile reset` forgets this
43
+ file's applied layers so the next apply replays everything.
44
+
45
+ Install the command permanently (optional):
46
+
47
+ uv tool install 'machinefile[ansible]' # or pipx
48
+
49
+ ## Commands
50
+
51
+ machine apply Machinefile [user@host] # local, or ssh (python3 on target)
52
+ machine plan Machinefile [ctx] -o pb.yaml [--arg K=V]...
53
+ machine reset Machinefile [user@host] # forget this file's applied layers
54
+ machine apply Machinefile -v # show task output (-vv, -vvv…)
55
+ machine apply Machinefile -- --check # passthrough to ansible-playbook
56
+
57
+ Re-apply resumes at your edit: unchanged layers skip, appended layers run
58
+ alone, a failed layer retries with its upstream still skipped. That is the
59
+ hash chain (`sha256(parent + layer)`, markers in `/var/lib/machinefile/`),
60
+ expressed as Ansible `creates:` guards on paired work/marker tasks.
61
+
62
+ | Instruction | Becomes |
63
+ |-----------------------|-----------------------------------------------------|
64
+ | `RUN cmd` | `shell` + stamp pair (heredocs verbatim, ENV as export prefix) |
65
+ | `COPY src dest` | `copy` with `checksum:` (native idempotency) |
66
+ | `COPY dir dest` | stamp pair: tree-hash check + `cp -a` |
67
+ | `ADD url dest` | `get_url` + stamp pair |
68
+ | `ADD archive dest` | stamp pair: `tar -xf` |
69
+ | `ENV K=V` | export prefix on later layers only; never the host |
70
+ | `USER u` | `become_user:` on later tasks |
71
+ | `WORKDIR d` | directory task + `chdir:` on later tasks |
72
+ | `FROM` `ARG` rest | comments; ARG expands, `--arg` overrides |
73
+
74
+ Output keeps one `# Machinefile:<line>: <full line>` comment and a blank
75
+ line per source instruction, so the playbook reads against the original;
76
+ comments never enter hashes. Nothing is hoisted or reordered: an apt
77
+ install stays below the apt source it needs.
78
+
79
+ The playbook is a build product: it references context paths and checksums,
80
+ so plan and repo travel together, regenerate after `git clone`, gitignore
81
+ it. Stamps hash layer text, so pin URLs whose content matters. `USER foo`
82
+ presupposes the user exists.
83
+
84
+ uv run pytest tests/ # examples/ double as fixtures
85
+
86
+ Why not bootc: great format, forces an immutable OS. Why not cloud-init:
87
+ unreliable reruns outside first boot, Ubuntu-flavored. Here the format is
88
+ Docker's, the executor is Ansible's.
@@ -0,0 +1,68 @@
1
+ # machinefile
2
+
3
+ Describe a system setup as a `Machinefile` (Dockerfile syntax), compile it
4
+ to an Ansible playbook, apply it locally or over ssh. Docker's layer cache
5
+ on a mutable machine, with no custom executor.
6
+
7
+ ## Hello world
8
+
9
+ Create `Machinefile` (`chmod +x` optional), then `./Machinefile apply`:
10
+
11
+ ```
12
+ #!/usr/bin/env -S uvx --from machinefile[ansible] machine
13
+ FROM ubuntu
14
+ RUN echo hello > /tmp/hello
15
+ RUN wc -c < /tmp/hello
16
+ ```
17
+
18
+ The only prerequisite is [uv](https://docs.astral.sh/uv/): the shebang lets
19
+ uvx fetch the tool ephemerally (no install step); the `[ansible]` extra
20
+ adds ansible-core, the executor. Bare `./Machinefile`
21
+ prints help; `./Machinefile plan|apply|reset` do the work. Re-apply is a
22
+ no-op; re-runs resume at your edit. `./Machinefile reset` forgets this
23
+ file's applied layers so the next apply replays everything.
24
+
25
+ Install the command permanently (optional):
26
+
27
+ uv tool install 'machinefile[ansible]' # or pipx
28
+
29
+ ## Commands
30
+
31
+ machine apply Machinefile [user@host] # local, or ssh (python3 on target)
32
+ machine plan Machinefile [ctx] -o pb.yaml [--arg K=V]...
33
+ machine reset Machinefile [user@host] # forget this file's applied layers
34
+ machine apply Machinefile -v # show task output (-vv, -vvv…)
35
+ machine apply Machinefile -- --check # passthrough to ansible-playbook
36
+
37
+ Re-apply resumes at your edit: unchanged layers skip, appended layers run
38
+ alone, a failed layer retries with its upstream still skipped. That is the
39
+ hash chain (`sha256(parent + layer)`, markers in `/var/lib/machinefile/`),
40
+ expressed as Ansible `creates:` guards on paired work/marker tasks.
41
+
42
+ | Instruction | Becomes |
43
+ |-----------------------|-----------------------------------------------------|
44
+ | `RUN cmd` | `shell` + stamp pair (heredocs verbatim, ENV as export prefix) |
45
+ | `COPY src dest` | `copy` with `checksum:` (native idempotency) |
46
+ | `COPY dir dest` | stamp pair: tree-hash check + `cp -a` |
47
+ | `ADD url dest` | `get_url` + stamp pair |
48
+ | `ADD archive dest` | stamp pair: `tar -xf` |
49
+ | `ENV K=V` | export prefix on later layers only; never the host |
50
+ | `USER u` | `become_user:` on later tasks |
51
+ | `WORKDIR d` | directory task + `chdir:` on later tasks |
52
+ | `FROM` `ARG` rest | comments; ARG expands, `--arg` overrides |
53
+
54
+ Output keeps one `# Machinefile:<line>: <full line>` comment and a blank
55
+ line per source instruction, so the playbook reads against the original;
56
+ comments never enter hashes. Nothing is hoisted or reordered: an apt
57
+ install stays below the apt source it needs.
58
+
59
+ The playbook is a build product: it references context paths and checksums,
60
+ so plan and repo travel together, regenerate after `git clone`, gitignore
61
+ it. Stamps hash layer text, so pin URLs whose content matters. `USER foo`
62
+ presupposes the user exists.
63
+
64
+ uv run pytest tests/ # examples/ double as fixtures
65
+
66
+ Why not bootc: great format, forces an immutable OS. Why not cloud-init:
67
+ unreliable reruns outside first boot, Ubuntu-flavored. Here the format is
68
+ Docker's, the executor is Ansible's.
@@ -0,0 +1,52 @@
1
+ [project]
2
+ name = "machinefile"
3
+ version = "0.1.4"
4
+ description = "Compile a Machinefile (Dockerfile-syntax) into an Ansible playbook with Docker layer-cache semantics"
5
+ readme = "README.md"
6
+ requires-python = ">=3.13"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ keywords = [
10
+ "machinefile",
11
+ "ansible",
12
+ "dockerfile",
13
+ "provisioning",
14
+ "reproducible",
15
+ ]
16
+ classifiers = [
17
+ "Environment :: Console",
18
+ "Intended Audience :: System Administrators",
19
+ "Operating System :: POSIX :: Linux",
20
+ "Programming Language :: Python :: 3",
21
+ "Topic :: System :: Installation/Setup",
22
+ "Topic :: System :: Systems Administration",
23
+ ]
24
+ dependencies = [
25
+ "pyyaml>=6.0.3",
26
+ "rich-click>=1.9.9",
27
+ ]
28
+
29
+ [project.optional-dependencies]
30
+ ansible = ["ansible-core>=2.21.5"]
31
+
32
+ [project.scripts]
33
+ machine = "machinefile.cli:main"
34
+
35
+ [dependency-groups]
36
+ dev = [
37
+ "machinefile[ansible]",
38
+ "pytest>=9.1.1",
39
+ ]
40
+
41
+ [build-system]
42
+ requires = ["uv_build>=0.13"]
43
+ build-backend = "uv_build"
44
+
45
+ [tool.bumpversion]
46
+ current_version = "0.1.4"
47
+ commit = true
48
+ tag = true
49
+ tag_name = "v{new_version}"
50
+
51
+ [[tool.bumpversion.files]]
52
+ filename = "src/machinefile/__init__.py"
@@ -0,0 +1,47 @@
1
+ [project]
2
+ name = "machinefile"
3
+ version = "0.1.4"
4
+ description = "Compile a Machinefile (Dockerfile-syntax) into an Ansible playbook with Docker layer-cache semantics"
5
+ readme = "README.md"
6
+ requires-python = ">=3.13"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ keywords = ["machinefile", "ansible", "dockerfile", "provisioning", "reproducible"]
10
+ classifiers = [
11
+ "Environment :: Console",
12
+ "Intended Audience :: System Administrators",
13
+ "Operating System :: POSIX :: Linux",
14
+ "Programming Language :: Python :: 3",
15
+ "Topic :: System :: Installation/Setup",
16
+ "Topic :: System :: Systems Administration",
17
+ ]
18
+ dependencies = [
19
+ "pyyaml>=6.0.3",
20
+ "rich-click>=1.9.9",
21
+ ]
22
+
23
+ [project.optional-dependencies]
24
+ # apply/reset shell out to ansible-playbook; plan works without it
25
+ ansible = ["ansible-core>=2.21.5"]
26
+
27
+ [project.scripts]
28
+ machine = "machinefile.cli:main"
29
+
30
+ [dependency-groups]
31
+ dev = [
32
+ "machinefile[ansible]",
33
+ "pytest>=9.1.1",
34
+ ]
35
+
36
+ [build-system]
37
+ requires = ["uv_build>=0.13"]
38
+ build-backend = "uv_build"
39
+
40
+ [tool.bumpversion]
41
+ current_version = "0.1.4"
42
+ commit = true
43
+ tag = true
44
+ tag_name = "v{new_version}"
45
+
46
+ [[tool.bumpversion.files]]
47
+ filename = "src/machinefile/__init__.py"
@@ -0,0 +1,3 @@
1
+ """machinefile: compile a Machinefile (Dockerfile-syntax) into an Ansible playbook."""
2
+
3
+ __version__ = "0.1.4"
@@ -0,0 +1 @@
1
+ """Ships the Ansible stdout callback; loaded by path, not imported."""
@@ -0,0 +1,98 @@
1
+ """Docker-like stdout callback: one Machinefile line, then its output.
2
+
3
+ Activated by `machine apply` (ANSIBLE_CALLBACK_PLUGINS +
4
+ ANSIBLE_STDOUT_CALLBACK=machinefile). Format rules:
5
+
6
+ - non-noise task start -> '# Machinefile:<line>: <instruction>'
7
+ - ok -> the command's stdout/stderr, if any
8
+ - skipped -> 'cached' (layer marker already present)
9
+ - failed -> stdout/stderr + the error message
10
+ - marker/bootstrap tasks and all ansible banners -> silent
11
+ - stats -> one summary line
12
+
13
+ True byte-streaming during a command is not available: ansible
14
+ captures module output and delivers it on task completion. Verbose
15
+ ansible internals: `machine apply -vvv` (disables this callback).
16
+ """
17
+
18
+ from ansible.plugins.callback import CallbackBase
19
+
20
+ BOOTSTRAP = "ensure stamp dir"
21
+
22
+ # The callback runs inside the ansible-playbook process (usually the
23
+ # same venv, where rich is present via our rich-click dep); degrade to
24
+ # plain text when it is not (e.g. system ansible on PATH).
25
+ try:
26
+ from rich.console import Console
27
+ _console = Console(highlight=False)
28
+ except ImportError:
29
+ _console = None
30
+
31
+
32
+ class CallbackModule(CallbackBase):
33
+ CALLBACK_VERSION = 2.0
34
+ CALLBACK_TYPE = "stdout"
35
+ CALLBACK_NAME = "machinefile_stdout" # file name = plugin name for ansible
36
+
37
+ def __init__(self):
38
+ super().__init__()
39
+ self._quiet = False
40
+
41
+ @staticmethod
42
+ def _out(text):
43
+ print(text, flush=True)
44
+
45
+ @staticmethod
46
+ def _label(text):
47
+ # source annotation, styled; markup=False: Machinefile lines may
48
+ # contain literal [brackets]
49
+ if _console is not None:
50
+ _console.print(text, style="bold cyan", markup=False)
51
+ else:
52
+ print(text, flush=True)
53
+
54
+ def v2_playbook_on_task_start(self, task, is_conditional):
55
+ name = task.get_name()
56
+ self._quiet = name.startswith("mark:") or name == BOOTSTRAP
57
+ if self._quiet:
58
+ return
59
+ src = task.vars.get("_mf_src") or name
60
+ self._label(f"# {src}")
61
+
62
+ def v2_runner_on_ok(self, result):
63
+ if self._quiet:
64
+ return
65
+ r = result._result
66
+ # `creates:` skips arrive as ok (changed=False) with the reason in
67
+ # stdout ('skipped, since <marker> exists'); docker says it better
68
+ # with one word
69
+ if (r.get("skipped")
70
+ or not r.get("changed")
71
+ and (str(r.get("stdout", "")).startswith("skipped, since ")
72
+ or str(r.get("msg", "")).startswith("Did not run command"))):
73
+ self._out("cached")
74
+ return
75
+ for key in ("stdout", "stderr"):
76
+ text = (r.get(key) or "").strip()
77
+ if text:
78
+ self._out(text)
79
+
80
+ def v2_runner_on_skipped(self, result):
81
+ if not self._quiet:
82
+ self._out("cached")
83
+
84
+ def v2_runner_on_failed(self, result, ignore_errors=False):
85
+ r = result._result
86
+ for key in ("stdout", "stderr"):
87
+ text = (r.get(key) or "").strip()
88
+ if text:
89
+ self._out(text)
90
+ msg = r.get("msg")
91
+ if msg:
92
+ self._out(f"error: {msg}")
93
+
94
+ def v2_playbook_on_stats(self, stats):
95
+ if stats.dark or any(stats.failures.values()):
96
+ self._out("apply FAILED")
97
+ else:
98
+ self._out(f"apply done: {len(stats.changed or {})} host(s) changed")
@@ -0,0 +1,210 @@
1
+ """machine: the command-line surface.
2
+
3
+ Usage:
4
+ machine plan Machinefile [-o playbook.yaml] [--context DIR] [--arg K=V]...
5
+ machine apply Machinefile [user@host] [--context DIR] [--arg K=V]... [-- <ansible args>]
6
+
7
+ Parsing lives in parser.py, the Ansible backend (task mapping, hash
8
+ chain, playbook rendering, execution, stamp removal) in
9
+ runner_ansible.py. The playbook is a build product (gitignore it): it
10
+ references context file paths and checksums, so plan and repo travel
11
+ together.
12
+ """
13
+
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ import click
18
+ import rich_click as rc
19
+
20
+ from .runner_ansible import (ansible_env, build_ansible_command,
21
+ compile_tasks, find_ansible, remove_stamps,
22
+ render_playbook, run_command)
23
+
24
+
25
+ @rc.group()
26
+ def cli():
27
+ """Compile a Machinefile (Dockerfile-syntax) and apply it via Ansible."""
28
+
29
+
30
+ # Shared verb-level flag (each command takes it after its name; click
31
+ # cannot inherit group options to positions after the verb).
32
+ verbose_opt = rc.option(
33
+ "-v",
34
+ "--verbose",
35
+ count=True,
36
+ help="Verbose: apply forwards to ansible-playbook, "
37
+ "plan/reset report state (repeat: -vv).",
38
+ )
39
+
40
+
41
+ def parse_build_args(items: tuple[str, ...]) -> dict[str, str]:
42
+ out: dict[str, str] = {}
43
+ for item in items:
44
+ key, _, value = item.partition("=")
45
+ out[key] = value
46
+ return out
47
+
48
+
49
+ @cli.command("plan")
50
+ @rc.argument("machinefile", type=rc.Path(exists=True, dir_okay=False, path_type=Path))
51
+ @rc.argument("context_dir", required=False, default=None,
52
+ type=rc.Path(exists=True, file_okay=False, path_type=Path),
53
+ help="Build context (default: Machinefile's dir).")
54
+ @rc.option("-o", "--output", type=rc.Path(path_type=Path), default=None,
55
+ help="Write here instead of stdout.")
56
+ @rc.option("-c", "--context", "context_opt",
57
+ type=rc.Path(exists=True, file_okay=False, path_type=Path),
58
+ default=None, help="Build context (same as positional, pick one).")
59
+ @rc.option("--arg", "build_args", multiple=True, metavar="K=V",
60
+ help="Override ARG values (repeatable).")
61
+ @verbose_opt
62
+ def plan_cmd(
63
+ machinefile: Path,
64
+ context_dir: Path | None,
65
+ output: Path | None,
66
+ context_opt: Path | None,
67
+ build_args: tuple[str, ...],
68
+ verbose: int,
69
+ ):
70
+ """Emit the Ansible playbook for a Machinefile."""
71
+ if context_dir and context_opt:
72
+ sys.exit("error: context given twice")
73
+ context = context_opt or context_dir or machinefile.parent
74
+ tasks, comments = compile_tasks(machinefile, context, parse_build_args(build_args))
75
+ text, _ = render_playbook(tasks, comments, machinefile)
76
+ if verbose:
77
+ rc.echo(f"plan: {len(tasks)} tasks from {machinefile}", err=True)
78
+ if output:
79
+ output.write_text(text)
80
+ rc.echo(f"wrote {output}")
81
+ else:
82
+ sys.stdout.write(text)
83
+
84
+
85
+ @cli.command("apply", context_settings={"ignore_unknown_options": True})
86
+ @rc.argument("machinefile", type=rc.Path(exists=True, dir_okay=False, path_type=Path))
87
+ @rc.argument("target", required=False, default=None,
88
+ help="user@host or host (default: local machine).")
89
+ @rc.option("-c", "--context", type=rc.Path(exists=True, file_okay=False, path_type=Path),
90
+ default=None, help="Build context (default: Machinefile's dir).")
91
+ @rc.option("--arg", "build_args", multiple=True, metavar="K=V",
92
+ help="Override ARG values (repeatable).")
93
+ @verbose_opt
94
+ @rc.argument("ansible_args", nargs=-1, type=click.UNPROCESSED)
95
+ def apply_cmd(
96
+ machinefile: Path,
97
+ target: str | None,
98
+ context: Path | None,
99
+ build_args: tuple[str, ...],
100
+ verbose: int,
101
+ ansible_args: tuple[str, ...],
102
+ ):
103
+ """Compile and run the playbook via ansible-playbook.
104
+
105
+ Local by default (--connection local); give a target for plain ssh
106
+ transport (python3 required on the remote, nothing else). Extra args
107
+ after `--` pass through to ansible-playbook (e.g. --check, --diff).
108
+ """
109
+ # click binds the first post-`--` token to the optional target even
110
+ # when it is an option (`apply M -- --check`); a host never starts
111
+ # with '-', so hand it to the passthrough instead.
112
+ if target and target.startswith("-"):
113
+ ansible_args = (target, *ansible_args)
114
+ target = None
115
+
116
+ # ansible may be missing without the [ansible] extra
117
+ ansible = find_ansible()
118
+ if ansible is None:
119
+ rc.secho(
120
+ "ansible-playbook not found. Install `ansible-core` or the extra 'machinefile[ansible]'",
121
+ err=True,
122
+ )
123
+ sys.exit(1)
124
+ context = context or machinefile.parent
125
+ tasks, comments = compile_tasks(machinefile, context, parse_build_args(build_args))
126
+ text, _ = render_playbook(tasks, comments, machinefile)
127
+ plan_path = machinefile.parent / (machinefile.name + ".ansible.yaml")
128
+ plan_path.write_text(text)
129
+ cmd = build_ansible_command(ansible, plan_path, target, verbose,
130
+ list(ansible_args))
131
+ rc.echo(f"$ {' '.join(cmd)}", err=True)
132
+ sys.exit(run_command(cmd, ansible_env(verbose)))
133
+
134
+
135
+ @cli.command("reset")
136
+ @rc.argument("machinefile", type=rc.Path(exists=True, dir_okay=False, path_type=Path))
137
+ @rc.argument(
138
+ "target",
139
+ required=False,
140
+ default=None,
141
+ help="user@host or host (default: local machine).",
142
+ )
143
+ @rc.option(
144
+ "-c",
145
+ "--context",
146
+ type=rc.Path(exists=True, file_okay=False, path_type=Path),
147
+ default=None,
148
+ help="Build context (default: Machinefile's dir).",
149
+ )
150
+ @rc.option(
151
+ "--arg",
152
+ "build_args",
153
+ multiple=True,
154
+ metavar="K=V",
155
+ help="Override ARG values (must match how it was applied).",
156
+ )
157
+ @verbose_opt
158
+ def reset_cmd(
159
+ machinefile: Path,
160
+ target: str | None,
161
+ context: Path | None,
162
+ build_args: tuple[str, ...],
163
+ verbose: int,
164
+ ):
165
+ """Forget which layers of THIS Machinefile ran (delete its stamps).
166
+
167
+ Recomputes the chain and removes exactly those markers, leaving other
168
+ Machinefiles' stamps on the same host untouched. Next apply re-runs
169
+ every layer. Convergent tasks (COPY) need no reset; they re-converge.
170
+ """
171
+ context = context or machinefile.parent
172
+ tasks, comments = compile_tasks(machinefile, context, parse_build_args(build_args))
173
+ _, stamps = render_playbook(tasks, comments, machinefile)
174
+ if verbose:
175
+ rc.echo(f"reset: {len(stamps)} stamps of {machinefile}", err=True)
176
+ remaining, escalated = remove_stamps(stamps, target)
177
+ if remaining:
178
+ for m in remaining:
179
+ rc.echo(m, err=True)
180
+ rc.secho(f"reset FAILED: {len(remaining)} of {len(stamps)} markers "
181
+ "remain", err=True)
182
+ sys.exit(1)
183
+ rc.secho(f"reset: {len(stamps)} markers removed"
184
+ + (" (via sudo)" if escalated else ""), err=True)
185
+
186
+
187
+ def main():
188
+ # `#!` exec puts the filename first: `./Machinefile plan` arrives as
189
+ # [<file>, plan, ...extras]. Fixing here by de-swapping before
190
+ # calling Click:
191
+ # ./Machinefile -> bare: calls --help instead
192
+ # ./Machinefile verb ... -> swap file and verb (verb goes first)
193
+ # ./Machinefile --help -> file moves to the end
194
+ # Standard `machine plan Machinefile` works as before.
195
+ argv = sys.argv[1:]
196
+ machinefile = None
197
+ if argv and Path(argv[0]).is_file() and argv[0] not in cli.commands:
198
+ machinefile = argv.pop(0)
199
+
200
+ if len(argv) == 0:
201
+ argv = ["--help"]
202
+
203
+ if machinefile:
204
+ argv.insert(1, machinefile)
205
+
206
+ cli(argv)
207
+
208
+
209
+ if __name__ == "__main__":
210
+ main()
@@ -0,0 +1,125 @@
1
+ """Machinefile text -> instruction dicts.
2
+
3
+ Dockerfile syntax: backslash continuations, heredocs (<<, <<- with
4
+ tab-stripped terminators, quoted delimiters), comment accumulation for
5
+ annotations, $VAR expansion against declared ARG/ENV, and the
6
+ per-instruction argument forms (ENV pairs, COPY/ADD lists). Instruction
7
+ *mapping* to tasks lives in runner_ansible.py.
8
+ """
9
+
10
+ import re
11
+ import shlex
12
+ import sys
13
+
14
+ import yaml
15
+
16
+ HEREDOC_RE = re.compile(r"<<(-?)(['\"]?)(\w+)\2")
17
+
18
+
19
+ def expand_vars(text: str, known: dict[str, str]) -> str:
20
+ """Expand $VAR/${VAR} only against declared ARG/ENV values.
21
+
22
+ Unknown $refs are left intact for the apply-time shell (a Machinefile
23
+ targeting a new machine must not bake in the compiling machine's
24
+ environment). Docker likewise resolves RUN bodies against the image's
25
+ env, not the builder's host env.
26
+ """
27
+
28
+ def sub(m: re.Match) -> str:
29
+ key = m.group(1) or m.group(2)
30
+ return known.get(key) or m.group(0) or ""
31
+
32
+ return re.sub(r"\$\{(\w+)\}|\$(\w+)", sub, text)
33
+
34
+
35
+ def parse_env(arg: str) -> list[tuple[str, str]]:
36
+ """Support both 'ENV K=V [K2=V2]' and legacy 'ENV K V'."""
37
+ parts = arg.split(None, 1)
38
+ if len(parts) == 1:
39
+ parts = [parts[0], ""]
40
+ if "=" in parts[0]:
41
+ return [
42
+ (m.group(1), m.group(2).strip("\"'"))
43
+ for m in re.finditer(r"(\w+)=(\"[^\"]*\"|'[^']*'|[^\s]+)", arg)
44
+ ]
45
+ return [(parts[0], parts[1].strip().strip("\"'"))]
46
+
47
+
48
+ def copy_add_args(arg: str) -> tuple[list[str], str]:
49
+ """Split COPY/ADD argument into (sources, dest), honoring flags and JSON form."""
50
+ if arg.strip().startswith("["):
51
+ items = yaml.safe_load(arg)
52
+ else:
53
+ items = shlex.split(arg)
54
+ items = [i for i in items if not i.startswith("--")]
55
+ if len(items) < 2:
56
+ sys.exit(f"error: invalid COPY/ADD: {arg!r}")
57
+ return items[:-1], items[-1]
58
+
59
+
60
+ def _collapse(lines: list[str]) -> str:
61
+ return " ".join(l.rstrip("\\").strip() for l in lines)
62
+
63
+
64
+ def parse_lines(text: str) -> list[dict]:
65
+ """Parse Machinefile text into instruction dicts:
66
+ {'instruction', 'value', 'heredoc', 'heredoc_quoted', 'line', 'note'}.
67
+
68
+ 'note' is the display-only annotation: comment lines directly above
69
+ plus the collapsed instruction line; notes never enter step hashes.
70
+ """
71
+ out: list[dict] = []
72
+ pending: list[str] = []
73
+ lines = text.splitlines()
74
+ i, n = 0, len(lines)
75
+ while i < n:
76
+ lineno = i + 1
77
+ line = lines[i].strip()
78
+ i += 1
79
+ if not line:
80
+ continue
81
+ if line.startswith("#"):
82
+ pending.append(line)
83
+ continue
84
+ joined = [line]
85
+ while line.endswith("\\") and i < n:
86
+ line = lines[i].strip()
87
+ i += 1
88
+ joined.append(line)
89
+ collapsed = _collapse(joined)
90
+ parts = collapsed.split(None, 1)
91
+ instr = parts[0].upper() if parts else ""
92
+ value = parts[1] if len(parts) > 1 else ""
93
+ heredoc = quoted = False
94
+ m = HEREDOC_RE.search(value)
95
+ if m:
96
+ heredoc, quoted = True, bool(m.group(2))
97
+ dash = m.group(1) == "-"
98
+ head = value[: m.start()].rstrip()
99
+ body: list[str] = []
100
+ while i < n:
101
+ raw = lines[i]
102
+ i += 1
103
+ term = raw.strip() if dash else raw.rstrip()
104
+ if term == m.group(3):
105
+ break
106
+ body.append(raw[1:] if dash and raw.startswith("\t") else raw)
107
+ value = (head + "\n" if head else "") + "\n".join(body)
108
+ out.append({
109
+ "instruction": instr,
110
+ "value": value,
111
+ "heredoc": heredoc,
112
+ "heredoc_quoted": quoted,
113
+ "line": lineno,
114
+ "note": pending + [collapsed],
115
+ })
116
+ pending = []
117
+ return out
118
+
119
+
120
+ def note_name(note: list[str]) -> str:
121
+ """Task name from source annotation: comments then the instruction."""
122
+ comments = [n.lstrip("# ").rstrip() for n in note[:-1]]
123
+ instr_line = note[-1]
124
+ parts = ([f"[{c}]" for c in comments] + [instr_line]) if comments else [instr_line]
125
+ return " ".join(parts)
@@ -0,0 +1,354 @@
1
+ """The Ansible backend: Machinefile instructions -> tasks -> playbook -> execution.
2
+
3
+ Mapping (Dockerfile instruction -> playbook task):
4
+ RUN <cmd> -> ansible.builtin.shell (stamp pair); heredocs pass
5
+ verbatim in a YAML block scalar; env + chdir per task
6
+ COPY file -> ansible.builtin.copy with checksum: (drift-aware)
7
+ COPY dir -> stamped shell: tree sha256 check + cp -a
8
+ ADD url dest -> ansible.builtin.get_url (stamp pair)
9
+ ADD archive -> stamped shell: tar -xf into dest
10
+ ENV K=V -> NOT persisted to the host: attached as `environment:`
11
+ to subsequent tasks (Docker layer scope)
12
+ USER u -> become_user on subsequent tasks
13
+ WORKDIR d -> file: state=directory; chdir on subsequent tasks
14
+ ARG -> compile-time value for $ expansion; commented
15
+ FROM / others -> comments (informational)
16
+
17
+ Execution, privilege, transport are Ansible's job:
18
+ - local: machine apply Mf (ansible-playbook --connection local)
19
+ - remote: machine apply Mf user@host (plain ssh, python3 on target)
20
+ - USER u -> become_user: u (no sudo-in-bash quoting anywhere)
21
+
22
+ Docker layer semantics, enforced by Ansible rather than hand-rolled bash:
23
+
24
+ - every instruction becomes its own task, never reordered or merged;
25
+ - imperative RUN layers run at most once: the layer is paired with
26
+ `creates: /var/lib/machinefile/<chain-hash>` and a following
27
+ marker task (marker only after success);
28
+ - convergent instructions (file COPY, get_url, directory) have native
29
+ Ansible idempotency and need no marker;
30
+ - the hash chain mirrors Docker: editing a layer (or its COPY'd bytes,
31
+ carried as `checksum:`) changes its hash and every downstream hash,
32
+ so re-applying resumes exactly at the edit point, and appending
33
+ layers never invalidates the past.
34
+
35
+ Reset for a full re-apply: rm -rf /var/lib/machinefile
36
+ """
37
+
38
+ import hashlib
39
+ import os
40
+ import re
41
+ import shlex
42
+ import shutil
43
+ import subprocess
44
+ import sys
45
+ from pathlib import Path
46
+
47
+ import yaml
48
+
49
+ from .parser import copy_add_args, expand_vars, note_name, parse_env, parse_lines
50
+
51
+ STAMP_DIR = os.environ.get("MACHINEFILE_STAMP_DIR", "/var/lib/machinefile")
52
+
53
+ TARBALL_RE = re.compile(r"\.(tar|tar\.gz|tgz|tar\.bz2|tar\.xz)$", re.IGNORECASE)
54
+
55
+
56
+ def env_assign(k: str, v: str) -> str:
57
+ """Render K=V for an apply-time `export`, preserving literal $refs.
58
+
59
+ Ansible's `environment:` sets literal strings (no shell re-expansion),
60
+ so ENV values referencing runtime vars (PATH=...:$PATH) must be carried
61
+ into the shell command itself. shlex.quote would single-quote and freeze
62
+ $refs; use double quotes with the few active characters escaped. Values
63
+ come from the (trusted) Machinefile; a hostile Machinefile is arbitrary
64
+ code anyway via RUN.
65
+ """
66
+ if not v or any(c.isspace() or c in ';&|<>()"\\`' for c in v):
67
+ v = v.replace("\\", "\\\\").replace('"', '\\"').replace("`", "\\`")
68
+ return f'{k}="{v}"'
69
+ return f"{k}={v}"
70
+
71
+
72
+ def file_sha256(p: Path) -> str:
73
+ return hashlib.sha256(p.read_bytes()).hexdigest()
74
+
75
+
76
+ def tree_sha256(d: Path) -> str:
77
+ """sha256 over file contents in sorted relative-path order."""
78
+ h = hashlib.sha256()
79
+ for p in sorted(d.rglob("*"), key=lambda p: str(p.relative_to(d))):
80
+ if p.is_file():
81
+ h.update(p.read_bytes())
82
+ return h.hexdigest()
83
+
84
+
85
+ def compile_tasks(machinefile: Path, context: Path,
86
+ build_args: dict[str, str] | None = None) -> tuple[list[dict], list[str]]:
87
+ """Return (ordered playbook task dicts, header comments).
88
+
89
+ Task dicts carry the final module args plus stamp metadata; a task with
90
+ stamp=True gets `creates:` + a paired touch marker at render time. The
91
+ hash chain is computed over each layer's serialized module args, so any
92
+ edit (instruction text or COPY'd bytes via checksum) cascades
93
+ downstream exactly like Docker.
94
+ """
95
+ structure = parse_lines(machinefile.read_text())
96
+
97
+ tasks: list[dict] = []
98
+ comments: list[str] = []
99
+ known: dict[str, str] = dict(build_args or {}) # --arg seeds first
100
+ env: dict[str, str] = {}
101
+ user = ""
102
+ workdir = ""
103
+
104
+ def add(module: str, args: dict, entry: dict, stamp: bool = False):
105
+ if env and module == "ansible.builtin.shell":
106
+ # Layer env via in-command exports (see env_assign): the values
107
+ # must survive shell expansion at apply time, and COPY-style
108
+ # modules carry no shell at all (matches Docker).
109
+ prefix = " && ".join(f"export {env_assign(k, v)}" for k, v in env.items())
110
+ args = {**args, "cmd": prefix + "\n" + args["cmd"]}
111
+ task: dict = {"name": note_name(entry["note"])}
112
+ task["_src"] = (entry["line"], entry["note"][-1])
113
+ if stamp:
114
+ task["_stamp"] = True
115
+ task[module] = args
116
+ if user and user != "root":
117
+ task["become_user"] = user
118
+ if module in ("ansible.builtin.shell", "ansible.builtin.command") and workdir:
119
+ task["args"] = {"chdir": workdir}
120
+ tasks.append(task)
121
+
122
+ def emit_copy(src: str, dest: str, entry: dict):
123
+ f = context / src
124
+ if not f.exists():
125
+ sys.exit(f"error: source not found in context: {f}")
126
+ dest = expand_vars(dest, known)
127
+ if dest.endswith("/"):
128
+ dest = dest + f.name
129
+ if f.is_dir():
130
+ # No native recursive-copy module: keep a stamped shell with a
131
+ # tree-hash guard (same definition as tree_sha256: sorted
132
+ # relative paths, concatenated contents).
133
+ h = tree_sha256(f)
134
+ src_q, dest_q = shlex.quote(str(f)), shlex.quote(dest)
135
+ add("ansible.builtin.shell", {
136
+ "cmd": (
137
+ f'test "$(cd {src_q} && find . -type f -print0 | LC_ALL=C sort -z '
138
+ f"| xargs -0 -r cat | sha256sum | cut -d' ' -f1)\" = {h} "
139
+ f"&& install -d {dest_q} && cp -a {src_q}/. {dest_q}"
140
+ )
141
+ }, entry, stamp=True)
142
+ return
143
+ # Native convergent copy: checksum binds the layer hash to the
144
+ # source bytes (content edit = Docker COPY cache invalidation),
145
+ # and remote transfers verify integrity with it.
146
+ mode = f"{f.stat().st_mode & 0o777:04o}"
147
+ add("ansible.builtin.copy", {
148
+ "src": str(f),
149
+ "dest": dest,
150
+ "mode": mode,
151
+ "checksum": f"sha256:{file_sha256(f)}",
152
+ }, entry)
153
+
154
+ for entry in structure:
155
+ instr, arg = entry["instruction"], entry["value"]
156
+ if instr == "FROM":
157
+ comments.append(f"base image intent: FROM {arg}")
158
+ elif instr == "ARG":
159
+ key, _, default = arg.partition("=")
160
+ key = key.strip()
161
+ if key not in (build_args or {}):
162
+ known[key] = expand_vars(default.strip().strip("\"'"), known)
163
+ comments.append(f"ARG {arg}")
164
+ elif instr == "RUN":
165
+ cmd = arg if entry["heredoc_quoted"] else expand_vars(arg, known)
166
+ add("ansible.builtin.shell", {"cmd": cmd}, entry, stamp=True)
167
+ elif instr == "COPY":
168
+ srcs, dest = copy_add_args(arg)
169
+ for src in srcs:
170
+ emit_copy(src, dest, entry)
171
+ elif instr == "ADD":
172
+ srcs, dest = copy_add_args(arg)
173
+ for src in srcs:
174
+ src_x = expand_vars(src, known)
175
+ dest_x = expand_vars(dest, known)
176
+ if src_x.startswith(("http://", "https://")):
177
+ add("ansible.builtin.get_url", {"url": src_x, "dest": dest_x},
178
+ entry, stamp=True)
179
+ elif TARBALL_RE.search(src_x):
180
+ src_q, dest_q = shlex.quote(str(context / src_x)), shlex.quote(dest_x)
181
+ add("ansible.builtin.shell", {
182
+ "cmd": f"install -d {dest_q} && tar -xf {src_q} -C {dest_q}"
183
+ }, entry, stamp=True)
184
+ else:
185
+ emit_copy(src, dest, entry)
186
+ elif instr == "ENV":
187
+ # Layer-scoped (Docker semantics): attached as task
188
+ # `environment:` for subsequent layers, never persisted to the
189
+ # host. Want a permanent env var? Write profile.d via COPY/RUN.
190
+ for key, value in parse_env(arg):
191
+ value = expand_vars(value, known)
192
+ known[key] = value
193
+ env[key] = value
194
+ elif instr == "USER":
195
+ user = expand_vars(arg, known).strip()
196
+ elif instr == "WORKDIR":
197
+ workdir = arg.strip()
198
+ add("ansible.builtin.file",
199
+ {"path": workdir, "state": "directory"}, entry)
200
+ else:
201
+ comments.append(f"ignored: {instr} {arg}")
202
+
203
+ return tasks, comments
204
+
205
+
206
+ def render_playbook(
207
+ tasks: list[dict], comments: list[str], machinefile: Path | None = None
208
+ ) -> tuple[str, list[str]]:
209
+ """Serialize tasks into a playbook, resolving stamp pairs.
210
+
211
+ Stamped layers become two tasks: the work (guarded by `creates:` on the
212
+ chain-hash marker) and a `touch` of that marker. A failed layer aborts
213
+ before its touch, so it retries on the next apply; an unchanged plan
214
+ leaves every marker in place and Ansible skips every layer.
215
+ """
216
+
217
+ markers: list[str] = []
218
+
219
+ def flush(out: list[tuple], task: dict):
220
+ src = task.pop("_src", None)
221
+ stamp = task.pop("_stamp", None)
222
+ args = next(v for k, v in list(task.items()) if k not in
223
+ ("name", "environment", "become_user"))
224
+ module = next(k for k in task if k.startswith("ansible.builtin."))
225
+ layer = yaml.safe_dump({module: args}, sort_keys=True, width=10**6)
226
+ nonlocal chain
227
+ chain = hashlib.sha256(f"{chain}\n{layer}".encode()).hexdigest()[:16]
228
+ marker = f"{STAMP_DIR}/{chain}"
229
+ if stamp:
230
+ markers.append(marker)
231
+ task.setdefault("args", {})["creates"] = marker
232
+ out.append((src, task))
233
+ # Marker as command+creates: skipped when present, runs `touch`
234
+ # once when absent. (The file module has no `creates`, and its
235
+ # state:touch re-reports changed on every pass.)
236
+ out.append((src, {"name": f"mark: {task['name']}",
237
+ "ansible.builtin.command": {"cmd": f"touch {marker}"},
238
+ "args": {"creates": marker}}))
239
+ else:
240
+ out.append((src, task))
241
+
242
+ chain = "machinefile-root"
243
+ resolved: list[tuple] = []
244
+ for task in tasks:
245
+ flush(resolved, task)
246
+ if any("creates" in str(t.get("args", "")) for _, t in resolved):
247
+ # convergent bootstrap (never hashed): touch needs the dir
248
+ resolved.insert(0, (None, {"name": "ensure stamp dir",
249
+ "ansible.builtin.file": {"path": STAMP_DIR,
250
+ "state": "directory"}}))
251
+
252
+ header = ["# Generated by machinefile. Build product: do not commit;"]
253
+ if machinefile:
254
+ header[0] = f"# Generated by machinefile from {machinefile}. Build product: do not commit;"
255
+ for c in comments:
256
+ header.append(f"# {c}")
257
+ return _emit(resolved, header), markers
258
+
259
+
260
+ def _emit(items: list[tuple], header: list[str]) -> str:
261
+ """Playbook YAML written task-by-task (safe_dump cannot interleave
262
+ comments/blank lines). Tasks from one Machinefile line form a group:
263
+ one '# Machinefile:<line>: <full line>' comment above the group, one
264
+ blank line after it. Comments never enter the hash chain. Each task
265
+ also carries _mf_src as a variable: the machinefile_stdout callback
266
+ reads it to label output (vars are schema-free, arbitrary task keys
267
+ are not; injection happens post-hash, so the chain is unaffected)."""
268
+ lines = header + ["- hosts: all", " gather_facts: false",
269
+ " become: true", " tasks:"]
270
+ prev = object()
271
+ for src, task in items:
272
+ if src != prev:
273
+ if prev is not object() and src is not None:
274
+ lines.append("") # gap after the previous line's group
275
+ if src is not None:
276
+ lines.append(f" # Machinefile:{src[0]}: {src[1]}")
277
+ if src is not None:
278
+ task = {**task, "vars": {"_mf_src": f"Machinefile:{src[0]}: {src[1]}"}}
279
+ body = yaml.safe_dump(task, default_flow_style=False,
280
+ sort_keys=False, width=10**6, allow_unicode=True)
281
+ body_lines = body.rstrip().splitlines()
282
+ lines.append(" - " + body_lines[0])
283
+ lines.extend(" " + l for l in body_lines[1:])
284
+ prev = src
285
+ return "\n".join(lines) + "\n"
286
+
287
+
288
+ def find_ansible() -> str | None:
289
+ """Locate ansible-playbook: PATH first, then our own venv's bin
290
+ (uv tool install puts the entry point there, not on PATH)."""
291
+ return shutil.which("ansible-playbook") or shutil.which(
292
+ "ansible-playbook", path=os.path.dirname(sys.executable))
293
+
294
+
295
+ def ansible_env(verbose: int) -> dict[str, str]:
296
+ """Environment for ansible-playbook: our docker-like stdout callback,
297
+ unless -vvv asks for raw ansible internals."""
298
+ env = dict(os.environ)
299
+ if verbose < 3:
300
+ env["ANSIBLE_CALLBACK_PLUGINS"] = str(Path(__file__).parent / "callbacks")
301
+ env["ANSIBLE_STDOUT_CALLBACK"] = "machinefile_stdout"
302
+ env.setdefault("ANSIBLE_NOCOWS", "1")
303
+ return env
304
+
305
+
306
+ def run_command(cmd: list[str], env: dict[str, str] | None = None) -> int:
307
+ """Execute a built command (the CLI owns messaging, we own processes)."""
308
+ return subprocess.call(cmd, env=env)
309
+
310
+
311
+ def build_ansible_command(ansible: str, plan_path: Path, target: str | None,
312
+ verbose: int, ansible_args: list[str]) -> list[str]:
313
+ cmd = [ansible, str(plan_path)]
314
+ if target:
315
+ cmd += ["-i", f"{target},"]
316
+ else:
317
+ cmd += ["-i", "localhost,", "--connection", "local"]
318
+ cmd += ["-" + "v" * verbose] if verbose else []
319
+ cmd += ansible_args
320
+ return cmd
321
+
322
+
323
+ def remove_stamps(stamps: list[str], target: str | None) -> tuple[list[str], bool]:
324
+ """Delete marker files; return (still-present markers, escalated).
325
+
326
+ Truth is decided by re-checking existence, not by exit codes: the
327
+ plain pass is expected to fail on /var/lib (markers are root-owned
328
+ after apply's `become`), so it is a quiet probe and sudo runs only
329
+ when it fails (user-owned sandbox dirs stay sudo-free).
330
+ """
331
+ if not stamps:
332
+ return [], False
333
+ quoted = " ".join(shlex.quote(m) for m in stamps)
334
+ # brace the chain: `{ rm && rm; } 2>/dev/null` silences every rm (a
335
+ # bare suffix redirect would cover only the last one)
336
+ rm = "{ " + " && ".join(f"rm -f {p}" for p in stamps) + "; }"
337
+ check = f'for f in {quoted}; do [ -e "$f" ] && echo "$f"; done; true'
338
+ escalated = False
339
+ if target:
340
+ if subprocess.call(["ssh", target, f"{rm} 2>/dev/null"]):
341
+ escalated = True
342
+ subprocess.call(["ssh", "-t", target,
343
+ f"sudo sh -c {shlex.quote(rm)}"])
344
+ out = subprocess.run(["ssh", target, check],
345
+ capture_output=True, text=True)
346
+ else:
347
+ if subprocess.call(["bash", "-c", f"{rm} 2>/dev/null"]):
348
+ escalated = True
349
+ if os.geteuid() != 0:
350
+ subprocess.call(["bash", "-c",
351
+ f"sudo sh -c {shlex.quote(rm)}"])
352
+ out = subprocess.run(["bash", "-c", check],
353
+ capture_output=True, text=True)
354
+ return out.stdout.split(), escalated
@@ -1,11 +0,0 @@
1
- Metadata-Version: 2.3
2
- Name: machinefile
3
- Version: 0.0.1
4
- Summary: Placeholder while the machinefile tool is finalized; see the GitHub repo alanjds/machinefile
5
- Requires-Python: >=3.13
6
- Description-Content-Type: text/markdown
7
-
8
- Name: machinefile
9
-
10
- Placeholder release: the real tool lands in a later version.
11
- Repository: https://github.com/alanjds/machinefile
@@ -1,4 +0,0 @@
1
- Name: machinefile
2
-
3
- Placeholder release: the real tool lands in a later version.
4
- Repository: https://github.com/alanjds/machinefile
@@ -1,10 +0,0 @@
1
- [project]
2
- name = "machinefile"
3
- version = "0.0.1"
4
- description = "Placeholder while the machinefile tool is finalized; see the GitHub repo alanjds/machinefile"
5
- readme = "README.md"
6
- requires-python = ">=3.13"
7
-
8
- [build-system]
9
- requires = ["uv_build>=0.13"]
10
- build-backend = "uv_build"
@@ -1,10 +0,0 @@
1
- [project]
2
- name = "machinefile"
3
- version = "0.0.1"
4
- description = "Placeholder while the machinefile tool is finalized; see the GitHub repo alanjds/machinefile"
5
- readme = "README.md"
6
- requires-python = ">=3.13"
7
-
8
- [build-system]
9
- requires = ["uv_build>=0.13"]
10
- build-backend = "uv_build"
@@ -1 +0,0 @@
1
- __version__ = "0.0.1"