Skip to content

Commit

Permalink
merge: pull request #81 from mdzk-rs/issue-80
Browse files Browse the repository at this point in the history
Issue 80
  • Loading branch information
kmaasrud authored Mar 28, 2022
2 parents 1cdf956 + b493572 commit 4949e18
Show file tree
Hide file tree
Showing 5 changed files with 75 additions and 4 deletions.
6 changes: 6 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,18 @@ pub enum Error {
#[error("The source for a vault must be a directory.")]
/// Thrown by [`VaultBuilder`](crate::VaultBuilder) when the source is not a directory.
VaultSourceNotDir,

#[error("The path {0} was not found.")]
/// An error stating a path does not exist in the filesystem.
PathNotFound(PathBuf),

#[error("Cannot find the destination for the internal link: {0}")]
/// An error for when a destination for an internal link cannot be found.
InvalidInternalLinkDestination(String),

#[error("Could not format the value: {0}")]
FormatError(#[from] serde_json::Error),

#[error(transparent)]
/// Represents all other errors, likely from another crate.
Other(#[from] anyhow::Error),
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ extern crate pest_derive;

pub mod error;
pub mod note;
mod utils;
pub mod utils;
mod vault;

#[doc(inline)]
Expand Down
16 changes: 15 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use anyhow::{bail, Result};
use clap::Parser;
use jql::walker;
use mdzk::utils::string::format_json_value;
use std::path::PathBuf;

#[derive(Parser)]
Expand Down Expand Up @@ -29,6 +30,19 @@ struct Args {
/// The ignore patterns are in the gitignore format.
/// See https://git-scm.com/docs/gitignore#_pattern_format for a reference.
ignore: Vec<String>,

#[clap(long = "pretty")]
/// Prettify the JSON output
///
/// If both --pretty and --raw are specified, the --raw flag takes precedence for strings and arrays.
pretty: bool,

#[clap(short = 'r', long = "raw")]
/// Output shell-compatible raw strings and arrays
///
/// If the output is a string, it will get formatted without quotes and if the output is an
/// array, it's values will get delimited by newlines and printed without square brackets.
raw: bool,
}

fn main() {
Expand All @@ -50,7 +64,7 @@ fn run() -> Result<()> {
let json = serde_json::to_value(vault)?;

match walker(&json, &args.query) {
Ok(out) => println!("{}", out),
Ok(out) => println!("{}", format_json_value(&out, args.raw, args.pretty)?),
Err(msg) => bail!(msg),
}

Expand Down
52 changes: 51 additions & 1 deletion src/utils/string.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::NoteId;
use crate::{error::Result, NoteId};
use pulldown_cmark::escape::escape_href as ehref;
use serde_json::{to_string, to_string_pretty, Value};

/// Make kebab-cased string
pub fn kebab(s: impl AsRef<str>) -> String {
Expand Down Expand Up @@ -32,3 +33,52 @@ pub fn escape_href(text: &str) -> String {
pub fn hex(id: &NoteId) -> String {
format!("{:x}", id)
}

pub fn format_json_value(val: &Value, raw: bool, pretty: bool) -> Result<String> {
Ok(match (pretty, raw, val) {
(_, true, Value::String(s)) => s.to_owned(),
(_, true, Value::Array(a)) => {
let mut acc: Vec<String> = Vec::new();
for val in a {
let val = format_json_value(val, true, false)?;
acc.push(val);
}
acc.join("\n")
}
(true, _, _) => to_string_pretty(val)?,
_ => to_string(val)?,
})
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_format_json_value() {
let want = r#"{
"key": "value",
"another-key": [
1,
2,
3
]
}"#
.to_string();
let object = json!({ "key": "value", "another-key": [1, 2, 3]});
assert_eq!(want, format_json_value(&object, false, true).unwrap());

use serde_json::json;
let string = json!("test");
assert_eq!(
"test".to_string(),
format_json_value(&string, true, false).unwrap()
);

let arr = json!(["el1", "el2", "el3"]);
assert_eq!(
"el1\nel2\nel3".to_string(),
format_json_value(&arr, true, false).unwrap()
)
}
}
3 changes: 2 additions & 1 deletion src/vault/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,8 @@ struct VaultSerialized {
impl From<&Vault> for VaultSerialized {
fn from(vault: &Vault) -> Self {
Self {
notes: vault.notes
notes: vault
.notes
.par_iter()
.map(|(id, note)| {
NoteSerialized::new(
Expand Down

0 comments on commit 4949e18

Please sign in to comment.