useland 0.1.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.
useland-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,45 @@
1
+ Metadata-Version: 2.4
2
+ Name: useland
3
+ Version: 0.1.0
4
+ Summary: Typed wrappers over the land CLI's --json output
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://useland.dev
7
+ Project-URL: Documentation, https://docs.useland.dev
8
+ Requires-Python: >=3.9
9
+ Description-Content-Type: text/markdown
10
+
11
+ # land SDK for Python
12
+
13
+ Typed wrappers over the `land` command line. Each call runs `land ... --json` and gives you back the JSON it prints.
14
+ The SDK has no network code of its own, so it signs in the same way the CLI does (your `land login`, or `LAND_TOKEN`
15
+ in the environment). Install the `land` CLI first. No dependencies, Python 3.9 or newer.
16
+
17
+ ```python
18
+ import os
19
+ from useland import Land, RefusedError
20
+
21
+ land = Land(cwd="/path/to/repo")
22
+
23
+ try:
24
+ answer = land.merge(["sub/api", "sub/ledger"], onto="main")
25
+ print(answer["push"]) # the push command that moves main
26
+ except RefusedError as e:
27
+ print(e.answer["refused"], e.fix)
28
+
29
+ land.local(["spec"]) # run .land/tests on this machine, unsigned and never a verdict
30
+ land.add(dry_run=True) # what an add would send, and recipes to start from
31
+ land.logs("users") # the output of a refused test
32
+ land.secrets.set("STRIPE_KEY", os.environ["STRIPE_KEY"])
33
+ ```
34
+
35
+ Every non-zero exit raises an error with `code`, `fix` (the command that fixes it), `docs` and the whole `answer`.
36
+
37
+ | exit | error | means |
38
+ |---|---|---|
39
+ | 1 | `RefusedError` | a branch was refused or a local test failed (`answer` still holds what landed) |
40
+ | 2 | `UsageError` | a usage or local error |
41
+ | 3 | `StillRunningError` | land is still working, so make the same call again |
42
+ | 4 | `CouldNotCheckError` | land could not check, so make the same call again |
43
+
44
+ Tests run against a fake `land` in `sdk/fake` with `python3 -m unittest discover -s tests`. The package is not
45
+ published.
@@ -0,0 +1,35 @@
1
+ # land SDK for Python
2
+
3
+ Typed wrappers over the `land` command line. Each call runs `land ... --json` and gives you back the JSON it prints.
4
+ The SDK has no network code of its own, so it signs in the same way the CLI does (your `land login`, or `LAND_TOKEN`
5
+ in the environment). Install the `land` CLI first. No dependencies, Python 3.9 or newer.
6
+
7
+ ```python
8
+ import os
9
+ from useland import Land, RefusedError
10
+
11
+ land = Land(cwd="/path/to/repo")
12
+
13
+ try:
14
+ answer = land.merge(["sub/api", "sub/ledger"], onto="main")
15
+ print(answer["push"]) # the push command that moves main
16
+ except RefusedError as e:
17
+ print(e.answer["refused"], e.fix)
18
+
19
+ land.local(["spec"]) # run .land/tests on this machine, unsigned and never a verdict
20
+ land.add(dry_run=True) # what an add would send, and recipes to start from
21
+ land.logs("users") # the output of a refused test
22
+ land.secrets.set("STRIPE_KEY", os.environ["STRIPE_KEY"])
23
+ ```
24
+
25
+ Every non-zero exit raises an error with `code`, `fix` (the command that fixes it), `docs` and the whole `answer`.
26
+
27
+ | exit | error | means |
28
+ |---|---|---|
29
+ | 1 | `RefusedError` | a branch was refused or a local test failed (`answer` still holds what landed) |
30
+ | 2 | `UsageError` | a usage or local error |
31
+ | 3 | `StillRunningError` | land is still working, so make the same call again |
32
+ | 4 | `CouldNotCheckError` | land could not check, so make the same call again |
33
+
34
+ Tests run against a fake `land` in `sdk/fake` with `python3 -m unittest discover -s tests`. The package is not
35
+ published.
@@ -0,0 +1,19 @@
1
+ [project]
2
+ name = "useland"
3
+ version = "0.1.0"
4
+ description = "Typed wrappers over the land CLI's --json output"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ requires-python = ">=3.9"
8
+ dependencies = []
9
+
10
+ [project.urls]
11
+ Homepage = "https://useland.dev"
12
+ Documentation = "https://docs.useland.dev"
13
+
14
+ [build-system]
15
+ requires = ["setuptools>=77"]
16
+ build-backend = "setuptools.build_meta"
17
+
18
+ [tool.setuptools]
19
+ packages = ["useland"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,56 @@
1
+ """Runs the SDK against the fake `land` in sdk/fake, put first on PATH."""
2
+ import os
3
+ import pathlib
4
+ import sys
5
+ import tempfile
6
+ import unittest
7
+
8
+ HERE = pathlib.Path(__file__).resolve().parent
9
+ sys.path.insert(0, str(HERE.parent))
10
+ from useland import Land, RefusedError, StillRunningError, UsageError # noqa: E402
11
+
12
+ LOG = os.path.join(tempfile.mkdtemp(prefix="land-sdk-"), "argv")
13
+ os.environ["PATH"] = f"{HERE.parent.parent / 'fake'}{os.pathsep}{os.environ['PATH']}"
14
+ os.environ["FAKE_LAND_LOG"] = LOG
15
+
16
+
17
+ def argv() -> str:
18
+ return pathlib.Path(LOG).read_text().strip()
19
+
20
+
21
+ class LandTest(unittest.TestCase):
22
+ land = Land()
23
+
24
+ def test_merge_returns_the_answer_and_passes_json(self):
25
+ self.assertEqual(self.land.merge(["sub/ok"], "main")["landed"], ["sub/ok"])
26
+ self.assertEqual(argv(), "merge sub/ok --onto main --json")
27
+
28
+ def test_exit_1_is_refused_and_keeps_the_answer(self):
29
+ with self.assertRaises(RefusedError) as e:
30
+ self.land.merge(["sub/bad"], "main")
31
+ self.assertEqual(e.exception.answer["refused"][0]["branch"], "sub/bad")
32
+
33
+ def test_exit_2_carries_fix_and_docs(self):
34
+ with self.assertRaises(UsageError) as e:
35
+ self.land.logs("users")
36
+ self.assertEqual(e.exception.fix, "land merge <branch>... --onto main")
37
+ self.assertEqual(e.exception.docs, "https://docs.useland.dev/errors#exit-2")
38
+
39
+ def test_exit_3_is_still_running(self):
40
+ with self.assertRaises(StillRunningError) as e:
41
+ self.land.add()
42
+ self.assertEqual(e.exception.fix, "land add")
43
+
44
+ def test_a_local_run_is_never_signed(self):
45
+ a = self.land.local()
46
+ self.assertIs(a["signed"], False)
47
+ self.assertEqual(a["tests"]["ran_units"][0]["name"], "spec")
48
+
49
+ def test_a_secrets_value_goes_on_stdin(self):
50
+ self.land.secrets.set("STRIPE_KEY", "sk_test_1")
51
+ self.assertEqual(argv(), "secret set STRIPE_KEY --json")
52
+ self.assertEqual(pathlib.Path(LOG + ".stdin").read_text(), "sk_test_1")
53
+
54
+
55
+ if __name__ == "__main__":
56
+ unittest.main()
@@ -0,0 +1,166 @@
1
+ """Typed wrappers over the land CLI.
2
+
3
+ Every call spawns ``land ... --json``, reads the one JSON object it prints on stdout and returns it; a non-zero exit
4
+ raises a typed error carrying land's ``fix`` and ``docs``. No network code: the CLI does all of that, with your login
5
+ or LAND_TOKEN.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import subprocess
12
+ from typing import Any, Dict, List, Optional, Sequence, TypedDict
13
+
14
+ __all__ = ["Land", "LandError", "RefusedError", "UsageError", "StillRunningError", "CouldNotCheckError", "error_for"]
15
+
16
+
17
+ class RanUnit(TypedDict, total=False):
18
+ name: str
19
+ state: str # "ran", "failed", "rerun", "not_run"
20
+ seconds: float
21
+ why: str
22
+ exit: int
23
+ output: str
24
+
25
+
26
+ class Tests(TypedDict, total=False):
27
+ total: int
28
+ ran: int
29
+ carried: int
30
+ failed: int
31
+ ran_units: List[RanUnit]
32
+
33
+
34
+ class MergeAnswer(TypedDict, total=False):
35
+ landed: List[str]
36
+ refused: List[Dict[str, Any]]
37
+ result: str # the commit to push
38
+ push: str # the exact push command
39
+ tests: Tests
40
+
41
+
42
+ class LocalAnswer(TypedDict, total=False):
43
+ """``land merge --local``: never a verdict. ``signed``, ``recorded`` and ``landed`` are always False."""
44
+
45
+ local: bool
46
+ signed: bool
47
+ recorded: bool
48
+ landed: bool
49
+ verdict: None
50
+ said: str
51
+ tests: Tests
52
+
53
+
54
+ class AddAnswer(TypedDict, total=False):
55
+ added: bool
56
+ dry_run: bool
57
+ repo: str
58
+ suggest: List[Dict[str, Any]] # recipes to start from, when the tree has no .land/tests and no workflow
59
+
60
+
61
+ class LogsAnswer(TypedDict, total=False):
62
+ failing: List[Dict[str, Any]]
63
+ probe: Dict[str, Any]
64
+
65
+
66
+ class LandError(Exception):
67
+ """A non-zero exit of the CLI. ``answer`` is the whole JSON object it printed."""
68
+
69
+ def __init__(self, message: str, code: int, fix: Optional[str], docs: Optional[str], answer: Dict[str, Any]):
70
+ super().__init__(message)
71
+ self.code, self.fix, self.docs, self.answer = code, fix, docs, answer
72
+
73
+
74
+ class RefusedError(LandError):
75
+ """exit 1: some branch was refused, a local test failed, or an add was refused. ``answer`` still holds what landed."""
76
+
77
+
78
+ class UsageError(LandError):
79
+ """exit 2: a usage or local error; ``fix`` is the command that fixes it."""
80
+
81
+
82
+ class StillRunningError(LandError):
83
+ """exit 3: land is still working; run the same call again to wait (``answer['again']``, ``answer['job']``)."""
84
+
85
+
86
+ class CouldNotCheckError(LandError):
87
+ """exit 4: land could not check (an engine or infrastructure error): run the same call again."""
88
+
89
+
90
+ _BY_CODE = {1: RefusedError, 2: UsageError, 3: StillRunningError, 4: CouldNotCheckError}
91
+
92
+
93
+ def error_for(code: int, answer: Dict[str, Any]) -> LandError:
94
+ """Map an exit code and the CLI's JSON to the typed error."""
95
+ s = lambda k: answer[k] if isinstance(answer.get(k), str) else None # noqa: E731
96
+ cls = _BY_CODE.get(code, LandError)
97
+ return cls(s("error") or f"land exited {code}", code, s("fix") or s("again"), s("docs"), answer)
98
+
99
+
100
+ class _Secrets:
101
+ def __init__(self, land: "Land"):
102
+ self._land = land
103
+
104
+ def set(self, name: str, value: str) -> Dict[str, Any]:
105
+ """Store one secret. The value goes on stdin, never in an argument."""
106
+ return self._land.run(["secret", "set", name], stdin=value)
107
+
108
+ def set_many(self, dotenv: str) -> Dict[str, Any]:
109
+ """Store every NAME=value line of a .env text."""
110
+ return self._land.run(["secret", "set"], stdin=dotenv)
111
+
112
+ def list(self) -> Dict[str, Any]:
113
+ return self._land.run(["secret", "list"])
114
+
115
+ def rm(self, name: str) -> Dict[str, Any]:
116
+ return self._land.run(["secret", "rm", name])
117
+
118
+
119
+ class Land:
120
+ def __init__(self, bin: str = "land", cwd: Optional[str] = None, env: Optional[Dict[str, str]] = None):
121
+ self.bin, self.cwd, self.env = bin, cwd, env or {}
122
+ self.secrets = _Secrets(self)
123
+
124
+ def run(self, args: Sequence[str], stdin: str = "") -> Dict[str, Any]:
125
+ """Run ``land <args> --json`` and return its JSON; a non-zero exit raises the typed error."""
126
+ p = subprocess.run([self.bin, *args, "--json"], cwd=self.cwd, env={**os.environ, **self.env},
127
+ input=stdin, capture_output=True, text=True)
128
+ lines = p.stdout.strip().splitlines()
129
+ try:
130
+ answer = json.loads(lines[-1]) if lines else {}
131
+ except json.JSONDecodeError:
132
+ answer = {"error": f"land printed no JSON (exit {p.returncode}): {p.stderr.strip()[-500:]}"}
133
+ if p.returncode != 0:
134
+ raise error_for(p.returncode, answer)
135
+ return answer
136
+
137
+ def merge(self, branches: Sequence[str], onto: str, result_tree: bool = False) -> MergeAnswer:
138
+ """Merge branches onto a target on land and prove the result. Exit 1 (some refused) raises RefusedError."""
139
+ return self.run(["merge", *branches, "--onto", onto, *(["--result", "tree"] if result_tree else [])]) # type: ignore[return-value]
140
+
141
+ def local(self, names: Sequence[str] = ()) -> LocalAnswer:
142
+ """Run .land/tests (all, or the named lines or tests) on this machine. Unsigned, never a verdict."""
143
+ return self.run(["merge", "--local", *names]) # type: ignore[return-value]
144
+
145
+ def add(self, dry_run: bool = False, test: Sequence[str] = (), allow_test_edits: Optional[bool] = None,
146
+ allow_low_guard: Optional[bool] = None, cpus: Optional[int] = None, time_limit: Optional[int] = None,
147
+ plane: Optional[str] = None) -> AddAnswer:
148
+ """Connect this repository (or preview with dry_run)."""
149
+ a = ["add"] + (["--dry-run"] if dry_run else [])
150
+ for t in test:
151
+ a += ["--test", t]
152
+ if allow_test_edits is not None:
153
+ a.append("--allow-test-edits" if allow_test_edits else "--no-allow-test-edits")
154
+ if allow_low_guard is not None:
155
+ a.append("--allow-low-guard" if allow_low_guard else "--no-allow-low-guard")
156
+ if cpus is not None:
157
+ a += ["--cpus", str(cpus)]
158
+ if time_limit is not None:
159
+ a += ["--time-limit", str(time_limit)]
160
+ if plane:
161
+ a += ["--plane", plane]
162
+ return self.run(a) # type: ignore[return-value]
163
+
164
+ def logs(self, name: Optional[str] = None, run: Optional[str] = None) -> LogsAnswer:
165
+ """The output of the tests the last merge refused; with ``run``, a command in that test's view on land's runner."""
166
+ return self.run(["logs", *([name] if name else []), *(["--run", run] if run is not None else [])]) # type: ignore[return-value]
@@ -0,0 +1,45 @@
1
+ Metadata-Version: 2.4
2
+ Name: useland
3
+ Version: 0.1.0
4
+ Summary: Typed wrappers over the land CLI's --json output
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://useland.dev
7
+ Project-URL: Documentation, https://docs.useland.dev
8
+ Requires-Python: >=3.9
9
+ Description-Content-Type: text/markdown
10
+
11
+ # land SDK for Python
12
+
13
+ Typed wrappers over the `land` command line. Each call runs `land ... --json` and gives you back the JSON it prints.
14
+ The SDK has no network code of its own, so it signs in the same way the CLI does (your `land login`, or `LAND_TOKEN`
15
+ in the environment). Install the `land` CLI first. No dependencies, Python 3.9 or newer.
16
+
17
+ ```python
18
+ import os
19
+ from useland import Land, RefusedError
20
+
21
+ land = Land(cwd="/path/to/repo")
22
+
23
+ try:
24
+ answer = land.merge(["sub/api", "sub/ledger"], onto="main")
25
+ print(answer["push"]) # the push command that moves main
26
+ except RefusedError as e:
27
+ print(e.answer["refused"], e.fix)
28
+
29
+ land.local(["spec"]) # run .land/tests on this machine, unsigned and never a verdict
30
+ land.add(dry_run=True) # what an add would send, and recipes to start from
31
+ land.logs("users") # the output of a refused test
32
+ land.secrets.set("STRIPE_KEY", os.environ["STRIPE_KEY"])
33
+ ```
34
+
35
+ Every non-zero exit raises an error with `code`, `fix` (the command that fixes it), `docs` and the whole `answer`.
36
+
37
+ | exit | error | means |
38
+ |---|---|---|
39
+ | 1 | `RefusedError` | a branch was refused or a local test failed (`answer` still holds what landed) |
40
+ | 2 | `UsageError` | a usage or local error |
41
+ | 3 | `StillRunningError` | land is still working, so make the same call again |
42
+ | 4 | `CouldNotCheckError` | land could not check, so make the same call again |
43
+
44
+ Tests run against a fake `land` in `sdk/fake` with `python3 -m unittest discover -s tests`. The package is not
45
+ published.
@@ -0,0 +1,8 @@
1
+ README.md
2
+ pyproject.toml
3
+ tests/test_land.py
4
+ useland/__init__.py
5
+ useland.egg-info/PKG-INFO
6
+ useland.egg-info/SOURCES.txt
7
+ useland.egg-info/dependency_links.txt
8
+ useland.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ useland