Skip to content

Commit

Permalink
Merge pull request #489 from mkatychev/feat/array_separator
Browse files Browse the repository at this point in the history
  • Loading branch information
panekj authored Oct 19, 2023
2 parents 48dcbf1 + 62bd5db commit 1892861
Show file tree
Hide file tree
Showing 8 changed files with 48 additions and 54 deletions.
3 changes: 2 additions & 1 deletion crates/lsp-async-stub/src/listen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,8 @@ impl<W: Clone + 'static> Server<W> {
} else {
Err(anyhow!("got exit message without shutdown notice"))
}
}).await?;
})
.await?;

Ok(())
}
Expand Down
7 changes: 7 additions & 0 deletions crates/taplo-cli/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,13 @@ pub struct GetCommand {
/// - dependencies.tokio-*.version
///
pub pattern: Option<String>,

/// A string that separates array values when printing to stdout.
///
/// If `--separator` is specified with a non text output format,
/// the operation will fail.
#[clap(long)]
pub separator: Option<String>,
}

#[derive(Clone, Copy, ArgEnum)]
Expand Down
2 changes: 1 addition & 1 deletion crates/taplo-cli/src/commands/lint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ impl<E: Environment> Taplo<E> {
async fn lint_file(&self, file: &Path) -> Result<(), anyhow::Error> {
let source = self.env.read_file(file).await?;
let source = String::from_utf8(source)?;
self.lint_source(&*file.to_string_lossy(), &source).await
self.lint_source(&file.to_string_lossy(), &source).await
}

async fn lint_source(&self, file_path: &str, source: &str) -> Result<(), anyhow::Error> {
Expand Down
76 changes: 31 additions & 45 deletions crates/taplo-cli/src/commands/queries.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use std::borrow::Cow;

use crate::{args::GetCommand, Taplo};
use crate::{
args::{GetCommand, OutputFormat},
Taplo,
};
use anyhow::anyhow;
use codespan_reporting::files::SimpleFile;
use taplo::{
Expand All @@ -14,6 +17,13 @@ impl<E: Environment> Taplo<E> {
pub async fn execute_get(&self, cmd: GetCommand) -> Result<(), anyhow::Error> {
let mut stdout = self.env.stdout();

// `--separator` should only be handled for a text output format
if cmd.separator.is_some() && !matches!(cmd.output_format, OutputFormat::Value) {
return Err(anyhow!(
"`--separator` is only valid for `--output-format value`"
));
}

let source = match &cmd.file_path {
Some(p) => String::from_utf8(self.env.read_file(p).await?)?,
None => {
Expand Down Expand Up @@ -93,52 +103,34 @@ impl<E: Environment> Taplo<E> {
}
}
crate::args::OutputFormat::Value => {
if let Some(p) = cmd.pattern {
let separator = cmd.separator.as_deref().unwrap_or("\n");
let mut buf = if let Some(p) = cmd.pattern {
let p = p.trim_start_matches('.');

let keys = p
let nodes = p
.parse::<Keys>()
.map_err(|err| anyhow!("invalid pattern: {err}"))?;

let nodes = node
.find_all_matches(keys, false)
.and_then(|keys| node.find_all_matches(keys, false))
.map_err(|err| anyhow!("invalid pattern: {err}"))?;

if nodes.len() == 0 {
return Err(anyhow!("no values matched the pattern"));
}

let mut buf = String::new();
for (_, node) in nodes {
buf += &extract_value(&node)?;
buf += "\n";
}
if cmd.strip_newline {
if buf.ends_with('\n') {
let new_len = buf.trim_end().len();
buf.truncate(new_len);
}
} else if !buf.ends_with('\n') {
buf += "\n";
}
let values = nodes
.map(|(_, node)| extract_value(&node, separator))
.collect::<Result<Vec<String>, _>>()?;

stdout.write_all(buf.as_bytes()).await?;
stdout.flush().await?;
values.join(separator)
} else {
let mut buf = extract_value(&node)?;
extract_value(&node, separator)?
};

if cmd.strip_newline {
if buf.ends_with('\n') {
let new_len = buf.trim_end().len();
buf.truncate(new_len);
}
} else if !buf.ends_with('\n') {
buf += "\n";
}

stdout.write_all(buf.as_bytes()).await?;
stdout.flush().await?;
if !cmd.strip_newline {
buf += "\n";
}

stdout.write_all(buf.as_bytes()).await?;
stdout.flush().await?;
}
crate::args::OutputFormat::Toml => {
if let Some(p) = cmd.pattern {
Expand Down Expand Up @@ -216,27 +208,21 @@ impl<E: Environment> Taplo<E> {
}
}

fn extract_value(node: &Node) -> Result<String, anyhow::Error> {
fn extract_value(node: &Node, separator: &str) -> Result<String, anyhow::Error> {
Ok(match node {
Node::Table(_) => {
return Err(anyhow!(
r#"cannot print tables with the given output format, specify a different output format (e.g. with `-o json`) "#
))
}
Node::Array(arr) => {
let mut s = String::new();

let mut start = true;
for item in &**arr.items().read() {
if !start {
s += "\n";
}
start = false;
let mut values = Vec::new();

s += &extract_value(item)?;
for node in arr.items().read().iter() {
values.push(extract_value(node, separator)?);
}

s
values.join(separator)
}
Node::Bool(b) => b.value().to_string(),
Node::Str(s) => s.value().to_string(),
Expand Down
5 changes: 4 additions & 1 deletion crates/taplo-common/src/schema/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@ impl<E: Environment> Cache<E> {
)))),
lru_expires_by: Arc::new(Mutex::new(env.now() + DEFAULT_LRU_CACHE_EXPIRATION_TIME)),
env,
schemas: Arc::new(Mutex::new(LruCache::with_hasher(10, ahash::RandomState::new()))),
schemas: Arc::new(Mutex::new(LruCache::with_hasher(
10,
ahash::RandomState::new(),
))),
cache_path: Default::default(),
}
}
Expand Down
3 changes: 1 addition & 2 deletions crates/taplo/src/formatter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1085,8 +1085,7 @@ fn format_array(node: SyntaxNode, options: &Options, context: &Context) -> impl
skip_newlines = 0;
}

formatted
.extend(options.newlines(newline_count.saturating_sub(skip_newlines)));
formatted.extend(options.newlines(newline_count.saturating_sub(skip_newlines)));
}
COMMENT => {
let newline_before = t
Expand Down
2 changes: 1 addition & 1 deletion crates/taplo/src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -918,7 +918,7 @@ fn check_underscores(s: &str, radix: u32) -> bool {

/// The final results of a parsing.
/// It contains the green tree, and
/// the errors that ocurred during parsing.
/// the errors that occurred during parsing.
#[derive(Debug, Clone)]
pub struct Parse {
pub green_node: GreenNode,
Expand Down
4 changes: 1 addition & 3 deletions crates/taplo/src/tests/formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1125,9 +1125,7 @@ my_array = [
]
"#;

let formatted = crate::formatter::format(
src, Default::default()
);
let formatted = crate::formatter::format(src, Default::default());

assert_format!(expected, &formatted);
}

0 comments on commit 1892861

Please sign in to comment.