diff options
author | stuebinm | 2024-04-19 02:49:45 +0200 |
---|---|---|
committer | stuebinm | 2024-04-19 02:49:45 +0200 |
commit | f17762ec0ef9eea0ee3e67b0b2b1ec4fd623a72b (patch) | |
tree | d1ae38663152d0aebad0943e4de7816fbc39befe /src/main.rs | |
parent | 93d72079a86849e0453c9130c73e1702e3d66f69 (diff) |
(instead of just printing them, might be useful for scripts — also, I've
not come up with a better name than "nixq" yet, so it really ought to be
able to query things)
Diffstat (limited to '')
-rw-r--r-- | src/main.rs | 77 |
1 files changed, 58 insertions, 19 deletions
diff --git a/src/main.rs b/src/main.rs index 6e85257..bd448ce 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,7 +3,9 @@ use rowan::ast::AstNode; use clap::{arg, Parser}; use queries::Query; -use changes::apply_changes; +use changes::{apply_changes, format_range}; + +use crate::changes::format_range_json; #[allow(dead_code)] mod queries; @@ -24,7 +26,11 @@ struct Args { #[arg(short, long)] debug: bool, #[arg(long)] - batchmode: bool + batchmode: bool, + #[arg(long)] + print_positions: bool, + #[arg(long)] + json: bool } fn main() { @@ -38,31 +44,64 @@ fn main() { } if args.batchmode { + macro_rules! warn_arg { + ($arg: ident, $text:literal) => { if args.$arg { + eprintln!("Warning: option {} is ignored in batch mode.", $text); + }} + } + + warn_arg!(json, "--json"); + warn_arg!(print_positions, "--print-positions"); + batchmode::batchmode(args.path, query, args.debug); } else { - let (content, nexp) = match parse_nixfile(&args.path[0]) { - Err(e) => { - eprintln!("could not parse file: {e}"); - exit(2); - }, - Ok(exp) => exp - }; - - let (changes, results) = query.apply(&content, nexp.syntax().clone()).unwrap(); - - if args.debug { - println!("{changes:?}"); + for path in &args.path { + handle_file(path, &args, &query) } + } +} + +fn handle_file(path: &PathBuf, args: &Args, query: &Query) { + let (content, nexp) = match parse_nixfile(path) { + Err(e) => { + eprintln!("could not parse file: {e}"); + exit(2); + }, + Ok(exp) => exp + }; - if changes.len() == 0 { + let (changes, results) = query.apply(&content, nexp.syntax().clone()).unwrap(); + + if args.debug { + println!("{changes:?}"); + } + + if changes.len() == 0 { + if args.print_positions { + if args.json { + let json = results + .iter() + .map(|result| + format_range_json(path, &content, result.text_range())) + .collect::<Vec<_>>(); + println!("{}", serde_json::to_string(&json).unwrap()); + } else { + for result in results { + println!( + "{}", + format_range(path, &content, result.text_range()) + ); + } + } + } else { for result in results { println!("{result}"); } - } else { - let changed = apply_changes(&content, changes, args.debug); - - println!("{changed}"); } + } else { + let changed = apply_changes(&content, changes, args.debug); + + println!("{changed}"); } } |