Skip to content

Commit

Permalink
Bump to 0.0.10, add --version flag, improve error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
vemonet committed Nov 21, 2023
1 parent b4bbd64 commit c3d09b5
Show file tree
Hide file tree
Showing 10 changed files with 43 additions and 31 deletions.
4 changes: 2 additions & 2 deletions cli/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "nanopub-cli"
version = "0.0.9"
version = "0.0.10"
description = """
A cross-platform CLI tool written in Rust to sign Nanopublications.
"""
Expand All @@ -14,6 +14,6 @@ homepage.workspace = true
categories.workspace = true

[dependencies]
nanopub = { version = "0.0.9", path = "../lib" }
nanopub = { version = "0.0.10", path = "../lib" }
clap = { version = "4.4", features = ["derive"] }
tokio = { version = "1.34", features = ["macros", "rt-multi-thread"] }
25 changes: 16 additions & 9 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use clap::{arg, Command};
use nanopub::{get_np_server, profile::get_default_profile_path, Nanopub, NpProfile};
use nanopub::{
error::NpError, get_np_server, profile::get_default_profile_path, Nanopub, NpProfile,
};
use std::{error::Error, fs, path::Path};

// https://github.com/clap-rs/clap/blob/master/examples/git.rs
Expand All @@ -8,8 +10,7 @@ use std::{error::Error, fs, path::Path};
async fn main() -> Result<(), Box<dyn Error>> {
let cmd = Command::new("nanopub")
.bin_name("np")
// .version("1.0")
// .author("Vincent Emonet <vincent.emonet@gmail.com>")
.version(env!("CARGO_PKG_VERSION"))
.about("Sign, publish, and check Nanopublications.")
.subcommand_required(true)
.arg_required_else_help(true)
Expand All @@ -18,7 +19,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
.about("Sign a Nanopub")
.arg(arg!(<NANOPUB_FILE> "The file to sign"))
.arg(
arg!(-k --key <PRIVATE_KEY> "The private key used to sign. Found in ~/.nanopub by default")
arg!(-k --key <PRIVATE_KEY> "The path to a private key used to sign. Found in ~/.nanopub by default")
.default_value("")
)
.arg(
Expand All @@ -29,18 +30,18 @@ async fn main() -> Result<(), Box<dyn Error>> {
)
.subcommand(
Command::new("publish")
.about("Sign and publish a Nanopub")
.about("Sign, publish, or check a Nanopublication (https://nanopub.net)")
.arg(arg!(<NANOPUB_FILE> "The file to publish"))
.arg(
arg!(-k --key <PRIVATE_KEY> "The private key used to sign.")
arg!(-k --key <PRIVATE_KEY> "The path to a private key used to sign.")
.default_value("")
)
.arg(
arg!(-p --profile <PROFILE> "The path to a profile.yml file. Default: ~/.nanopub/profile.yml")
.default_value("")
)
.arg(
arg!(-t --test "To publish to the test server instead of a production server.")
arg!(-t --test "To publish to the test server instead of the Nanopublication network.")
)
.arg_required_else_help(true),
).subcommand(
Expand Down Expand Up @@ -76,12 +77,18 @@ async fn main() -> Result<(), Box<dyn Error>> {
// Prefix the nanopub filename with "signed."
let path = Path::new(np_file);
let parent = path.parent().unwrap_or_else(|| Path::new(""));
let file_name = path.file_name().unwrap().to_str().unwrap();
let file_name = path
.file_name()
.ok_or_else(|| NpError("Error getting filename".to_string()))?
.to_str()
.ok_or_else(|| NpError("Error getting filename".to_string()))?;
let new_file_name = format!("signed.{}", file_name);
let signed_path = parent.join(new_file_name);
println!(
"📁 Signed Nanopub stored to {}",
signed_path.to_str().unwrap()
signed_path
.to_str()
.ok_or_else(|| NpError("Error getting signed path".to_string()))?
);
let _ = fs::write(signed_path, np.get_rdf());
}
Expand Down
4 changes: 2 additions & 2 deletions js/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "nanopub-js"
version = "0.0.9"
version = "0.0.10"
description = "JavaScript bindings for the Nanopub rust toolkit"
repository = "https://github.com/vemonet/nanopub-rs/tree/main/js"
authors.workspace = true
Expand All @@ -15,7 +15,7 @@ categories.workspace = true
crate-type = ["cdylib"]

[dependencies]
nanopub = { version = "0.0.9", path = "../lib" }
nanopub = { version = "0.0.10", path = "../lib" }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
serde-wasm-bindgen = "0.6"
Expand Down
15 changes: 12 additions & 3 deletions js/src/nanopub.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use js_sys::Promise;
use js_sys::{Promise, JSON};
use nanopub::{constants::TEST_SERVER, get_np_server as get_server, Nanopub, NpProfile};
use serde::Serialize;
use wasm_bindgen::prelude::*;
Expand All @@ -23,8 +23,17 @@ impl NanopubJs {
}

#[wasm_bindgen(static_method_of = NanopubJs)]
pub fn sign(rdf: &str, profile: NpProfileJs) -> Result<NanopubJs, JsValue> {
Nanopub::sign(rdf, &profile.profile)
pub fn sign(rdf: JsValue, profile: NpProfileJs) -> Result<NanopubJs, JsValue> {
let rdf_str = if rdf.is_string() {
rdf.as_string()
.ok_or_else(|| JsValue::from_str("RDF input must be a string"))?
} else {
JSON::stringify(&rdf)
.map_err(|e| JsValue::from_str("Failed to stringify JSON-LD object"))?
.as_string()
.ok_or_else(|| JsValue::from_str("Failed to convert JSON-LD object to string"))?
};
Nanopub::sign(&rdf_str, &profile.profile)
.map(|np| Self { np })
.map_err(|e| JsValue::from_str(&e.to_string()))
}
Expand Down
2 changes: 1 addition & 1 deletion lib/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "nanopub"
version = "0.0.9"
version = "0.0.10"
description = """
A cross-platform Rust library to sign Nanopublications, with bindings to Python and JS (wasm)
"""
Expand Down
2 changes: 1 addition & 1 deletion lib/docs/use_cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ np publish signed.nanopub.trig

You can use the same `-p` and `-k` options that are available for the `np sign` command

## Check
## 🔎 Check

Check if a signed nanopub is valid. It will check the Trusty hash, and signature based on the public key:

Expand Down
3 changes: 1 addition & 2 deletions lib/src/nanopub.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ impl fmt::Display for Nanopub {
impl Nanopub {
/// Check a given Nanopub RDF is valid (check trusty hash and signature).
///
/// A failed check will throw an error (panic)
/// A failed check will throw an error
///
/// # Arguments
///
Expand Down Expand Up @@ -394,7 +394,6 @@ impl Nanopub {
dataset =
replace_ns_in_quads(&dataset, &np_info.ns, &np_info.uri, &trusty_ns, &trusty_uri)?;

// Prepare the trig serializer
let rdf_str = serialize_rdf(&dataset, &trusty_uri, &trusty_ns)?;

// Return the signed Nanopub object
Expand Down
9 changes: 2 additions & 7 deletions lib/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,12 @@ pub fn parse_rdf(rdf: &str) -> Result<LightDataset, NpError> {
pub fn parse_jsonld(rdf: &str) -> Result<LightDataset, NpError> {
let rdf = rdf.to_string();
let handle = std::thread::spawn(move || {
futures::executor::block_on(async {
jsonld::parse_str(&rdf).collect_quads()
// .unwrap()
// .map_err(|e| NpError(format!("Error parsing JSON-LD: {e}")))
})
futures::executor::block_on(async { jsonld::parse_str(&rdf).collect_quads() })
});
let dataset = handle
.join()
.map_err(|_| NpError("Error parsing JSON-LD".to_string()))?
.map_err(|e| NpError(format!("Error parsing JSON-LD: {e}",)))?;
.map_err(|e| NpError(format!("Error parsing JSON-LD: {e}")))?;
Ok(dataset)
}

Expand All @@ -63,7 +59,6 @@ pub fn serialize_rdf(dataset: &LightDataset, uri: &str, ns: &str) -> Result<Stri
.with_pretty(true)
.with_prefix_map(&prefixes[..]);
let mut trig_stringifier = TrigSerializer::new_stringifier_with_config(trig_config);

Ok(trig_stringifier.serialize_dataset(&dataset)?.to_string())
}

Expand Down
6 changes: 4 additions & 2 deletions lib/tests/resources/nanopub.jsonld
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
"pav": "http://purl.org/pav/",
"orcid": "https://orcid.org/",
"schema": "https://schema.org/",
"ex": "http://example.org/",
"hasAssertion": {"@id": "np:hasAssertion"},
"hasProvenance": {"@id": "np:hasProvenance"},
"hasPublicationInfo": {"@id": "np:hasPublicationInfo"},
Expand All @@ -24,6 +23,9 @@
"@type": "Nanopublication",
"hasAssertion" : {
"@id" : "#assertion",
"@context": {
"ex": "http://example.org/"
},
"@graph" : [
{
"@id": "ex:mosquito",
Expand Down Expand Up @@ -55,4 +57,4 @@
]
}
}
}
}
4 changes: 2 additions & 2 deletions python/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "nanopub-sign"
version = "0.0.9"
version = "0.0.10"
description = "Python bindings for the Nanopub rust toolkit"
repository = "https://github.com/vemonet/nanopub-rs/tree/main/python"
authors.workspace = true
Expand All @@ -16,7 +16,7 @@ name = "nanopub_sign"
crate-type = ["cdylib"]

[dependencies]
nanopub = { version = "0.0.9", path = "../lib" }
nanopub = { version = "0.0.10", path = "../lib" }
pyo3 = { version = "0.20", features = ["extension-module"] }
pyo3-asyncio = "0.20"
tokio = { version = "1.34", features = ["rt-multi-thread"] }

0 comments on commit c3d09b5

Please sign in to comment.