trefoil-cli 0.2.0__tar.gz → 1.0.0__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.

Potentially problematic release.


This version of trefoil-cli might be problematic. Click here for more details.

@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: trefoil-cli
3
- Version: 0.2.0
3
+ Version: 1.0.0
4
4
  Summary: CLI for the trefoil agent server
5
5
  Requires-Python: >=3.10
6
6
  Requires-Dist: pyyaml>=6
@@ -13,6 +13,9 @@ directory of the file that references them.
13
13
 
14
14
  Usage: trefoil <domain> <command> [args]
15
15
 
16
+ trefoil init [DIR] [--example=NAME]
17
+ trefoil update
18
+ trefoil start-backend [--settings=backend.yml] [--port=8080] [-d]
16
19
  trefoil config package path/to/config.yml [-o bundle.json]
17
20
  trefoil config sync [path/to/config.yml] [--server URL]
18
21
  trefoil agents list
@@ -29,8 +32,11 @@ import argparse
29
32
  import base64
30
33
  import getpass
31
34
  import importlib.metadata
35
+ import importlib.util
32
36
  import json
33
37
  import os
38
+ import shutil
39
+ import subprocess
34
40
  import sys
35
41
  import time
36
42
  import urllib.error
@@ -41,6 +47,7 @@ from pathlib import Path
41
47
  import yaml
42
48
 
43
49
  DEFAULT_SERVER = "http://localhost:8080"
50
+ EXAMPLES_API = "https://api.github.com/repos/alto-se/trefoil/contents/examples"
44
51
 
45
52
 
46
53
  class Ref:
@@ -143,6 +150,85 @@ def cmd_package(args):
143
150
  print(out)
144
151
 
145
152
 
153
+ def example_files(url, prefix=""):
154
+ """Yields (relative path, download URL) for every file in an example folder on GitHub."""
155
+ with urllib.request.urlopen(url, timeout=30) as resp:
156
+ entries = json.loads(resp.read())
157
+ for e in entries:
158
+ if e["type"] == "dir":
159
+ yield from example_files(e["url"], prefix + e["name"] + "/")
160
+ elif e["type"] == "file":
161
+ yield prefix + e["name"], e["download_url"]
162
+
163
+
164
+ def cmd_init(args):
165
+ dest = args.dir or Path(args.example)
166
+ if dest.exists() and (not dest.is_dir() or any(dest.iterdir())):
167
+ sys.exit(f"trefoil: {dest} already exists and is not empty")
168
+ try:
169
+ files = list(example_files(f"{EXAMPLES_API}/{quote(args.example)}?ref=main"))
170
+ for rel, url in files:
171
+ with urllib.request.urlopen(url, timeout=30) as resp:
172
+ data = resp.read()
173
+ path = dest / rel
174
+ path.parent.mkdir(parents=True, exist_ok=True)
175
+ path.write_bytes(data)
176
+ except urllib.error.HTTPError as e:
177
+ if e.code == 404:
178
+ sys.exit(f"trefoil: no example named {args.example}")
179
+ sys.exit(f"trefoil: fetching example {args.example}: {e}")
180
+ except urllib.error.URLError as e:
181
+ sys.exit(f"trefoil: cannot fetch example {args.example}: {e.reason}")
182
+ print(f"created {dest} from example {args.example} ({len(files)} files)")
183
+ print(f"next: cd {dest} && trefoil config sync")
184
+
185
+
186
+ def cmd_update(args):
187
+ # An editable install runs straight from a checkout; reinstalling from PyPI would replace it.
188
+ if Path(__file__).with_name("pyproject.toml").exists():
189
+ sys.exit(f"trefoil: running from a source checkout ({Path(__file__).parent}); "
190
+ "pull and run `make cli` instead")
191
+ # uv-created environments (uv tool install, uv venv) have no pip of their own.
192
+ if importlib.util.find_spec("pip"):
193
+ cmd = [sys.executable, "-m", "pip", "install", "--upgrade", "--force-reinstall", "trefoil-cli"]
194
+ elif shutil.which("uv"):
195
+ cmd = ["uv", "pip", "install", "--python", sys.executable, "--upgrade", "--reinstall", "trefoil-cli"]
196
+ else:
197
+ sys.exit("trefoil: neither pip nor uv is available to reinstall trefoil-cli")
198
+ print(f"trefoil {cli_version()}: {' '.join(cmd)}", file=sys.stderr)
199
+ sys.exit(subprocess.run(cmd).returncode)
200
+
201
+
202
+ def cmd_start_backend(args):
203
+ if not shutil.which("docker"):
204
+ sys.exit("trefoil: docker is not installed or not on PATH")
205
+ cmd = ["docker", "run", "--rm", "--name", args.name, "-p", f"{args.port}:8080",
206
+ "-v", "/var/run/docker.sock:/var/run/docker.sock", "-v", f"{args.volume}:/data"]
207
+ if args.settings:
208
+ path = args.settings.resolve()
209
+ if not path.is_file():
210
+ sys.exit(f"trefoil: {args.settings} is not a file")
211
+ mount = f"/trefoil/settings/{path.name}"
212
+ cmd += ["-v", f"{path}:{mount}:ro", "-e", f"TREFOIL_SETTINGS={mount}"]
213
+ # The server resolves env_file against the settings file and fails if
214
+ # it's missing, so mount it where it will look.
215
+ try:
216
+ env_file = (yaml.safe_load(path.read_text()) or {}).get("env_file")
217
+ except (yaml.YAMLError, AttributeError) as e:
218
+ sys.exit(f"trefoil: {args.settings}: {e}")
219
+ if env_file:
220
+ host = (path.parent / env_file).resolve()
221
+ if not host.is_file():
222
+ sys.exit(f"trefoil: env_file {host} (from {args.settings}) not found")
223
+ target = env_file if os.path.isabs(env_file) else os.path.normpath(f"/trefoil/settings/{env_file}")
224
+ cmd += ["-v", f"{host}:{target}:ro"]
225
+ if args.detach:
226
+ cmd.append("-d")
227
+ cmd.append(args.image)
228
+ print(f"trefoil: {' '.join(cmd)}", file=sys.stderr)
229
+ sys.exit(subprocess.run(cmd).returncode)
230
+
231
+
146
232
  def api_request(server, method, path, body=None, timeout=30, raw=False):
147
233
  """Calls the API and returns the decoded JSON, or the bytes with raw=True."""
148
234
  req = urllib.request.Request(server.rstrip("/") + path, data=body, method=method)
@@ -469,6 +555,27 @@ def main():
469
555
  return domains.add_parser(name, help=help_text).add_subparsers(
470
556
  dest="command", metavar="<command>", required=True)
471
557
 
558
+ init = domains.add_parser("init", help="scaffold a project from an example config")
559
+ init.add_argument("dir", type=Path, nargs="?", help="directory to create (default: the example's name)")
560
+ init.add_argument("--example", default="echo", metavar="NAME",
561
+ help="example under examples/ in github.com/alto-se/trefoil (default: echo)")
562
+ init.set_defaults(func=cmd_init)
563
+
564
+ update = domains.add_parser("update", help="reinstall the latest trefoil-cli from PyPI")
565
+ update.set_defaults(func=cmd_update)
566
+
567
+ start_backend = domains.add_parser("start-backend", help="run the trefoil API server image locally with docker")
568
+ start_backend.add_argument("--settings", type=Path, metavar="FILE",
569
+ help="backend settings file (backend.yml) to mount into the container")
570
+ start_backend.add_argument("--port", type=int, default=8080, help="host port to publish (default: 8080)")
571
+ start_backend.add_argument("--image", default="ghcr.io/alto-se/trefoil-api:latest",
572
+ help="API image (default: ghcr.io/alto-se/trefoil-api:latest)")
573
+ start_backend.add_argument("--name", default="trefoil-api", help="container name (default: trefoil-api)")
574
+ start_backend.add_argument("--volume", default="trefoil-data",
575
+ help="docker volume (or host path) for the data dir (default: trefoil-data)")
576
+ start_backend.add_argument("-d", "--detach", action="store_true", help="run in the background")
577
+ start_backend.set_defaults(func=cmd_start_backend)
578
+
472
579
  config = domain("config", "package and upload agent configs")
473
580
  package = config.add_parser("package", help=__doc__.splitlines()[0])
474
581
  package.add_argument("config", type=Path, help="path to config.yml")
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "trefoil-cli"
3
- version = "0.2.0"
3
+ version = "1.0.0"
4
4
  description = "CLI for the trefoil agent server"
5
5
  requires-python = ">=3.10"
6
6
  dependencies = ["pyyaml>=6"]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: trefoil-cli
3
- Version: 0.2.0
3
+ Version: 1.0.0
4
4
  Summary: CLI for the trefoil agent server
5
5
  Requires-Python: >=3.10
6
6
  Requires-Dist: pyyaml>=6
File without changes