Skip to content

Commit

Permalink
add ckb rpc submodule
Browse files Browse the repository at this point in the history
  • Loading branch information
chenyukang committed Oct 24, 2023
1 parent b9f5d71 commit c5d982f
Show file tree
Hide file tree
Showing 7 changed files with 94 additions and 51 deletions.
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,6 @@
path = test/vendor
url = https://github.com/nervosnetwork/ckb-tests.git
shallow = true
[submodule "docs/ckb_rpc_openrpc"]
path = docs/ckb_rpc_openrpc
url = https://github.com/nervosnetwork/ckb-rpc-resources.git
4 changes: 3 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,11 @@ doc-deps: ## Build the documentation for the local package and all dependencies.
cargo doc --workspace

.PHONY: gen-rpc-doc
gen-rpc-doc: ## Generate rpc documentation
gen-rpc-doc: submodule-init ## Generate rpc documentation
cd devtools/doc/rpc-gen && cargo build
cd docs/ckb_rpc_openrpc/ && git stash
./target/debug/ckb-rpc-gen rpc/README.md
./target/debug/ckb-rpc-gen --json

.PHONY: gen-hashes
gen-hashes: ## Generate docs/hashes.toml
Expand Down
47 changes: 28 additions & 19 deletions devtools/doc/rpc-gen/src/gen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ struct RpcModule {
}

impl RpcModule {
pub fn gen_menu(&self) -> Value {
pub fn gen_menu(&self, tag: &str) -> Value {
let capitlized = self.title.to_string();
let mut method_names = self
.methods
Expand All @@ -28,11 +28,14 @@ impl RpcModule {
("title", capitlized.clone().into()),
("name", self.title.to_lowercase().into()),
("methods", method_names.into()),
("link", gen_module_openrpc_playground(&capitlized).into()),
(
"link",
gen_module_openrpc_playground(&capitlized, tag).into(),
),
])
}

pub fn gen_module_content(&self) -> String {
pub fn gen_module_content(&self, tag: &str) -> String {
if self.title == "Subscription" {
return gen_subscription_rpc_doc();
}
Expand Down Expand Up @@ -78,7 +81,10 @@ impl RpcModule {
include_str!("../templates/module.tera"),
&[
("name", capitlized.clone().into()),
("link", gen_module_openrpc_playground(&capitlized).into()),
(
"link",
gen_module_openrpc_playground(&capitlized, tag).into(),
),
("desc", description.into()),
("methods", methods.into()),
],
Expand All @@ -90,10 +96,11 @@ pub(crate) struct RpcDocGenerator {
rpc_methods: Vec<RpcModule>,
types: Vec<(String, Value)>,
file_path: String,
tag: String,
}

impl RpcDocGenerator {
pub fn new(all_rpc: &Vec<Value>, readme_path: String) -> Self {
pub fn new(all_rpc: &Vec<Value>, readme_path: String, tag: String) -> Self {
let mut rpc_methods = vec![];
let mut all_types: Vec<&Map<String, Value>> = vec![];
for rpc in all_rpc {
Expand Down Expand Up @@ -133,6 +140,7 @@ impl RpcDocGenerator {
rpc_methods,
types,
file_path: readme_path,
tag,
}
}

Expand All @@ -151,7 +159,7 @@ impl RpcDocGenerator {
let module_menus = self
.rpc_methods
.iter()
.map(|r| r.gen_menu())
.map(|r| r.gen_menu(&self.tag))
.collect::<Vec<_>>();

let type_menus: Value = self
Expand All @@ -165,7 +173,7 @@ impl RpcDocGenerator {
let modules: Vec<Value> = self
.rpc_methods
.iter()
.map(|r| r.gen_module_content().into())
.map(|r| r.gen_module_content(&self.tag).into())
.collect::<Vec<_>>();

let types = self.gen_type_contents();
Expand Down Expand Up @@ -409,29 +417,30 @@ fn gen_subscription_rpc_doc() -> String {
format!("{}\n\n{}\n", summary, sub_desc)
}

/// wrapper for render value
fn gen_value(pairs: &[(&str, Value)]) -> Value {
let mut res = Value::Object(Map::new());
for (k, v) in pairs {
res.as_object_mut()
.unwrap()
.insert(k.to_string(), v.to_owned());
}
res
}

/// generate openrpc playground urls
fn gen_module_openrpc_playground(module: &str) -> String {
fn gen_module_openrpc_playground(module: &str, tag: &str) -> String {
let title = format!("CKB-{}", capitlize(module));
render_tera(
include_str!("../templates/link.tera"),
&[
("title", title.into()),
("module", module.to_lowercase().into()),
("tag", tag.into()),
],
)
}

/// wrapper for render value
fn gen_value(pairs: &[(&str, Value)]) -> Value {
let mut res = Value::Object(Map::new());
for (k, v) in pairs {
res.as_object_mut()
.unwrap()
.insert(k.to_string(), v.to_owned());
}
res
}

fn render_tera(template: &str, content: &[(&str, Value)]) -> String {
let mut context = tera::Context::new();
for (k, v) in content {
Expand Down
46 changes: 37 additions & 9 deletions devtools/doc/rpc-gen/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@
mod gen;
use crate::gen::RpcDocGenerator;
use ckb_rpc::module::*;
use serde_json::json;
use std::fs;

/// Get git tag from command line
fn get_tag() -> Option<String> {
std::process::Command::new("git")
.args(["describe", "--tags", "--abbrev=0"])
const OPENRPC_DIR: &str = "./docs/ckb_rpc_openrpc/";

fn run_command(prog: &str, args: &[&str], dir: Option<&str>) -> Option<String> {
std::process::Command::new(prog)
.args(args)
.current_dir(dir.unwrap_or("."))
.output()
.ok()
.filter(|output| output.status.success())
Expand All @@ -18,14 +21,35 @@ fn get_tag() -> Option<String> {
})
}

fn get_tag() -> String {
run_command("git", &["describe", "--tags", "--abbrev=0"], None).unwrap_or("main".to_owned())
}

/// Get git tag from command line
fn get_commit_sha() -> String {
run_command("git", &["rev-parse", "HEAD"], Some(OPENRPC_DIR)).unwrap_or("main".to_string())
}

fn checkout_tag_branch(tag: &str) {
let dir = Some(OPENRPC_DIR);
let res = run_command("git", &["checkout", tag], dir);
if res.is_none() {
run_command("git", &["checkout", "-b", tag], dir);
}
}

fn dump_openrpc_json() -> Result<(), Box<dyn std::error::Error>> {
let dir = "./target/doc/ckb_rpc_openrpc/";
let dir = "./docs/ckb_rpc_openrpc/json/";
let tag = get_tag();
checkout_tag_branch(&tag);

fs::create_dir_all(dir)?;
let tag = get_tag().unwrap();
let dump =
|name: &str, doc: &mut serde_json::Value| -> Result<(), Box<dyn std::error::Error>> {
doc["info"]["version"] = serde_json::Value::String(tag.clone());
fs::write(dir.to_owned() + name, doc.to_string())?;
let obj = json!(doc);
let res = serde_json::to_string_pretty(&obj)?;
fs::write(dir.to_owned() + name, res)?;
Ok(())
};
dump("alert_rpc_doc.json", &mut alert_rpc_doc())?;
Expand All @@ -42,7 +66,10 @@ fn dump_openrpc_json() -> Result<(), Box<dyn std::error::Error>> {
)?;
dump("indexer_rpc_doc.json", &mut indexer_rpc_doc())?;
dump("experiment_rpc_doc.json", &mut experiment_rpc_doc())?;
eprintln!("finished dump openrpc json for tag: {:?}...", tag);
eprintln!(
"finished dump openrpc json for tag: {:?} at dir: {:?}",
tag, dir
);
Ok(())
}

Expand All @@ -62,7 +89,8 @@ pub fn gen_rpc_readme(readme_path: &str) -> Result<(), Box<dyn std::error::Error
experiment_rpc_doc(),
];

let generator = RpcDocGenerator::new(&all_rpc, readme_path.to_owned());
let tag = get_commit_sha();
let generator = RpcDocGenerator::new(&all_rpc, readme_path.to_owned(), tag);
fs::write(readme_path, generator.gen_markdown())?;

Ok(())
Expand Down
2 changes: 1 addition & 1 deletion devtools/doc/rpc-gen/templates/link.tera
Original file line number Diff line number Diff line change
@@ -1 +1 @@
[👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]={{title}}&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/json/{{module}}_rpc_doc.json)
[👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]={{title}}&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/{{tag}}/json/{{module}}_rpc_doc.json)
1 change: 1 addition & 0 deletions docs/ckb_rpc_openrpc
Submodule ckb_rpc_openrpc added at e8f344
Loading

0 comments on commit c5d982f

Please sign in to comment.