parent:
c3dee802a4878505a60909c4f533fffbdfffc936
nmyk <nick@nmyk.io>
2026-11-14T20:36:01-05:00
refactor government CLI
diff --git a/DESIGN.md b/DESIGN.md
index 660f6cbd9f5e5dfe7fabff5359f3a6e5cc32f2a6..5678bfa07dc7353ec71dac4260c3c87f220ea340 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -34,11 +34,11 @@
- **The trust anchor** is the one self-signed certificate. It carries no policies.
- **The certification path** is every other certificate. The certificate at depth *i* is issued by the one at depth *i−1* and carries every node at depth *i* of the tree. So *n* equals the program's AST depth.
- **Order.** The interpreter recovers each certificate's depth from the certificates themselves: it starts at the anchor and follows issuer links down. Every link is pinned by a signature, so the order cannot be forged, and a shuffled file runs exactly like the ordered one. A file that is not one clean chain (no anchor, two certificates issued by the same parent, a missing depth, an unrelated certificate) is an error.
-- Text outside PEM blocks is ignored, as PEM allows. The compiler writes nothing there by default (the program's name is already in every subject as `O=`). With `-source` it writes the original Lisp source, indented so no line of it can start a PEM block. The source is opt-in because the certs alone are the program, and the source may hold comments or code the author does not want to publish.
+- Text outside PEM blocks is ignored, as PEM allows. The compiler writes nothing there by default (the program's name is already in every subject as `O=`). With `--source` it writes the original Lisp source, indented so no line of it can start a PEM block. The source is opt-in because the certs alone are the program, and the source may hold comments or code the author does not want to publish.
- Any non-`CERTIFICATE` PEM block is an error.
- The compiler writes anchor first so that reading the file top to bottom reads the tree top to bottom (conventional PEM bundles are leaf-first). This is for human readers only.
-**Trust.** By default a program is self-ratified: the interpreter trusts the anchor inside the file, so validation checks internal consistency only. `government run -anchor gov-ca.pem prog.gov` additionally requires the anchor to match a given certificate, which gives code signing for free: only run programs ratified by your government.
+**Trust.** By default a program is self-ratified: the interpreter trusts the anchor inside the file, so validation checks internal consistency only. `government run --anchor gov-ca.pem prog.gov` additionally requires the anchor to match a given certificate, which gives code signing for free: only run programs ratified by your government.
### Certificate profile
@@ -49,7 +49,7 @@ | Serial | 1 | i + 1 | n + 1 |
| Signature | Ed25519 (author key) | Ed25519 (key of cert i−1) | Ed25519 (key of cert n−1) |
| Subject | `CN=<author or GOVERNMENT Anchor>, O=<program>` | `CN=GOVERNMENT Depth i, O=<program>` | `CN=GOVERNMENT Depth n, O=<program>` |
| subjectAltName | author email, if given | absent | absent |
-| Validity | `-effective` to `-expires` (default 2000-01-01 to 9999-12-31) | same | same |
+| Validity | `--effective` to `--expires` (default 2000-01-01 to 9999-12-31) | same | same |
| basicConstraints (critical) | CA:TRUE | CA:TRUE | CA:FALSE |
| keyUsage (critical) | keyCertSign, cRLSign | keyCertSign, cRLSign | digitalSignature |
| certificatePolicies | absent | cert 1: the top-level node OIDs; certs 2..n−1: `anyPolicy` only, plus any node that carries notes | `anyPolicy` only, plus any node that carries notes |
@@ -101,7 +101,7 @@ | 9 | One child OID mapped from several parents gets several parents (9618) or is duplicated (5280) | Shared subexpressions | Allowed; evaluated directly on the DAG, never unfolded (decided) |
**Strict check.** Plain RFC processing forgives mistakes by deleting code. After policy processing, the interpreter also verifies that certs 2..n assert `anyPolicy` and cert 1 does not, that every explicitly asserted policy in cert *i* is a node at depth *i*, that every mapping in cert *i* produced an edge, and that the program's distinct node ids are exactly 1..N with no gaps. A failure is a ratification error naming the orphaned OID. This turns silent data loss into a compile-style error.
-**Denial-of-service guard.** Policy processing has caused real DoS bugs, e.g. Go's CVE-2026-32281 (inefficient policy validation, fixed in Go 1.25.9 / 1.26.2). The graph form keeps work linear in mappings, and the interpreter caps nodes (`-max-nodes`, default 1,000,000).
+**Denial-of-service guard.** Policy processing has caused real DoS bugs, e.g. Go's CVE-2026-32281 (inefficient policy validation, fixed in Go 1.25.9 / 1.26.2). The graph form keeps work linear in mappings, and the interpreter caps nodes (`--max-nodes`, default 1,000,000).
## OID encoding
@@ -317,25 +317,28 @@ | `gov2lisp` | Decompiler: AST back to Lisp text |
### Ratification steps
-1. Parse every PEM block (an unreadable file is `E-MALFORMED`). Order the certs: the anchor is the only self-issued cert, every other cert's issuer must be the subject of exactly one cert in the file, and no two certs may share a parent (else `E-CHAIN`). The anchor must be self-signed. With `-anchor`, its public key must match the pinned one (else `E-FOREIGN`).
-2. For each cert at depth *i*: `CheckSignatureFrom(cert at depth i−1)` passes (else `E-TAMPERED`); the check time (`-at`, default now) is inside its validity (else `E-NOT-IN-FORCE` or `E-LAPSED`).
+1. Parse every PEM block (an unreadable file is `E-MALFORMED`). Order the certs: the anchor is the only self-issued cert, every other cert's issuer must be the subject of exactly one cert in the file, and no two certs may share a parent (else `E-CHAIN`). The anchor must be self-signed. With `--anchor`, its public key must match the pinned one (else `E-FOREIGN`).
+2. For each cert at depth *i*: `CheckSignatureFrom(cert at depth i−1)` passes (else `E-TAMPERED`); the check time (`--at`, default now) is inside its validity (else `E-NOT-IN-FORCE` or `E-LAPSED`).
3. Certs at depths 0..n−1 are CAs allowed to sign certs (basicConstraints CA:TRUE and keyCertSign); no cert but the anchor is self-issued, since that would change `policy_mapping` counting (else `E-CHAIN`).
4. No unknown critical extensions; no `policyConstraints` or `inhibitAnyPolicy`, rejected in v1 to keep the counters trivial (else `E-CHAIN`).
-5. With `-crl`: verify each CRL and reject any path cert it revokes (`E-REPEALED`, `E-STALE-REPEALS`).
-6. Run policy processing with the inputs in "The policy tree as AST", then the strict check (else `E-POLICY`; a graph past the `-max-nodes` budget is `E-TOO-LARGE`).
+5. With `--crl`: verify each CRL and reject any path cert it revokes (`E-REPEALED`, `E-STALE-REPEALS`).
+6. Run policy processing with the inputs in "The policy tree as AST", then the strict check (else `E-POLICY`; a graph past the `--max-nodes` budget is `E-TOO-LARGE`).
### CLI
| Command | Does |
| --- | --- |
| `government run prog.gov` | Ratify, decode, evaluate, print results |
+| `government prog.gov` | Same as `government run prog.gov`, as with `python prog.py`. A command name always wins over a file of the same name, and an argument that is neither a file nor a `.gov` name is reported as an unknown command |
| `government verify prog.gov` | Ratify and decode only; print the certificate of ratification; exit 0 if the program is lawful |
| `government tree prog.gov` | Print the policy tree, with `GOV` abbreviated, payloads decoded and notes shown |
| `government decompile prog.gov` | Print equivalent Lisp source, notes restored as comments |
-| `government compile prog.gov.lisp -o prog.gov` | Run the transpiler (`-key`, `-author`, `-seed`, `-effective`, `-expires`, `-name`, `-source`) |
-| `government repeal prog.gov -o repeal.crl` | Write a CRL repealing the program (`-key` or `-seed`, `-reason`, `-at`, `-issued`, `-next-update`; `-next-update` defaults to 9999-12-31, a permanent repeal) |
+| `government compile prog.gov.lisp -o prog.gov` | Run the transpiler (`--key`, `--author`, `--seed`, `--effective`, `--expires`, `--name`, `--source`) |
+| `government repeal prog.gov -o repeal.crl` | Write a CRL repealing the program (`--key` or `--seed`, `--reason`, `--at`, `--issued`, `--next-update`; `--next-update` defaults to 9999-12-31, a permanent repeal) |
+
+Shared flags: `--at <RFC 3339 time>`, `--anchor <cert or public key PEM>`, `--crl <file>` (repeatable), `--max-nodes <n>`.
-Shared flags: `-at <RFC 3339 time>`, `-anchor <cert or public key PEM>`, `-crl <file>` (repeatable), `-max-nodes <n>`.
+The CLI is built on [cobra](https://github.com/spf13/cobra), so flags follow GNU style: long flags take two dashes, `-o` is short for `--output`, flags may come before or after the file name, and `government <command> --help` lists a command's flags.
GOVERNMENT's Lisp source files use the extension `.gov.lisp`. A second command, `govlisp`, runs Lisp source directly, with no certificates: `govlisp` alone is a REPL (multi-line forms, errors reported without ending the session), and `govlisp prog.gov.lisp` runs a file, printing each non-`define` value and reporting the first error at its source line and column.
@@ -351,7 +354,7 @@ 3. **Number** nodes in pre-order, starting at 1.
4. **Layer**: compute n = max depth and each node's depth. No padding is written: `anyPolicy` makes the validator copy shallow leaves down.
5. **Assign**: cert 1 lists the top-level nodes; certs 2..n list `anyPolicy`, plus any node that carries notes; each parent→child edge becomes a mapping in the parent's cert.
6. **Sign**: take the author key (or the default seed), derive one Ed25519 key per depth, build the anchor and certs 1..n, and hand-encode certificatePolicies and policyMappings.
-7. **Emit** PEM, with the original source above the first block if `-source` is given.
+7. **Emit** PEM, with the original source above the first block if `--source` is given.
The same source and flags always give the same bytes.
@@ -391,7 +394,7 @@ | Language | `testdata/*.gov.lisp` | All semantics: arithmetic, comparisons, truthiness, `if`, `quote`, lists, `define`, closures, scoping, recursion, higher-order functions, strings and Unicode |
| Shape stress | `testdata/*.gov.lisp` | 200-deep nesting (201 certs), 1,000-argument calls, wide `quote`d lists, shared subexpressions |
| Round trip | Go test over every `testdata` file | `gov2lisp(lisp2gov(src))` equals the normalized source, comments included |
| Ratification | Go table test that mutates a valid chain | Flipped signature byte, reordered certs, dropped mapping, orphaned policy, mapping in cert n, `anyPolicy` missing from a cert 2..n or asserted in cert 1, a list node with no elements, unknown critical extension; each expects a specific error |
-| Civic | Go table test | Runs before, inside and after an `-effective`/`-expires` window; repeal of each depth; scheduled repeal; stale CRL; CRL signed by the wrong key; `-anchor` pin across a re-ratified version; notes over 200 characters; default-key warning |
+| Civic | Go table test | Runs before, inside and after an `--effective`/`--expires` window; repeal of each depth; scheduled repeal; stale CRL; CRL signed by the wrong key; `--anchor` pin across a re-ratified version; notes over 200 characters; default-key warning |
| Golden | One checked-in `.gov` | Byte equality, proving determinism |
| External oracle (optional) | `openssl verify -policy_check -explicit_policy -policy 2.5.29.32.0`, plus `-crl_check` | OpenSSL accepts every valid program, rejects broken ones, and agrees on repeals. Without `-policy 2.5.29.32.0` OpenSSL treats the acceptable set as empty |
@@ -405,8 +408,8 @@ ### Effective dates
A program is in force only between its start and end dates.
-- `government compile -effective 2027-01-01 -expires 2027-12-31` sets `notBefore` and `notAfter` on every cert. The defaults are 2000-01-01 and 9999-12-31 (no expiry).
-- The interpreter checks every cert's window at the check time (`-at`, default now). The program's window is the overlap of all of them.
+- `government compile --effective 2027-01-01 --expires 2027-12-31` sets `notBefore` and `notAfter` on every cert. The defaults are 2000-01-01 and 9999-12-31 (no expiry).
+- The interpreter checks every cert's window at the check time (`--at`, default now). The program's window is the overlap of all of them.
- Before the window: `E-NOT-IN-FORCE: takes effect 2027-01-01T00:00:00Z`. After it: `E-LAPSED: expired 2027-12-31T00:00:00Z`. Both exit with code 2.
### Repeal (revocation)
@@ -415,9 +418,9 @@ A signed certificate revocation list (CRL) can strike down a ratified program after it has shipped.
- Revoking any cert of the chain breaks it, so revoking one cert repeals the whole program.
- Per RFC 5280, a cert's revocation is published by its issuer. `government repeal` always revokes depth 1, so its CRL is signed by the anchor, with the author's own key: the author strikes down what they ratified.
-- `government repeal prog.gov -reason superseded -o repeal.crl` writes that CRL. It needs the program's signing key (see Authorship). The reason is any RFC 5280 CRLReason, e.g. `superseded` or `cessationOfOperation`.
+- `government repeal prog.gov --reason superseded -o repeal.crl` writes that CRL. It needs the program's signing key (see Authorship). The reason is any RFC 5280 CRLReason, e.g. `superseded` or `cessationOfOperation`.
- The checker accepts a CRL from any cert of the chain, as RFC 5280 path validation does, so a hand-made CRL for depth *i*, signed by cert *i−1*, repeals the program too. Every CA cert therefore gets `cRLSign` as well as `keyCertSign`.
-- `government run -crl repeal.crl prog.gov` loads one or more CRL PEM blocks (the flag repeats; `verify`, `tree` and `decompile` take it too). For each CRL it checks that its issuer is a cert of this program (else `E-FOREIGN`), its signature (`RevocationList.CheckSignatureFrom`, else `E-TAMPERED`), and that the check time is not past `nextUpdate`. A check time before `thisUpdate` is allowed: each entry's revocation time already says when the repeal applies, so a newer list can still answer whether the program was in force at an earlier `-at`.
+- `government run --crl repeal.crl prog.gov` loads one or more CRL PEM blocks (the flag repeats; `verify`, `tree` and `decompile` take it too). For each CRL it checks that its issuer is a cert of this program (else `E-FOREIGN`), its signature (`RevocationList.CheckSignatureFrom`, else `E-TAMPERED`), and that the check time is not past `nextUpdate`. A check time before `thisUpdate` is allowed: each entry's revocation time already says when the repeal applies, so a newer list can still answer whether the program was in force at an earlier `--at`.
- A path cert listed with a revocation time at or before the check time fails: `E-REPEALED: depth 1 repealed 2027-03-01 (superseded)`.
- A CRL past its `nextUpdate` is `E-STALE-REPEALS`. This is a deliberate GOVERNMENT rule: an outdated repeal list fails closed.
- A future revocation time gives a scheduled repeal. RFC 5280 treats that field as when revocation occurred, so honoring a future time is a GOVERNMENT-specific reading, noted as such.
@@ -437,12 +440,12 @@ ### Authorship
A program is signed by its author's key, which records who ratified it and lets only that person amend or repeal it.
-- `government compile -key author.pem -author "Ada Lovelace <ada@example.com>"` takes an Ed25519 PKCS#8 key. The anchor is self-signed with it, with subject `CN=Ada Lovelace, O=<program>` and the email in subjectAltName.
+- `government compile --key author.pem --author "Ada Lovelace <ada@example.com>"` takes an Ed25519 PKCS#8 key. The anchor is self-signed with it, with subject `CN=Ada Lovelace, O=<program>` and the email in subjectAltName.
- The keys for certs 1..n are derived from the author key: seed for depth *i* = SHA-256(author seed ‖ "GOVERNMENT" ‖ i). Output stays byte-for-byte deterministic, and the key holder alone can rebuild the chain or sign repeals.
- Any changed byte breaks a signature: `E-TAMPERED: clause at depth 2 fails signature check`. Amending a program means re-ratifying it.
-- `-anchor` pins a public key, not a whole cert. It accepts a cert or a public key PEM and compares SubjectPublicKeyInfo. A re-ratified program with new dates or text still matches its author's pin.
+- `--anchor` pins a public key, not a whole cert. It accepts a cert or a public key PEM and compares SubjectPublicKeyInfo. A re-ratified program with new dates or text still matches its author's pin.
- `government verify` prints a certificate of ratification: author, key fingerprint (SHA-256 of the SPKI), window in force, depth and node count.
-- Without `-key`, the default seed is public, so anyone can forge, amend or repeal. `verify` says so: `ratified by nobody in particular (default key)`.
+- Without `--key`, the default seed is public, so anyone can forge, amend or repeal. `verify` says so: `ratified by nobody in particular (default key)`.
## Design decisions
@@ -455,8 +458,8 @@ | Number size? | 64 bits: int64 (overflow is an error) and float64 | Semantics |
| What does a program output? | Value of every non-`define` top-level form | Semantics, tests |
| Shared subexpressions? | Allowed; evaluated on the DAG without unfolding | Policy tree |
| `define` in lambda bodies? | Allowed at the start of the body; sequential, no mutual recursion | Semantics |
-| Who is trusted? | The file's own anchor (`-anchor` optional) | Source format |
-| Should programs expire? | Only when built with `-expires` | Civic features |
+| Who is trusted? | The file's own anchor (`--anchor` optional) | Source format |
+| Should programs expire? | Only when built with `--expires` | Civic features |
| Cert order in the file? | Written anchor first, top-down; read in any order | Source format |
| OID root? | UUID arc under `2.25` | OID encoding |
| v1 extras? | No variadic lambdas; `if` without else returns `()`; add `strlen`, `strcat`, `str?` | Semantics, builtin table |
diff --git a/PLAN.md b/PLAN.md
index e91f31c3966c1dbe319063284bfee15a501bab74..a0ad2dd00f0fd73dc0c16e3c334d1e79ca20b44d 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -135,7 +135,7 @@ - Build: hand-encode `certificatePolicies` (OID `2.5.29.32`) as a SEQUENCE of PolicyInformation, OIDs only for now, leaving room for qualifiers in Phase 7. Cert 1 lists the top-level nodes; certs 2..n list `anyPolicy` (`2.5.29.32.0`).
- Learn: policy OIDs as assertions a CA makes about a certificate, which is the hook GOVERNMENT abuses. Read RFC 5280 §4.2.1.4.
- Done when: `ParseCertificate` returns the OIDs in `Policies`, including one with the 128-bit `GOV` arc.
22. **The transpiler** (`lisp2gov`, `cmd/government`)
- - Build: `Compile(src) ([]byte, error)`: read, build the tree, layer, then one cert per depth (cert 1 with the top-level nodes, the rest with `anyPolicy`), each with the mappings for its depth's outgoing edges; per-depth keys from the seed; PEM, with the source above the first block if `-source` is given. Wire up `government compile`.
+ - Build: `Compile(src) ([]byte, error)`: read, build the tree, layer, then one cert per depth (cert 1 with the top-level nodes, the rest with `anyPolicy`), each with the mappings for its depth's outgoing edges; per-depth keys from the seed; PEM, with the source above the first block if `--source` is given. Wire up `government compile`.
- Learn: how a certification path is a chain of issuer→subject links; how a whole program becomes n+1 signed objects.
- Done when: `government compile examples/sq.gov.lisp -o sq.gov` writes a file that `openssl x509` can print block by block, and compiling twice gives identical bytes. **Milestone: GOVERNMENT programs exist.**
@@ -152,11 +152,11 @@ - Build: `Order`, which finds the anchor (the only self-issued cert) and follows issuer links to put every cert at its depth, rejecting a missing anchor, forks, gaps and unrelated certs (`E-CHAIN`); then for each cert *i*: `CheckSignatureFrom` passes (`E-TAMPERED`), parents are CA with keyCertSign, no cert but the anchor is self-issued, no unknown critical extensions, and `policyConstraints` / `inhibitAnyPolicy` are absent (`E-CHAIN`).
- Learn: basic path processing (RFC 5280 §6.1.3 a–c, §6.1.4 k–n); why name chaining and signatures are separate checks; how a chain's order is recoverable from the certs themselves; what a relying party must do with a critical extension it does not understand.
- Done when: a mutation table test (flip a signature byte, change a signed byte, clear `IsCA`, add an unknown critical extension, drop a depth, duplicate a cert, add a foreign cert) gives `E-TAMPERED` or `E-CHAIN` for each, and a shuffled file ratifies exactly like the ordered one.
25. **Validity windows** (`ratify`)
- - Build: check every cert's `NotBefore`/`NotAfter` against the check time; the `-at` flag; `E-NOT-IN-FORCE` and `E-LAPSED`.
+ - Build: check every cert's `NotBefore`/`NotAfter` against the check time; the `--at` flag; `E-NOT-IN-FORCE` and `E-LAPSED`.
- Learn: why validity is per certificate, so a chain's lifetime is the overlap; UTCTime vs GeneralizedTime (RFC 5280 §4.1.2.5 switches encodings at 2050, which is why 9999-12-31 works).
- - Done when: a cert valid in 2027 passes with `-at 2027-06-01T00:00:00Z` and fails with each error on either side.
+ - Done when: a cert valid in 2027 passes with `--at 2027-06-01T00:00:00Z` and fails with each error on either side.
26. **Trust anchors and pinning** (`ratify`)
- - Build: the anchor must be self-signed; optional `-anchor` compares SubjectPublicKeyInfo bytes with a given cert or public key PEM.
+ - Build: the anchor must be self-signed; optional `--anchor` compares SubjectPublicKeyInfo bytes with a given cert or public key PEM.
- Learn: a trust anchor is a key you already trust, not really a certificate; why pinning a key outlives pinning a cert.
- Done when: a program built from the same seed but with different dates still matches its pin, and one from another seed does not. **Milestone: tampered, expired and foreign programs are refused.**
@@ -173,7 +173,7 @@ - Build: RFC 5280 §6.1.4 (a)–(b): reject `anyPolicy` in mappings; for each depth-*i* node that is an `issuerDomainPolicy`, set its expected set to the mapped `subjectDomainPolicy` values; skip this step for cert *n*.
- Learn: what mappings mean between real CAs ("your policy X is equivalent to my policy Y"), and why that is exactly a parent→child edge.
- Done when: the design's worked example produces its tree exactly, checked against the table, and a child mapped from two parents gets two parents.
29. **Strict check and limits** (`policy`)
- - Build: after processing, every asserted policy is a node at its depth, every mapping produced an edge, and node ids are exactly 1..N (else an orphaned-policy error naming the OID); mappings in cert *n* rejected; `anyPolicy` missing from a cert 2..n, or asserted in cert 1, rejected; `-max-nodes` budget.
+ - Build: after processing, every asserted policy is a node at its depth, every mapping produced an edge, and node ids are exactly 1..N (else an orphaned-policy error naming the OID); mappings in cert *n* rejected; `anyPolicy` missing from a cert 2..n, or asserted in cert 1, rejected; `--max-nodes` budget.
- Learn: how silent pruning makes RFC processing forgiving, and why a language needs it to be unforgiving; policy-processing DoS (CVE-2026-32281 in Go).
- Done when: deleting one mapping from a valid file gives an error (a gap in the node ids, or a list node left with no elements), not a shorter program, except for the subtree with the highest ids, which the test documents.
30. **The full pipeline** (`cmd/government`)
@@ -196,22 +196,22 @@ - Done when: `verify` exits 0 on valid files and 2 with the right error on each Phase 4 mutation.
## Phase 7: Civic features (steps 33–36)
-Add the four features that use X.509 for more than structure. Effective dates already exist from step 25 (`-effective` and `-expires` only need compile flags, added in step 34), so this phase covers notes, authorship and repeal.
+Add the four features that use X.509 for more than structure. Effective dates already exist from step 25 (`--effective` and `--expires` only need compile flags, added in step 34), so this phase covers notes, authorship and repeal.
33. **Notes** (`sexpr`, `lisp2gov`, `policy`)
- Build: the reader keeps comments and attaches each to the form on the next line or the form it trails; the certificatePolicies encoder adds user-notice qualifiers (`1.3.6.1.5.5.7.2.2`), splitting text over 200 characters; a raw-extension decoder reads them back; `tree`, errors and `decompile` show them.
- Learn: policy qualifiers and why relying parties may ignore them (they never affect validation); working with extension bytes Go parses only partly.
- Done when: a 450-character comment survives compile → decompile intact, and an error inside a noted form prints its note.
34. **Authorship** (`lisp2gov`, `cmd/government`)
- - Build: `-key` (Ed25519 PKCS#8), `-author "Name <email>"` into the anchor subject and subjectAltName, per-depth key derivation SHA-256(seed ‖ "GOVERNMENT" ‖ i), the `-effective` and `-expires` flags; `verify` reports "ratified by nobody in particular" for the default seed.
+ - Build: `--key` (Ed25519 PKCS#8), `--author "Name <email>"` into the anchor subject and subjectAltName, per-depth key derivation SHA-256(seed ‖ "GOVERNMENT" ‖ i), the `--effective` and `--expires` flags; `verify` reports "ratified by nobody in particular" for the default seed.
- Learn: private keys, PKCS#8, and key derivation; why the default seed being public makes every default-built program forgeable.
- - Done when: two authors' builds of one source differ only in keys and names, each verifies with its own `-anchor` pin, and neither verifies with the other's.
+ - Done when: two authors' builds of one source differ only in keys and names, each verifies with its own `--anchor` pin, and neither verifies with the other's.
35. **Writing repeals** (`cmd/government`)
- Build: `government repeal prog.gov`: re-derive the anchor key, then `x509.CreateRevocationList` listing the serial of cert 1 with a CRLReason, `thisUpdate`, `nextUpdate` and a revocation time. Every CA cert gains `cRLSign` in its keyUsage.
- Learn: CRLs, why a cert is revoked by its own issuer, serial numbers being unique only per issuer, reason codes. Read RFC 5280 §5.
- Done when: `openssl crl -text` prints your CRL, and its signature verifies against the anchor.
36. **Checking repeals** (`ratify`)
- - Build: `-crl` (repeatable); match each CRL to its issuer in the path, verify with `RevocationList.CheckSignatureFrom`, reject if the check time is past `nextUpdate` (`E-STALE-REPEALS`), and reject listed certs whose revocation time has passed (`E-REPEALED`, so future times act as scheduled repeals).
+ - Build: `--crl` (repeatable); match each CRL to its issuer in the path, verify with `RevocationList.CheckSignatureFrom`, reject if the check time is past `nextUpdate` (`E-STALE-REPEALS`), and reject listed certs whose revocation time has passed (`E-REPEALED`, so future times act as scheduled repeals).
- Learn: revocation checking as a separate trust decision; fail-open vs fail-closed, and why GOVERNMENT picks fail-closed.
- Done when: a table test covers repeal of each depth, a scheduled repeal before and after its date, a stale CRL, and a CRL signed by the wrong key. **Milestone: the full design is implemented.**
@@ -220,11 +220,11 @@
Finish with the tests that prove GOVERNMENT is deterministic, survives large programs, and agrees with an independent PKI implementation.
37. **Shared subexpressions** (`lisp2gov`, `eval`)
- - Build: an opt-in `-share` compile flag that hash-conses identical subtrees at the same depth into one node with several parents; confirm `Unlayer` and the evaluator walk the DAG without copying.
+ - Build: an opt-in `--share` compile flag that hash-conses identical subtrees at the same depth into one node with several parents; confirm `Unlayer` and the evaluator walk the DAG without copying.
- Learn: hash-consing; how RFC 9618's graph makes sharing cheap where RFC 5280's tree would duplicate it.
- - Done when: every `testdata` file gives the same results with and without `-share`, and a program with 20 nested copies of one subexpression stays small.
+ - Done when: every `testdata` file gives the same results with and without `--share`, and a program with 20 nested copies of one subexpression stays small.
38. **Stress and golden tests**
- - Build: generated programs 200 deep (201 certs) and 1,000 arguments wide; `-max-nodes` tests; one checked-in golden `.gov` compared byte for byte.
+ - Build: generated programs 200 deep (201 certs) and 1,000 arguments wide; `--max-nodes` tests; one checked-in golden `.gov` compared byte for byte.
- Learn: why reproducible output is a security property (anyone can rebuild and compare), and how golden files catch unintended format changes.
- Done when: stress tests finish in under a few seconds, and the golden test fails if any byte of the encoding changes.
39. **OpenSSL as an oracle** (optional, skipped when `openssl` is absent)
diff --git a/cmd/government/anchor.go b/cmd/government/anchor.go
index 4540145e2c288a7699fd2753da47e5d976c55e0b..fac70c5ca93cc4c5e516f4d5aadbedee4e83b3fa 100644
--- a/cmd/government/anchor.go
+++ b/cmd/government/anchor.go
@@ -1,21 +1,22 @@
package main
import (
- "flag"
"os"
+
+ "github.com/spf13/pflag"
"government/ratify"
)
-// anchorFlag is -anchor, shared by run and verify: a file holding the only
-// key a program's anchor may have. It accepts a public key PEM, a cert, or
-// another .gov file ratified by the same author.
+// anchorFlag is --anchor, shared by every command that loads a program: a
+// file holding the only key a program's anchor may have. It accepts a
+// public key PEM, a cert, or another .gov file ratified by the same author.
type anchorFlag struct {
path string
pin ratify.Pin
}
-func addAnchorFlag(fs *flag.FlagSet) *anchorFlag {
+func addAnchorFlag(fs *pflag.FlagSet) *anchorFlag {
a := &anchorFlag{}
fs.Var(a, "anchor", "only accept programs whose anchor key matches the one in `file` (a public key, cert or .gov)")
return a
@@ -41,5 +42,7 @@ a.path, a.pin = path, pin
return nil
}
-// Pin is nil when -anchor was not given.
+func (a *anchorFlag) Type() string { return "file" }
+
+// Pin is nil when --anchor was not given.
func (a *anchorFlag) Pin() ratify.Pin { return a.pin }
diff --git a/cmd/government/anchor_test.go b/cmd/government/anchor_test.go
index 1a75b6494a700496395d215e10e06630bd823c83..922d117ec62954d299c43f1e26d02009d4b29245 100644
--- a/cmd/government/anchor_test.go
+++ b/cmd/government/anchor_test.go
@@ -1,11 +1,12 @@
package main
import (
- "flag"
"io"
"os"
"path/filepath"
"testing"
+
+ "github.com/spf13/pflag"
"government/lisp2gov"
"government/ratify"
@@ -23,7 +24,7 @@ junk := filepath.Join(dir, "junk.txt")
os.WriteFile(junk, []byte("not a key"), 0o644)
parse := func(args ...string) (*anchorFlag, error) {
- fs := flag.NewFlagSet("test", flag.ContinueOnError)
+ fs := pflag.NewFlagSet("test", pflag.ContinueOnError)
fs.SetOutput(io.Discard)
a := addAnchorFlag(fs)
return a, fs.Parse(args)
@@ -34,7 +35,7 @@ if err != nil || a.Pin() != nil {
t.Errorf("no -anchor: pin %v, err %v; want none", a.Pin(), err)
}
- a, err = parse("-anchor", prog)
+ a, err = parse("--anchor", prog)
if err != nil {
t.Fatal(err)
}
@@ -44,7 +45,7 @@ t.Errorf("pin from the program itself: %v", err)
}
for _, bad := range []string{junk, filepath.Join(dir, "missing.pem")} {
- if _, err := parse("-anchor", bad); err == nil {
+ if _, err := parse("--anchor", bad); err == nil {
t.Errorf("-anchor %s accepted", bad)
}
}
diff --git a/cmd/government/at.go b/cmd/government/at.go
index e06992b4da254c58e43b969407d81ba717748ba5..8e751fbea5c5807c9d544336f91a5f7b75ae0d18 100644
--- a/cmd/government/at.go
+++ b/cmd/government/at.go
@@ -1,21 +1,22 @@
package main
import (
- "flag"
"fmt"
"time"
+
+ "github.com/spf13/pflag"
)
-// atFlag is -at, shared by run, verify and repeal: the moment at which a
-// program's validity windows and repeals are checked. It defaults to now,
-// and setting it is how you ask whether a program was, or will be, in
-// force at some other time.
+// atFlag is --at, shared by every command that loads a program: the moment
+// at which a program's validity windows and repeals are checked. It
+// defaults to now, and setting it is how you ask whether a program was,
+// or will be, in force at some other time.
type atFlag struct {
t time.Time
}
-func addAtFlag(fs *flag.FlagSet) *atFlag {
- a := &atFlag{t: time.Now().UTC()}
+func addAtFlag(fs *pflag.FlagSet) *atFlag {
+ a := &atFlag{}
fs.Var(a, "at", "check validity and repeals at this RFC 3339 `time` (default now), e.g. 2027-06-01T00:00:00Z")
return a
}
@@ -36,4 +37,11 @@ a.t = t.UTC()
return nil
}
-func (a *atFlag) Time() time.Time { return a.t }
+func (a *atFlag) Type() string { return "time" }
+
+func (a *atFlag) Time() time.Time {
+ if a.t.IsZero() {
+ return time.Now().UTC()
+ }
+ return a.t
+}
diff --git a/cmd/government/at_test.go b/cmd/government/at_test.go
index ef6ff60bd1e9c3bf202545412b6072bd1a79b786..2760d7dca1c71ba5d3471ad8f6b65944b24552ea 100644
--- a/cmd/government/at_test.go
+++ b/cmd/government/at_test.go
@@ -1,15 +1,16 @@
package main
import (
- "flag"
"io"
"testing"
"time"
+
+ "github.com/spf13/pflag"
)
func TestAtFlag(t *testing.T) {
parse := func(args ...string) (*atFlag, error) {
- fs := flag.NewFlagSet("test", flag.ContinueOnError)
+ fs := pflag.NewFlagSet("test", pflag.ContinueOnError)
fs.SetOutput(io.Discard)
at := addAtFlag(fs)
return at, fs.Parse(args)
@@ -20,18 +21,18 @@ if err != nil || time.Since(at.Time()) > time.Minute {
t.Errorf("default: %v, %v; want about now", at.Time(), err)
}
- at, err = parse("-at", "2027-06-01T00:00:00Z")
+ at, err = parse("--at", "2027-06-01T00:00:00Z")
if err != nil || !at.Time().Equal(time.Date(2027, 6, 1, 0, 0, 0, 0, time.UTC)) {
t.Errorf("-at 2027-06-01T00:00:00Z: %v, %v", at.Time(), err)
}
- at, err = parse("-at", "2027-06-01T09:00:00-04:00")
+ at, err = parse("--at", "2027-06-01T09:00:00-04:00")
if err != nil || !at.Time().Equal(time.Date(2027, 6, 1, 13, 0, 0, 0, time.UTC)) {
t.Errorf("offset: %v, %v", at.Time(), err)
}
for _, bad := range []string{"2027-06-01", "June 1", ""} {
- if _, err := parse("-at", bad); err == nil {
+ if _, err := parse("--at", bad); err == nil {
t.Errorf("-at %q accepted", bad)
}
}
diff --git a/cmd/government/author_test.go b/cmd/government/author_test.go
index 3966c1c20be09491caca8b904ec4f1857ab52491..7a31c000d0608f550adaac70effeadf3191cdc0a 100644
--- a/cmd/government/author_test.go
+++ b/cmd/government/author_test.go
@@ -33,7 +33,7 @@ src := writeSource(t, "law", "(+ 1 (* 2 3))")
build := func(who string, seed byte, author string) string {
key := writeKey(t, dir, who, seed)
gov := filepath.Join(dir, who+".gov")
- if code, _, stderr := runCmd("compile", src, "-o", gov, "-key", key, "-author", author); code != exitOK {
+ if code, _, stderr := runCmd("compile", src, "-o", gov, "--key", key, "--author", author); code != exitOK {
t.Fatalf("%s: %s", who, stderr)
}
return gov
@@ -45,7 +45,7 @@ for _, c := range []struct {
prog, pin string
ok bool
}{{ada, ada, true}, {bob, bob, true}, {ada, bob, false}, {bob, ada, false}} {
- code, _, stderr := runCmd("verify", c.prog, "-anchor", c.pin)
+ code, _, stderr := runCmd("verify", c.prog, "--anchor", c.pin)
if c.ok != (code == exitOK) {
t.Errorf("verify %s -anchor %s: exit %d, %s", filepath.Base(c.prog), filepath.Base(c.pin), code, stderr)
}
@@ -68,7 +68,7 @@ func TestCompileDates(t *testing.T) {
dir := t.TempDir()
src := writeSource(t, "dated", "(+ 1 2)")
gov := filepath.Join(dir, "dated.gov")
- if code, _, stderr := runCmd("compile", src, "-o", gov, "-effective", "2027-01-01", "-expires", "2027-12-31T00:00:00Z"); code != exitOK {
+ if code, _, stderr := runCmd("compile", src, "-o", gov, "--effective", "2027-01-01", "--expires", "2027-12-31T00:00:00Z"); code != exitOK {
t.Fatal(stderr)
}
for at, want := range map[string]string{
@@ -76,7 +76,7 @@ "2027-06-01T00:00:00Z": "",
"2026-12-31T00:00:00Z": "E-NOT-IN-FORCE: takes effect 2027-01-01T00:00:00Z",
"2028-01-01T00:00:00Z": "E-LAPSED: expired 2027-12-31T00:00:00Z",
} {
- code, stdout, stderr := runCmd("run", gov, "-at", at)
+ code, stdout, stderr := runCmd("run", gov, "--at", at)
switch {
case want == "" && (code != exitOK || stdout != "3\n"):
t.Errorf("at %s: exit %d, %q, %s", at, code, stdout, stderr)
@@ -84,7 +84,7 @@ case want != "" && !strings.Contains(stderr, want):
t.Errorf("at %s: %s, want %s", at, stderr, want)
}
}
- code, stdout, stderr := runCmd("verify", gov, "-at", "2027-06-01T00:00:00Z")
+ code, stdout, stderr := runCmd("verify", gov, "--at", "2027-06-01T00:00:00Z")
if code != exitOK || !strings.Contains(stdout, "In force 2027-01-01T00:00:00Z to 2027-12-31T00:00:00Z") {
t.Errorf("verify in the window: exit %d, %s%s", code, stdout, stderr)
}
@@ -96,20 +96,20 @@ src := writeSource(t, "p", "1")
key := writeKey(t, dir, "k", 5)
seedHex := strings.Repeat("05", 32)
a, b := filepath.Join(dir, "a.gov"), filepath.Join(dir, "b.gov")
- runCmd("compile", src, "-o", a, "-key", key)
- runCmd("compile", src, "-o", b, "-seed", seedHex)
+ runCmd("compile", src, "-o", a, "--key", key)
+ runCmd("compile", src, "-o", b, "--seed", seedHex)
x, _ := os.ReadFile(a)
y, _ := os.ReadFile(b)
if len(x) == 0 || string(x) != string(y) {
t.Error("-key and -seed for the same key gave different programs")
}
for _, args := range [][]string{
- {"compile", src, "-key", key, "-seed", seedHex},
- {"compile", src, "-seed", "abc"},
- {"compile", src, "-key", filepath.Join(dir, "missing.pem")},
- {"compile", src, "-effective", "next week"},
- {"compile", src, "-effective", "2028-01-01", "-expires", "2027-01-01"},
- {"compile", src, "-author", "Ada <broken"},
+ {"compile", src, "--key", key, "--seed", seedHex},
+ {"compile", src, "--seed", "abc"},
+ {"compile", src, "--key", filepath.Join(dir, "missing.pem")},
+ {"compile", src, "--effective", "next week"},
+ {"compile", src, "--effective", "2028-01-01", "--expires", "2027-01-01"},
+ {"compile", src, "--author", "Ada <broken"},
} {
if code, _, _ := runCmd(args...); code != exitInvalid {
t.Errorf("%v: exit %d, want %d", args[2:], code, exitInvalid)
diff --git a/cmd/government/compile.go b/cmd/government/compile.go
index fa5b6e03f55d7dbf9be9446d8d469827270ebe7e..d4b71ae1434f1bb93c057d3e68e739b65f22d2f8 100644
--- a/cmd/government/compile.go
+++ b/cmd/government/compile.go
@@ -3,109 +3,89 @@
import (
"encoding/hex"
"errors"
- "flag"
"fmt"
- "io"
"os"
"path/filepath"
"strings"
"time"
+ "github.com/spf13/cobra"
+
"government/lisp2gov"
"government/sexpr"
)
-func compile(args []string, stdout, stderr io.Writer) int {
- fs := flag.NewFlagSet("compile", flag.ContinueOnError)
- fs.SetOutput(stderr)
- out := fs.String("o", "", "write the program to `file` instead of standard output")
- name := fs.String("name", "", "program name for the certs' O= field (default: the source file's name without .gov.lisp)")
- withSource := fs.Bool("source", false, "copy the Lisp source into the file's header")
- keyFile := fs.String("key", "", "sign with the Ed25519 PKCS#8 private key in `file` (make one with: openssl genpkey -algorithm ed25519)")
- seedHex := fs.String("seed", "", "sign with keys derived from this 32-byte `hex` seed instead of a key file")
- author := fs.String("author", "", "name the author in the anchor, as `\"Name <email>\"`")
- var effective, expires dateFlag
- fs.Var(&effective, "effective", "the program takes effect at this `time` (RFC 3339 or YYYY-MM-DD; default 2000-01-01)")
- fs.Var(&expires, "expires", "the program expires at this `time` (RFC 3339 or YYYY-MM-DD; default 9999-12-31T23:59:59Z)")
- fs.Usage = func() {
- fmt.Fprintln(stderr, "usage: government compile prog.gov.lisp [-o prog.gov] [-name name] [-source]\n"+
- " [-key file | -seed hex] [-author \"Name <email>\"] [-effective time] [-expires time]")
- fs.PrintDefaults()
- }
- positional, err := parseInterspersed(fs, args)
- if err != nil {
- return exitInvalid
- }
- if len(positional) != 1 {
- fs.Usage()
- return exitInvalid
- }
- path := positional[0]
-
- src, err := os.ReadFile(path)
- if err != nil {
- fmt.Fprintln(stderr, err)
- return exitInvalid
- }
- if *name == "" {
- base := filepath.Base(path)
- *name = strings.TrimSuffix(base, ".gov.lisp")
- if *name == base {
- *name = strings.TrimSuffix(base, filepath.Ext(base))
- }
- }
- opts := lisp2gov.Options{Name: *name, IncludeSource: *withSource, Author: *author, Effective: effective.t, Expires: expires.t}
- if opts.Seed, err = signingSeed(*keyFile, *seedHex); err != nil {
- fmt.Fprintln(stderr, err)
- return exitInvalid
- }
- program, err := lisp2gov.Compile(string(src), opts)
- if err != nil {
- var se *sexpr.SyntaxError
- if errors.As(err, &se) {
- fmt.Fprintf(stderr, "%s:%v\n", path, se)
- } else {
- fmt.Fprintf(stderr, "%s: %v\n", path, err)
- }
- return exitInvalid
+func newCompileCmd() *cobra.Command {
+ var (
+ out, name, keyFile, seedHex, author string
+ withSource bool
+ effective, expires dateFlag
+ )
+ cmd := &cobra.Command{
+ Use: "compile prog.gov.lisp",
+ Short: "Transpile GovLisp source to .gov",
+ Example: " government compile quicksort.gov.lisp -o quicksort.gov\n" +
+ " government compile law.gov.lisp -o law.gov --key ada.pem --author \"Ada <ada@example.org>\"",
+ Args: oneFile,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ path := args[0]
+ src, err := readFile(path)
+ if err != nil {
+ return err
+ }
+ if name == "" {
+ base := filepath.Base(path)
+ name = strings.TrimSuffix(base, ".gov.lisp")
+ if name == base {
+ name = strings.TrimSuffix(base, filepath.Ext(base))
+ }
+ }
+ opts := lisp2gov.Options{Name: name, IncludeSource: withSource, Author: author, Effective: effective.t, Expires: expires.t}
+ if opts.Seed, err = signingSeed(keyFile, seedHex); err != nil {
+ return refused("%v", err)
+ }
+ program, err := lisp2gov.Compile(string(src), opts)
+ if err != nil {
+ var se *sexpr.SyntaxError
+ if errors.As(err, &se) {
+ return refused("%s:%v", path, se)
+ }
+ return refused("%s: %v", path, err)
+ }
+ return writeOutput(cmd, out, program)
+ },
}
+ f := cmd.Flags()
+ f.StringVarP(&out, "output", "o", "", "write the program to `file` instead of standard output")
+ f.StringVar(&name, "name", "", "program `name` for the certs' O= field (default: the source file's name without .gov.lisp)")
+ f.BoolVar(&withSource, "source", false, "copy the GovLisp source into the file's header")
+ f.StringVar(&keyFile, "key", "", "sign with the Ed25519 PKCS#8 private key in `file` (make one with: openssl genpkey -algorithm ed25519)")
+ f.StringVar(&seedHex, "seed", "", "sign with keys derived from this 32-byte `hex` seed instead of a key file")
+ f.StringVar(&author, "author", "", "name the `author` in the anchor, as \"Name <email>\"")
+ f.Var(&effective, "effective", "the program takes effect at this `time` (RFC 3339 or YYYY-MM-DD; default 2000-01-01)")
+ f.Var(&expires, "expires", "the program expires at this `time` (RFC 3339 or YYYY-MM-DD; default 9999-12-31T23:59:59Z)")
+ cmd.MarkFlagsMutuallyExclusive("key", "seed")
+ return cmd
+}
- if *out == "" {
- _, err = stdout.Write(program)
+// writeOutput writes to the -o file, or to standard output without one.
+func writeOutput(cmd *cobra.Command, path string, data []byte) error {
+ var err error
+ if path == "" {
+ _, err = cmd.OutOrStdout().Write(data)
} else {
- err = os.WriteFile(*out, program, 0o644)
+ err = os.WriteFile(path, data, 0o644)
}
if err != nil {
- fmt.Fprintln(stderr, err)
- return exitInvalid
- }
- return exitOK
-}
-
-// parseInterspersed lets flags come before or after the file name, as in
-// "government compile prog.gov.lisp -o prog.gov". The flag package alone stops
-// at the first argument that is not a flag.
-func parseInterspersed(fs *flag.FlagSet, args []string) ([]string, error) {
- var positional []string
- for {
- if err := fs.Parse(args); err != nil {
- return nil, err
- }
- args = fs.Args()
- if len(args) == 0 {
- return positional, nil
- }
- positional = append(positional, args[0])
- args = args[1:]
+ return refused("%v", err)
}
+ return nil
}
-// signingSeed reads -key or -seed. Neither means the default seed, which
+// signingSeed reads --key or --seed. Neither means the default seed, which
// is public: anyone can rebuild, amend or repeal such a program.
func signingSeed(keyFile, seedHex string) (*[32]byte, error) {
switch {
- case keyFile != "" && seedHex != "":
- return nil, errors.New("give -key or -seed, not both")
case keyFile != "":
data, err := os.ReadFile(keyFile)
if err != nil {
@@ -119,7 +99,7 @@ return seed, nil
case seedHex != "":
b, err := hex.DecodeString(seedHex)
if err != nil || len(b) != 32 {
- return nil, errors.New("-seed wants 64 hex digits (32 bytes)")
+ return nil, errors.New("--seed wants 64 hex digits (32 bytes)")
}
seed := [32]byte(b)
return &seed, nil
@@ -127,8 +107,8 @@ }
return nil, nil
}
-// dateFlag is -effective or -expires: an RFC 3339 time, or a date meaning
-// midnight UTC at its start.
+// dateFlag is --effective, --expires or one of repeal's times: an RFC 3339
+// time, or a date meaning midnight UTC at its start.
type dateFlag struct {
t time.Time
}
@@ -149,3 +129,5 @@ }
}
return errors.New("want an RFC 3339 time or a date, such as 2027-01-01")
}
+
+func (d *dateFlag) Type() string { return "time" }
diff --git a/cmd/government/inspect.go b/cmd/government/inspect.go
index 161f240cfb8471ea932dbe50c3fd198ba914684e..203be814cc0068c22ea02ab9c63b7f9aaf2b9627 100644
--- a/cmd/government/inspect.go
+++ b/cmd/government/inspect.go
@@ -1,63 +1,62 @@
package main
import (
- "flag"
"fmt"
- "io"
+
+ "github.com/spf13/cobra"
"government/gov2lisp"
"government/policy"
- "government/program"
"government/ratify"
)
// tree stops after policy processing, without decoding, so it can still
// show a graph whose shape the decoder would reject. That makes it the
// tool for looking at a broken program.
-func tree(args []string, stdout, stderr io.Writer) int {
- fs := flag.NewFlagSet("tree", flag.ContinueOnError)
- fs.SetOutput(stderr)
- lf := addLoadFlags(fs)
- fs.Usage = func() {
- fmt.Fprintln(stderr, "usage: government tree prog.gov [-at time] [-anchor file] [-crl file]... [-max-nodes n]")
- fs.PrintDefaults()
- }
- path, data, ok := oneFile(fs, args, stderr)
- if !ok {
- return exitInvalid
+func newTreeCmd() *cobra.Command {
+ var lf loadFlags
+ cmd := &cobra.Command{
+ Use: "tree prog.gov",
+ Short: "Print the policy tree",
+ Args: oneFile,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ path := args[0]
+ data, err := readFile(path)
+ if err != nil {
+ return err
+ }
+ opts := lf.programOptions()
+ certs, err := ratify.Ratify(data, ratify.Options{At: opts.At, Pin: opts.Pin, CRLs: opts.CRLs})
+ if err != nil {
+ return refused("%s: %v", path, err)
+ }
+ g, err := policy.Program(certs, policy.Options{MaxNodes: opts.MaxNodes})
+ if err != nil {
+ return refused("%s: %v", path, err)
+ }
+ fmt.Fprint(cmd.OutOrStdout(), g.Draw())
+ return nil
+ },
}
- opts := lf.programOptions()
- certs, err := ratify.Ratify(data, ratify.Options{At: opts.At, Pin: opts.Pin, CRLs: opts.CRLs})
- if err != nil {
- fmt.Fprintf(stderr, "%s: %v\n", path, err)
- return exitInvalid
- }
- g, err := policy.Program(certs, policy.Options{MaxNodes: opts.MaxNodes})
- if err != nil {
- fmt.Fprintf(stderr, "%s: %v\n", path, err)
- return exitInvalid
- }
- fmt.Fprint(stdout, g.Draw())
- return exitOK
+ lf = addLoadFlags(cmd.Flags())
+ return cmd
}
-func decompile(args []string, stdout, stderr io.Writer) int {
- fs := flag.NewFlagSet("decompile", flag.ContinueOnError)
- fs.SetOutput(stderr)
- lf := addLoadFlags(fs)
- fs.Usage = func() {
- fmt.Fprintln(stderr, "usage: government decompile prog.gov [-at time] [-anchor file] [-crl file]... [-max-nodes n]")
- fs.PrintDefaults()
- }
- path, data, ok := oneFile(fs, args, stderr)
- if !ok {
- return exitInvalid
- }
- p, err := program.Load(data, lf.programOptions())
- if err != nil {
- fmt.Fprintf(stderr, "%s: %v\n", path, err)
- return exitInvalid
+func newDecompileCmd() *cobra.Command {
+ var lf loadFlags
+ cmd := &cobra.Command{
+ Use: "decompile prog.gov",
+ Short: "Print equivalent GovLisp source",
+ Args: oneFile,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ p, err := loadProgram(args[0], lf)
+ if err != nil {
+ return err
+ }
+ fmt.Fprint(cmd.OutOrStdout(), gov2lisp.DecompileTree(p.Tree))
+ return nil
+ },
}
- fmt.Fprint(stdout, gov2lisp.DecompileTree(p.Tree))
- return exitOK
+ lf = addLoadFlags(cmd.Flags())
+ return cmd
}
diff --git a/cmd/government/inspect_test.go b/cmd/government/inspect_test.go
index b36289daf384faabdf5da410b631811be5fee896..a5f5ab2f68509de1c340cb6d2ec08207a999b9c9 100644
--- a/cmd/government/inspect_test.go
+++ b/cmd/government/inspect_test.go
@@ -29,7 +29,7 @@
func TestInspectRefusals(t *testing.T) {
gov := compileTo(t, t.TempDir(), "p", "(+ 1 2)")
for _, cmd := range []string{"tree", "decompile"} {
- if code, _, stderr := runCmd(cmd, gov, "-at", "1999-01-01T00:00:00Z"); code != exitInvalid || !strings.Contains(stderr, "E-NOT-IN-FORCE") {
+ if code, _, stderr := runCmd(cmd, gov, "--at", "1999-01-01T00:00:00Z"); code != exitInvalid || !strings.Contains(stderr, "E-NOT-IN-FORCE") {
t.Errorf("%s before the window: exit %d, %s", cmd, code, stderr)
}
if code, _, stderr := runCmd(cmd); code != exitInvalid || !strings.Contains(stderr, "usage") {
diff --git a/cmd/government/load.go b/cmd/government/load.go
index 5b9290a7e1741ec8c9ab4028d479a9a3ca1cd1ac..58780daf133d1125cedf65f837ce62af5e800c0a 100644
--- a/cmd/government/load.go
+++ b/cmd/government/load.go
@@ -1,12 +1,11 @@
package main
import (
- "flag"
- "fmt"
- "io"
"os"
"strings"
+ "github.com/spf13/pflag"
+
"government/policy"
"government/program"
)
@@ -19,7 +18,7 @@ crls *crlFlag
maxNodes *int
}
-func addLoadFlags(fs *flag.FlagSet) loadFlags {
+func addLoadFlags(fs *pflag.FlagSet) loadFlags {
lf := loadFlags{
at: addAtFlag(fs),
anchor: addAnchorFlag(fs),
@@ -30,7 +29,7 @@ fs.Var(lf.crls, "crl", "apply the repeal list in `file` (repeatable)")
return lf
}
-// crlFlag is -crl, which may be given several times: each is a file of
+// crlFlag is --crl, which may be given several times: each is a file of
// repeal lists to check the program against.
type crlFlag struct {
paths []string
@@ -54,26 +53,16 @@ c.data = append(c.data, data)
return nil
}
+func (c *crlFlag) Type() string { return "file" }
+
func (lf loadFlags) programOptions() program.Options {
return program.Options{At: lf.at.Time(), Pin: lf.anchor.Pin(), CRLs: lf.crls.data, MaxNodes: *lf.maxNodes}
}
-// oneFile parses a command's arguments, which must name exactly one .gov
-// file, and reads it. It prints its own errors.
-func oneFile(fs *flag.FlagSet, args []string, stderr io.Writer) (path string, data []byte, ok bool) {
- positional, err := parseInterspersed(fs, args)
+func readFile(path string) ([]byte, error) {
+ data, err := os.ReadFile(path)
if err != nil {
- return "", nil, false
- }
- if len(positional) != 1 {
- fs.Usage()
- return "", nil, false
+ return nil, refused("%v", err)
}
- path = positional[0]
- data, err = os.ReadFile(path)
- if err != nil {
- fmt.Fprintln(stderr, err)
- return "", nil, false
- }
- return path, data, true
+ return data, nil
}
diff --git a/cmd/government/main.go b/cmd/government/main.go
index b90e93af750920a1b7431ba5d34b185cb0d1c3fd..1455493a4a99141936d3ccbd235531b8f2f87fb3 100644
--- a/cmd/government/main.go
+++ b/cmd/government/main.go
@@ -3,9 +3,13 @@ // GOVERNMENT programs.
package main
import (
+ "errors"
"fmt"
"io"
"os"
+ "strings"
+
+ "github.com/spf13/cobra"
)
// Exit codes: a runtime error is 1; anything that stops a program from
@@ -16,43 +20,111 @@ exitRuntime = 1
exitInvalid = 2
)
-const usage = `usage: government <command> [arguments]
-
-commands:
- compile transpile Lisp source to .gov
- run ratify, decode and evaluate a .gov program
- tree print the policy tree
- decompile print equivalent Lisp source
- verify ratify and decode only, and print a certificate of ratification
- repeal write a CRL repealing one depth of a program
-`
-
func main() {
os.Exit(run(os.Args[1:], os.Stdout, os.Stderr))
}
+// exitError is an error a command has already worded for the user, with
+// the exit code it should end with. Any other error comes from cobra
+// itself (an unknown command or flag, a missing file name) and is a
+// usage error.
+type exitError struct {
+ code int
+ err error
+}
+
+func (e *exitError) Error() string { return e.err.Error() }
+
+// refused is a program, file or flag that stops a command before it runs
+// anything.
+func refused(format string, args ...any) error {
+ return &exitError{exitInvalid, fmt.Errorf(format, args...)}
+}
+
func run(args []string, stdout, stderr io.Writer) int {
- if len(args) == 0 {
- fmt.Fprint(stderr, usage)
- return exitInvalid
+ root := newRootCmd()
+ root.SetArgs(args)
+ root.SetOut(stdout)
+ root.SetErr(stderr)
+ cmd, err := root.ExecuteC()
+ if err == nil {
+ return exitOK
}
- switch args[0] {
- case "compile":
- return compile(args[1:], stdout, stderr)
- case "run":
- return runProgram(args[1:], stdout, stderr)
- case "tree":
- return tree(args[1:], stdout, stderr)
- case "decompile":
- return decompile(args[1:], stdout, stderr)
- case "verify":
- return verify(args[1:], stdout, stderr)
- case "repeal":
- return repeal(args[1:], stdout, stderr)
- case "help", "-h", "-help", "--help":
- fmt.Fprint(stdout, usage)
- return exitOK
+ var ee *exitError
+ if errors.As(err, &ee) {
+ fmt.Fprintln(stderr, ee)
+ return ee.code
}
- fmt.Fprintf(stderr, "government: unknown command %q\n\n%s", args[0], usage)
+ fmt.Fprintf(stderr, "%s: %v\nRun '%s --help' for usage.\n", cmd.CommandPath(), err, cmd.CommandPath())
return exitInvalid
}
+
+// newRootCmd builds the command tree afresh, so each run starts with its
+// flags unset. With no command, the root runs its argument as a program,
+// so "government prog.gov" is "government run prog.gov", as with python or
+// node; a command name always wins over a file of the same name.
+func newRootCmd() *cobra.Command {
+ var lf loadFlags
+ root := &cobra.Command{
+ Use: "government [prog.gov]",
+ Short: "Compile, check, inspect, run and repeal GOVERNMENT programs",
+ Long: "GOVERNMENT programs are chains of X.509 certificates in .gov files.\n" +
+ "A program runs only once its chain is ratified: signed, in force and not repealed.\n\n" +
+ "\"government prog.gov\" runs a program, the same as \"government run prog.gov\".",
+ Args: func(cmd *cobra.Command, args []string) error {
+ if len(args) == 0 {
+ return nil
+ }
+ if err := checkCommand(cmd, args[0]); err != nil {
+ return err
+ }
+ return oneFile(cmd, args)
+ },
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if len(args) == 0 {
+ return cmd.Help()
+ }
+ return runFile(cmd, args[0], lf)
+ },
+ SilenceUsage: true,
+ SilenceErrors: true,
+ SuggestionsMinimumDistance: 2,
+ CompletionOptions: cobra.CompletionOptions{DisableDefaultCmd: true},
+ }
+ lf = addLoadFlags(root.Flags())
+ root.AddCommand(
+ newCompileCmd(),
+ newRunCmd(),
+ newTreeCmd(),
+ newDecompileCmd(),
+ newVerifyCmd(),
+ newRepealCmd(),
+ )
+ return root
+}
+
+// checkCommand catches a mistyped command before it is taken for a
+// program: an argument that is not a file and does not end in .gov is
+// reported as an unknown command, with cobra's guess at the one meant.
+func checkCommand(cmd *cobra.Command, arg string) error {
+ if strings.HasSuffix(arg, ".gov") {
+ return nil
+ }
+ if _, err := os.Stat(arg); err == nil {
+ return nil
+ }
+ msg := fmt.Sprintf("unknown command %q, and no file by that name", arg)
+ if s := cmd.SuggestionsFor(arg); len(s) > 0 {
+ msg += "; did you mean " + strings.Join(s, " or ") + "?"
+ }
+ return errors.New(msg)
+}
+
+// oneFile is the argument check for every command: each takes exactly one
+// file.
+func oneFile(cmd *cobra.Command, args []string) error {
+ if len(args) != 1 {
+ return fmt.Errorf("want one file, got %d", len(args))
+ }
+ return nil
+}
diff --git a/cmd/government/main_test.go b/cmd/government/main_test.go
index e6c3a571c1e8e4aceaff815ff6f6fd05be2d2f19..bb325486aa9a954ae1d41bf78393e159a9d00b25 100644
--- a/cmd/government/main_test.go
+++ b/cmd/government/main_test.go
@@ -50,7 +50,7 @@ }
}
func TestCompileSourceFlag(t *testing.T) {
- code, stdout, stderr := runCmd("compile", "-source", writeSource(t, "sq", sqSource))
+ code, stdout, stderr := runCmd("compile", "--source", writeSource(t, "sq", sqSource))
if code != exitOK {
t.Fatalf("exit %d: %s", code, stderr)
}
@@ -88,7 +88,8 @@ {[]string{"compile", filepath.Join(dir, "missing.gov.lisp")}, "no such file"},
{[]string{"compile"}, "usage"},
{[]string{"compile", "a.gov.lisp", "b.gov.lisp"}, "usage"},
{[]string{"frobnicate"}, "unknown command"},
- {nil, "usage"},
+ {[]string{"compile", "--frobnicate", "x.gov.lisp"}, "unknown flag: --frobnicate"},
+ {[]string{"compile", "-name", "x", "x.gov.lisp"}, "unknown shorthand flag: 'n' in -name"},
}
for _, tt := range tests {
code, _, stderr := runCmd(tt.args...)
@@ -97,3 +98,20 @@ t.Errorf("%v: exit %d, stderr %q; want exit %d mentioning %q", tt.args, code, stderr, exitInvalid, tt.want)
}
}
}
+
+// TestHelp checks that bare "government" and --help list the commands,
+// and that each command has help of its own.
+func TestHelp(t *testing.T) {
+ for _, args := range [][]string{nil, {"--help"}, {"help"}} {
+ code, stdout, _ := runCmd(args...)
+ if code != exitOK || !strings.Contains(stdout, "repeal") || !strings.Contains(stdout, "Available Commands") {
+ t.Errorf("%v: exit %d, %q", args, code, stdout)
+ }
+ }
+ for _, cmd := range []string{"compile", "run", "tree", "decompile", "verify", "repeal"} {
+ code, stdout, _ := runCmd(cmd, "--help")
+ if code != exitOK || !strings.Contains(stdout, "government "+cmd) {
+ t.Errorf("%s --help: exit %d, %q", cmd, code, stdout)
+ }
+ }
+}
diff --git a/cmd/government/repeal.go b/cmd/government/repeal.go
index 6a6f6c5be9f81e38cdc11a257b03913194625d81..8d2112ead93770b2f88d9d3cbca3d1235dfd9edf 100644
--- a/cmd/government/repeal.go
+++ b/cmd/government/repeal.go
@@ -1,12 +1,10 @@
package main
import (
- "flag"
- "fmt"
- "io"
- "os"
"strings"
"time"
+
+ "github.com/spf13/cobra"
"government/lisp2gov"
"government/ratify"
@@ -14,74 +12,68 @@ )
// repeal writes a CRL that strikes down a program. It needs the key the
// program was compiled with.
-func repeal(args []string, stdout, stderr io.Writer) int {
- fs := flag.NewFlagSet("repeal", flag.ContinueOnError)
- fs.SetOutput(stderr)
- out := fs.String("o", "", "write the CRL to `file` instead of standard output")
- keyFile := fs.String("key", "", "the Ed25519 PKCS#8 private key `file` the program was compiled with")
- seedHex := fs.String("seed", "", "the `hex` seed the program was compiled with, instead of a key file")
- reason := fs.String("reason", "unspecified", "the CRLReason: `name` is one of "+strings.Join(ratify.ReasonNames(), ", "))
- var at, issued, nextUpdate dateFlag
- fs.Var(&at, "at", "the repeal takes effect at this `time` (default now); a future time schedules it")
- fs.Var(&issued, "issued", "the CRL's issue `time` (thisUpdate; default now)")
- fs.Var(&nextUpdate, "next-update", "the CRL goes stale at this `time` (default 9999-12-31T23:59:59Z, never)")
- fs.Usage = func() {
- fmt.Fprintln(stderr, "usage: government repeal prog.gov [-o repeal.crl] [-key file | -seed hex]\n"+
- " [-reason name] [-at time] [-issued time] [-next-update time]")
- fs.PrintDefaults()
- }
- path, data, ok := oneFile(fs, args, stderr)
- if !ok {
- return exitInvalid
- }
- code, known := ratify.Reasons[*reason]
- if !known {
- fmt.Fprintf(stderr, "unknown reason %q; want one of %s\n", *reason, strings.Join(ratify.ReasonNames(), ", "))
- return exitInvalid
- }
- seed, err := signingSeed(*keyFile, *seedHex)
- if err != nil {
- fmt.Fprintln(stderr, err)
- return exitInvalid
- }
+func newRepealCmd() *cobra.Command {
+ var (
+ out, keyFile, seedHex, reason string
+ at, issued, nextUpdate dateFlag
+ )
+ cmd := &cobra.Command{
+ Use: "repeal prog.gov",
+ Short: "Write a CRL repealing a program",
+ Example: " government repeal law.gov --key ada.pem --reason superseded -o repeal.crl\n government run law.gov --crl repeal.crl",
+ Args: oneFile,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ path := args[0]
+ code, known := ratify.Reasons[reason]
+ if !known {
+ return refused("unknown reason %q; want one of %s", reason, strings.Join(ratify.ReasonNames(), ", "))
+ }
+ seed, err := signingSeed(keyFile, seedHex)
+ if err != nil {
+ return refused("%v", err)
+ }
+ data, err := readFile(path)
+ if err != nil {
+ return err
+ }
- // A program is repealed whatever its dates, so only its chain is
- // checked here, not its window in force.
- certs, err := ratify.Load(data)
- if err == nil {
- certs, err = ratify.Order(certs)
- }
- if err == nil {
- err = ratify.CheckChain(certs)
- }
- if err != nil {
- fmt.Fprintf(stderr, "%s: %v\n", path, err)
- return exitInvalid
- }
+ // A program is repealed whatever its dates, so only its chain
+ // is checked here, not its window in force.
+ certs, err := ratify.Load(data)
+ if err == nil {
+ certs, err = ratify.Order(certs)
+ }
+ if err == nil {
+ err = ratify.CheckChain(certs)
+ }
+ if err != nil {
+ return refused("%s: %v", path, err)
+ }
- now := time.Now().UTC().Truncate(time.Second)
- opts := lisp2gov.RepealOptions{
- Seed: seed,
- Reason: code,
- At: orDefault(at.t, now),
- Issued: orDefault(issued.t, now),
- NextUpdate: orDefault(nextUpdate.t, time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC)),
+ now := time.Now().UTC().Truncate(time.Second)
+ crl, err := lisp2gov.Repeal(certs, lisp2gov.RepealOptions{
+ Seed: seed,
+ Reason: code,
+ At: orDefault(at.t, now),
+ Issued: orDefault(issued.t, now),
+ NextUpdate: orDefault(nextUpdate.t, time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC)),
+ })
+ if err != nil {
+ return refused("%s: %v", path, err)
+ }
+ return writeOutput(cmd, out, crl)
+ },
}
- crl, err := lisp2gov.Repeal(certs, opts)
- if err != nil {
- fmt.Fprintf(stderr, "%s: %v\n", path, err)
- return exitInvalid
- }
- if *out == "" {
- _, err = stdout.Write(crl)
- } else {
- err = os.WriteFile(*out, crl, 0o644)
- }
- if err != nil {
- fmt.Fprintln(stderr, err)
- return exitInvalid
- }
- return exitOK
+ f := cmd.Flags()
+ f.StringVarP(&out, "output", "o", "", "write the CRL to `file` instead of standard output")
+ f.StringVar(&keyFile, "key", "", "the Ed25519 PKCS#8 private key `file` the program was compiled with")
+ f.StringVar(&seedHex, "seed", "", "the `hex` seed the program was compiled with, instead of a key file")
+ f.StringVar(&reason, "reason", "unspecified", "the CRLReason: `name` is one of "+strings.Join(ratify.ReasonNames(), ", "))
+ f.Var(&at, "at", "the repeal takes effect at this `time` (default now); a future time schedules it")
+ f.Var(&issued, "issued", "the CRL's issue `time` (thisUpdate; default now)")
+ f.Var(&nextUpdate, "next-update", "the CRL goes stale at this `time` (default 9999-12-31T23:59:59Z, never)")
+ cmd.MarkFlagsMutuallyExclusive("key", "seed")
+ return cmd
}
func orDefault(t, def time.Time) time.Time {
diff --git a/cmd/government/repeal_test.go b/cmd/government/repeal_test.go
index 484fcac027a324dd704385bc342db6f819053352..0bdd356d81f25f2e623aec1bf123735e2208fe97 100644
--- a/cmd/government/repeal_test.go
+++ b/cmd/government/repeal_test.go
@@ -14,12 +14,12 @@ dir := t.TempDir()
key := writeKey(t, dir, "ada", 1)
src := writeSource(t, "law", "(+ 1 (* 2 3))")
gov := filepath.Join(dir, "law.gov")
- if code, _, stderr := runCmd("compile", src, "-o", gov, "-key", key); code != exitOK {
+ if code, _, stderr := runCmd("compile", src, "-o", gov, "--key", key); code != exitOK {
t.Fatal(stderr)
}
crlPath := filepath.Join(dir, "repeal.crl")
- code, _, stderr := runCmd("repeal", gov, "-key", key, "-reason", "superseded",
- "-at", "2027-03-01", "-issued", "2027-02-01", "-o", crlPath)
+ code, _, stderr := runCmd("repeal", gov, "--key", key, "--reason", "superseded",
+ "--at", "2027-03-01", "--issued", "2027-02-01", "-o", crlPath)
if code != exitOK {
t.Fatalf("exit %d: %s", code, stderr)
}
@@ -45,15 +45,15 @@ key := writeKey(t, dir, "ada", 1)
other := writeKey(t, dir, "bob", 2)
src := writeSource(t, "law", "(+ 1 2)")
gov := filepath.Join(dir, "law.gov")
- runCmd("compile", src, "-o", gov, "-key", key)
+ runCmd("compile", src, "-o", gov, "--key", key)
tests := []struct {
args []string
want string
}{
- {[]string{"repeal", gov, "-key", other}, "did not compile"},
+ {[]string{"repeal", gov, "--key", other}, "did not compile"},
{[]string{"repeal", gov}, "did not compile"},
- {[]string{"repeal", gov, "-key", key, "-reason", "boredom"}, "unknown reason"},
- {[]string{"repeal", gov, "-key", key, "-issued", "2027-01-01", "-next-update", "2026-01-01"}, "go stale"},
+ {[]string{"repeal", gov, "--key", key, "--reason", "boredom"}, "unknown reason"},
+ {[]string{"repeal", gov, "--key", key, "--issued", "2027-01-01", "--next-update", "2026-01-01"}, "go stale"},
{[]string{"repeal"}, "usage"},
}
for _, tt := range tests {
@@ -84,25 +84,25 @@ dir := t.TempDir()
key := writeKey(t, dir, "ada", 1)
src := writeSource(t, "law", "(+ 1 (* 2 3))")
gov := filepath.Join(dir, "law.gov")
- runCmd("compile", src, "-o", gov, "-key", key)
+ runCmd("compile", src, "-o", gov, "--key", key)
crl := filepath.Join(dir, "repeal.crl")
- if code, _, stderr := runCmd("repeal", gov, "-key", key, "-reason", "superseded",
- "-at", "2027-03-01", "-issued", "2027-01-01", "-o", crl); code != exitOK {
+ if code, _, stderr := runCmd("repeal", gov, "--key", key, "--reason", "superseded",
+ "--at", "2027-03-01", "--issued", "2027-01-01", "-o", crl); code != exitOK {
t.Fatal(stderr)
}
before := "2027-02-01T00:00:00Z"
after := "2027-04-01T00:00:00Z"
- if code, stdout, stderr := runCmd("run", gov, "-crl", crl, "-at", before); code != exitOK || stdout != "7\n" {
+ if code, stdout, stderr := runCmd("run", gov, "--crl", crl, "--at", before); code != exitOK || stdout != "7\n" {
t.Errorf("before the repeal: exit %d, %q, %s", code, stdout, stderr)
}
for _, cmd := range []string{"run", "verify", "tree", "decompile"} {
- code, stdout, stderr := runCmd(cmd, gov, "-crl", crl, "-at", after)
+ code, stdout, stderr := runCmd(cmd, gov, "--crl", crl, "--at", after)
if code != exitInvalid || stdout != "" || !strings.Contains(stderr, "E-REPEALED: depth 1 repealed 2027-03-01 (superseded)") {
t.Errorf("%s after the repeal: exit %d, stdout %q, stderr %q", cmd, code, stdout, stderr)
}
}
- if code, _, stderr := runCmd("run", gov, "-crl", filepath.Join(dir, "missing.crl")); code != exitInvalid || !strings.Contains(stderr, "no such file") {
+ if code, _, stderr := runCmd("run", gov, "--crl", filepath.Join(dir, "missing.crl")); code != exitInvalid || !strings.Contains(stderr, "no such file") {
t.Errorf("missing CRL file: exit %d, %s", code, stderr)
}
}
diff --git a/cmd/government/run.go b/cmd/government/run.go
index 59a27e9bf77c0ecdb5343e73893b87cb9acacac4..c3a65c56193c7cc0c05e959d81febafa0acd15f9 100644
--- a/cmd/government/run.go
+++ b/cmd/government/run.go
@@ -1,33 +1,48 @@
package main
import (
- "flag"
"fmt"
- "io"
+
+ "github.com/spf13/cobra"
"government/program"
)
-func runProgram(args []string, stdout, stderr io.Writer) int {
- fs := flag.NewFlagSet("run", flag.ContinueOnError)
- fs.SetOutput(stderr)
- lf := addLoadFlags(fs)
- fs.Usage = func() {
- fmt.Fprintln(stderr, "usage: government run prog.gov [-at time] [-anchor file] [-crl file]... [-max-nodes n]")
- fs.PrintDefaults()
+func newRunCmd() *cobra.Command {
+ var lf loadFlags
+ cmd := &cobra.Command{
+ Use: "run prog.gov",
+ Short: "Ratify, decode and evaluate a .gov program",
+ Example: " government run quicksort.gov\n government quicksort.gov\n government run law.gov --anchor ada.gov --crl repeal.crl",
+ Args: oneFile,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runFile(cmd, args[0], lf)
+ },
+ }
+ lf = addLoadFlags(cmd.Flags())
+ return cmd
+}
+
+func runFile(cmd *cobra.Command, path string, lf loadFlags) error {
+ p, err := loadProgram(path, lf)
+ if err != nil {
+ return err
+ }
+ if err := p.Run(cmd.OutOrStdout()); err != nil {
+ return &exitError{exitRuntime, fmt.Errorf("%s: %s", path, p.Describe(err))}
}
- path, data, ok := oneFile(fs, args, stderr)
- if !ok {
- return exitInvalid
+ return nil
+}
+
+// loadProgram reads, ratifies and decodes a .gov file.
+func loadProgram(path string, lf loadFlags) (*program.Program, error) {
+ data, err := readFile(path)
+ if err != nil {
+ return nil, err
}
p, err := program.Load(data, lf.programOptions())
if err != nil {
- fmt.Fprintf(stderr, "%s: %v\n", path, err)
- return exitInvalid
+ return nil, refused("%s: %v", path, err)
}
- if err := p.Run(stdout); err != nil {
- fmt.Fprintf(stderr, "%s: %s\n", path, p.Describe(err))
- return exitRuntime
- }
- return exitOK
+ return p, nil
}
diff --git a/cmd/government/run_test.go b/cmd/government/run_test.go
index 4514bef27a112b35eefb16a52785bd7dcc85c509..c57e8e76d7dc995b173a461fa15f14f69cdb30f1 100644
--- a/cmd/government/run_test.go
+++ b/cmd/government/run_test.go
@@ -49,9 +49,9 @@ tests := []struct {
args []string
want string
}{
- {[]string{"run", gov, "-at", "1999-01-01T00:00:00Z"}, "E-NOT-IN-FORCE"},
- {[]string{"run", gov, "-max-nodes", "2"}, "E-TOO-LARGE"},
- {[]string{"run", gov, "-at", "yesterday"}, "RFC 3339"},
+ {[]string{"run", gov, "--at", "1999-01-01T00:00:00Z"}, "E-NOT-IN-FORCE"},
+ {[]string{"run", gov, "--max-nodes", "2"}, "E-TOO-LARGE"},
+ {[]string{"run", gov, "--at", "yesterday"}, "RFC 3339"},
{[]string{"run", tampered}, "E-"},
{[]string{"run", filepath.Join(dir, "missing.gov")}, "no such file"},
{[]string{"run"}, "usage"},
@@ -68,8 +68,48 @@ func TestRunWithAnchor(t *testing.T) {
dir := t.TempDir()
mine := compileTo(t, dir, "mine", "(+ 1 2)")
other := compileTo(t, dir, "other", "(* 2 3)")
- if code, stdout, stderr := runCmd("run", "-anchor", mine, other); code != exitOK || stdout != "6\n" {
+ if code, stdout, stderr := runCmd("run", "--anchor", mine, other); code != exitOK || stdout != "6\n" {
// Same default seed, so the same author: the pin matches.
t.Errorf("same author: exit %d, %q, %q", code, stdout, stderr)
}
}
+
+// TestRunIsTheDefault checks "government prog.gov", the run command
+// without its name, and that command names and typos still mean commands.
+func TestRunIsTheDefault(t *testing.T) {
+ dir := t.TempDir()
+ gov := compileTo(t, dir, "p", "(+ 1 2)")
+ if code, stdout, stderr := runCmd(gov); code != exitOK || stdout != "3\n" {
+ t.Errorf("government p.gov: exit %d, %q, %s", code, stdout, stderr)
+ }
+ if code, stdout, stderr := runCmd("--at", "2027-06-01T00:00:00Z", gov, "--max-nodes", "100"); code != exitOK || stdout != "3\n" {
+ t.Errorf("with flags on both sides: exit %d, %q, %s", code, stdout, stderr)
+ }
+ if code, _, stderr := runCmd(gov, "--at", "1999-01-01T00:00:00Z"); code != exitInvalid || !strings.Contains(stderr, "E-NOT-IN-FORCE") {
+ t.Errorf("refused program: exit %d, %s", code, stderr)
+ }
+
+ // A file with no .gov extension still runs if it exists.
+ bare := filepath.Join(dir, "law")
+ data, _ := os.ReadFile(gov)
+ os.WriteFile(bare, data, 0o644)
+ if code, stdout, stderr := runCmd(bare); code != exitOK || stdout != "3\n" {
+ t.Errorf("file without .gov: exit %d, %q, %s", code, stdout, stderr)
+ }
+
+ tests := []struct {
+ args []string
+ want string
+ }{
+ {[]string{"compiel", "x.gov.lisp"}, "did you mean compile?"},
+ {[]string{"frobnicate"}, "unknown command \"frobnicate\""},
+ {[]string{filepath.Join(dir, "missing.gov")}, "no such file"},
+ {[]string{gov, gov}, "want one file, got 2"},
+ }
+ for _, tt := range tests {
+ code, _, stderr := runCmd(tt.args...)
+ if code != exitInvalid || !strings.Contains(stderr, tt.want) {
+ t.Errorf("%v: exit %d, %q; want %q", tt.args, code, stderr, tt.want)
+ }
+ }
+}
diff --git a/cmd/government/verify.go b/cmd/government/verify.go
index f125e7a02aa07ba445b35cad0cc40a3f662dea3c..6cc29182c95b87ff260966ba96385094f1905896 100644
--- a/cmd/government/verify.go
+++ b/cmd/government/verify.go
@@ -3,11 +3,11 @@
import (
"bytes"
"crypto/x509"
- "flag"
"fmt"
- "io"
"strings"
"time"
+
+ "github.com/spf13/cobra"
"government/lisp2gov"
"government/program"
@@ -17,25 +17,23 @@
// verify answers "is this program lawful?" without asking "what does it
// do?": it runs every check run does, decodes the program, and stops
// before evaluating anything.
-func verify(args []string, stdout, stderr io.Writer) int {
- fs := flag.NewFlagSet("verify", flag.ContinueOnError)
- fs.SetOutput(stderr)
- lf := addLoadFlags(fs)
- fs.Usage = func() {
- fmt.Fprintln(stderr, "usage: government verify prog.gov [-at time] [-anchor file] [-crl file]... [-max-nodes n]")
- fs.PrintDefaults()
- }
- path, data, ok := oneFile(fs, args, stderr)
- if !ok {
- return exitInvalid
- }
- p, err := program.Load(data, lf.programOptions())
- if err != nil {
- fmt.Fprintf(stderr, "%s: %v\n", path, err)
- return exitInvalid
+func newVerifyCmd() *cobra.Command {
+ var lf loadFlags
+ cmd := &cobra.Command{
+ Use: "verify prog.gov",
+ Short: "Ratify and decode only, and print a certificate of ratification",
+ Args: oneFile,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ p, err := loadProgram(args[0], lf)
+ if err != nil {
+ return err
+ }
+ fmt.Fprint(cmd.OutOrStdout(), certificate(p))
+ return nil
+ },
}
- fmt.Fprint(stdout, certificate(p))
- return exitOK
+ lf = addLoadFlags(cmd.Flags())
+ return cmd
}
// certificate is the certificate of ratification: who ratified the
diff --git a/cmd/government/verify_test.go b/cmd/government/verify_test.go
index e77b70d9db4a5b9765736180b49809189d8f8b85..6159734e723dd392bc4bccbfcec6cb7c5fea2d95 100644
--- a/cmd/government/verify_test.go
+++ b/cmd/government/verify_test.go
@@ -106,9 +106,9 @@ {"flipped signature byte", []string{"verify", writeBlocks(t, dir, "flipped", flipped)}, "E-TAMPERED: clause at depth 2"},
{"dropped depth", []string{"verify", writeBlocks(t, dir, "dropped", [][]byte{blocks[0], blocks[1], blocks[3]})}, "E-CHAIN"},
{"duplicated cert", []string{"verify", writeBlocks(t, dir, "dup", append(append([][]byte(nil), blocks...), blocks[1]))}, "E-CHAIN"},
{"private key block", []string{"verify", writeBlocks(t, dir, "key", append(append([][]byte(nil), blocks...), []byte{1}), "", "", "", "", "PRIVATE KEY")}, "E-MALFORMED"},
- {"expired", []string{"verify", gov, "-at", "9999-12-31T23:59:59.5Z"}, "E-LAPSED"},
- {"not yet in force", []string{"verify", gov, "-at", "1999-12-31T23:59:59Z"}, "E-NOT-IN-FORCE"},
- {"foreign key", []string{"verify", foreign, "-anchor", gov}, "E-FOREIGN"},
+ {"expired", []string{"verify", gov, "--at", "9999-12-31T23:59:59.5Z"}, "E-LAPSED"},
+ {"not yet in force", []string{"verify", gov, "--at", "1999-12-31T23:59:59Z"}, "E-NOT-IN-FORCE"},
+ {"foreign key", []string{"verify", foreign, "--anchor", gov}, "E-FOREIGN"},
}
for _, tt := range tests {
code, stdout, stderr := runCmd(tt.args...)
diff --git a/go.mod b/go.mod
index 81389d6b8ad42fd056b61e099fd6ad3d81a91ebc..0c97266440a3efc936f94533140772c6ba00a769 100644
--- a/go.mod
+++ b/go.mod
@@ -1,3 +1,10 @@
module government
go 1.24
+
+require (
+ github.com/spf13/cobra v1.10.2
+ github.com/spf13/pflag v1.0.9
+)
+
+require github.com/inconshreveable/mousetrap v1.1.0 // indirect
diff --git a/go.sum b/go.sum
new file mode 100644
index 0000000000000000000000000000000000000000..a6ee3e0fb39674f5ff47f1f0480a532bde4abf20
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,10 @@
+github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
+github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
+github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
+github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
+github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
+github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
+github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
+github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
+go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=