Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions packages/forge/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,41 @@ has a key to rewrite is not a minimal edit. The order of its keys is kept.

</details>

## Inspecting a document

`forge inspect` prints what forge reads in a document, as JSON, without
generating anything. `forge inspect methods` prints the methods a document
makes, as an array. Each method has the group path and name forge gives it, in
kebab-case, which is how forge reads `x-forge-group-name`,
`x-forge-method-name` and `operationId`, so a tool can compare the methods of
two versions of a document without naming them itself.

```sh
npx forge inspect methods openapi.json

# Other tools' extensions are read only once they are normalized.
npx forge normalize openapi.json | npx forge inspect methods -
```

```json
[
{
"group": ["dns", "records"],
"name": "list",
"method": "GET",
"path": "/zones/{zone_id}/dns_records",
"hidden": false,
"deprecated": false,
"availability": "generally-available"
}
]
```

Methods come in the order of their groups, depth first from the root, and by
name within a group. `availability` is `null` when the operation does not say.
A document forge cannot read, such as one with two methods of the same name in
a group, is an error, as it is for generating an SDK.

## Plugins

A plugin generates an SDK, or anything else, from the document: forge parses
Expand Down
63 changes: 63 additions & 0 deletions src/bin/forge/inspect.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
//! `forge inspect`, which prints what forge reads in a document.

use std::io::{self, Write};
use std::path::PathBuf;

use forge::{Err, Forge, Method, Name};
use serde_json::{Value, json};

#[derive(clap::Args)]
pub struct Args {
#[command(subcommand)]
command: Command,
}

/// What `forge inspect` prints.
#[derive(clap::Subcommand)]
enum Command {
/// Print the methods a document makes, as JSON.
///
/// Each method has its group path and name, in kebab-case, as forge
/// resolves them from x-forge-group-name, x-forge-method-name and the
/// operationId, with its HTTP method and path. Other tools' extensions
/// are not read: run `forge normalize` on the document first.
Methods(Spec),
}

#[derive(clap::Args)]
struct Spec {
/// The OpenAPI JSON document, or - to read it from standard input.
spec: PathBuf,
}

pub fn run(args: Args) -> Result<(), Err> {
match args.command {
Command::Methods(Spec { spec }) => print(&methods(&super::read(&spec)?)),
}
}

/// Prints `value` to standard output.
fn print(value: &Value) -> Result<(), Err> {
let mut out = io::stdout().lock();
serde_json::to_writer_pretty(&mut out, value)?;
writeln!(out)?;
Ok(())
}

/// Returns every method of `forge` as JSON, in the order of
/// [`Forge::groups`], and by name within a group.
fn methods(forge: &Forge) -> Value {
forge.groups().flat_map(|group| group.methods()).map(method).collect()
}

fn method(method: Method<'_>) -> Value {
json!({
"group": method.group().path().map(Name::kebab).collect::<Vec<_>>(),
"name": method.name().kebab(),
"method": method.http_method().as_str(),
"path": method.path(),
"hidden": method.is_hidden(),
"deprecated": method.is_deprecated(),
"availability": method.availability().map(|availability| availability.as_str()),
})
}
14 changes: 12 additions & 2 deletions src/bin/forge/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
//! forge openapi.json --target mcp --out tools
//! forge openapi.json --target wasm://plugin.wasm --out sdk
//! forge normalize specs/*.json
//! forge inspect methods openapi.json
//! ```

use std::fs;
Expand All @@ -18,6 +19,7 @@ use forge::{Err, Forge, Plugin};
use strum::{EnumString, VariantNames};

mod capnweb;
mod inspect;
mod mcp;
mod normalize;
mod ts;
Expand Down Expand Up @@ -52,6 +54,8 @@ enum Command {
/// that has none is left as it is. A native key is never replaced: when a
/// document says the same thing twice, the native key is kept.
Normalize(normalize::Args),
/// Print what forge reads in a document, as JSON.
Inspect(inspect::Args),
}

/// What forge generates an SDK with.
Expand Down Expand Up @@ -107,8 +111,10 @@ fn main() -> ExitCode {

/// Does what `args` ask for.
fn run(args: Args) -> Result<(), Err> {
if let Some(Command::Normalize(args)) = args.command {
return normalize::run(args);
match args.command {
Some(Command::Normalize(args)) => return normalize::run(args),
Some(Command::Inspect(args)) => return inspect::run(args),
None => {}
}
// They are required, which a command is the only way around.
let (Some(spec), Some(target), Some(out)) = (args.spec, args.target, args.out) else {
Expand Down Expand Up @@ -174,6 +180,10 @@ mod tests {
let command = parse(&["normalize", "--check", "a.json"]).unwrap();
assert!(matches!(command.command, Some(Command::Normalize(_))) && command.spec.is_none());

let command = parse(&["inspect", "methods", "a.json"]).unwrap();
assert!(matches!(command.command, Some(Command::Inspect(_))) && command.spec.is_none());
assert!(parse(&["inspect", "a.json"]).is_err());

let document = parse(&["./normalize", "--target", "ts", "--out", "sdk"]).unwrap();
assert!(document.command.is_none() && document.spec.as_deref() == Some(Path::new("./normalize")));

Expand Down
86 changes: 86 additions & 0 deletions tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,89 @@ fn capnweb() {
);
std::fs::remove_dir_all(&out).unwrap();
}

#[test]
fn inspect_methods() {
let spec = r#"{
"openapi": "3.0.3",
"info": {"title": "t", "version": "1"},
"paths": {
"/zones/{zone_id}/dns_records": {
"get": {
"x-forge-group-name": "dns.records",
"x-forge-method-name": "listRecords",
"x-forge-availability": "beta",
"responses": {"200": {"description": "ok"}}
},
"post": {
"operationId": "dns.records.create",
"x-forge-hidden": true,
"deprecated": true,
"responses": {"200": {"description": "ok"}}
},
"put": {
"operationId": "dns.records.skipped",
"x-forge-skip": true,
"responses": {"200": {"description": "ok"}}
}
},
"/user": {
"get": {
"operationId": "getUser",
"responses": {"200": {"description": "ok"}}
}
}
}
}"#;
let out = forge(&["inspect", "methods", "-"], spec);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
let methods: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
assert_eq!(
methods,
serde_json::json!([
{
"group": [],
"name": "get-user",
"method": "GET",
"path": "/user",
"hidden": false,
"deprecated": false,
"availability": null
},
{
"group": ["dns", "records"],
"name": "create",
"method": "POST",
"path": "/zones/{zone_id}/dns_records",
"hidden": true,
"deprecated": true,
"availability": null
},
{
"group": ["dns", "records"],
"name": "list-records",
"method": "GET",
"path": "/zones/{zone_id}/dns_records",
"hidden": false,
"deprecated": false,
"availability": "beta"
}
])
);
}

#[test]
fn inspect_methods_of_an_invalid_document() {
let spec = r#"{
"openapi": "3.0.3",
"info": {"title": "t", "version": "1"},
"paths": {
"/a": {
"get": {"operationId": "a.get", "responses": {"200": {"description": "ok"}}},
"post": {"operationId": "a.get", "responses": {"200": {"description": "ok"}}}
Comment on lines +185 to +186
}
}
}"#;
let err = failure(forge(&["inspect", "methods", "-"], spec));
assert!(err.contains("in the same group"), "{err}");
}
Loading