Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Machine-readable output (for search mode) #171

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 40 additions & 8 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
//! deals with CLI argument handling, I/O, threading, and more.

use std::error::Error;
use std::fmt::Write as FmtWrite;
use std::fs::{self, File};
use std::io::{self, stdout, Read, Write};
use std::io::{self, stdout, IsTerminal, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::{env, fmt};
Expand All @@ -27,6 +28,7 @@ use srgn::iterext::ParallelZipExt;
use srgn::scoping::langs::LanguageScoper;
use srgn::scoping::literal::{Literal, LiteralError};
use srgn::scoping::regex::{Regex, RegexError};
use srgn::scoping::scope::{RWScope, Scope};
use srgn::scoping::view::ScopedViewBuilder;
use srgn::scoping::Scoper;
use tree_sitter::QueryError as TSQueryError;
Expand Down Expand Up @@ -300,6 +302,7 @@ fn handle_actions_on_stdin(
general_scoper,
language_scopers,
pipeline,
None,
)?;

stdout().lock().write_all(destination.as_bytes())?;
Expand Down Expand Up @@ -601,6 +604,8 @@ fn process_path(
return Err(PathProcessingError::InvalidFile);
}

let is_terminal = stdout().is_terminal();

debug!("Processing path: {:?}", path);

let (new_contents, filesize, changed) = {
Expand All @@ -613,6 +618,7 @@ fn process_path(

let mut destination = String::with_capacity(source.len());

let p = path.display().to_string();
let changed = apply(
global_options,
standalone_action,
Expand All @@ -621,6 +627,7 @@ fn process_path(
general_scoper,
language_scopers,
pipeline,
if is_terminal { None } else { Some(&p) },
)?;

(destination, filesize, changed)
Expand All @@ -631,12 +638,21 @@ fn process_path(

if search_mode {
if !new_contents.is_empty() {
writeln!(
stdout,
"{}\n{}",
path.display().to_string().magenta(),
&new_contents
)?;
if is_terminal {
writeln!(
stdout,
"{}\n{}",
path.display().to_string().magenta(),
&new_contents
)?;
} else {
write!(
stdout,
"{}",
// path.display().to_string().magenta(),
&new_contents
)?;
}
}
} else {
if filesize > 0 && new_contents.is_empty() {
Expand Down Expand Up @@ -683,6 +699,7 @@ fn process_path(
/// TODO: The way this interacts with [`process_path`] etc. is just **awful** spaghetti
/// of the most imperative, procedural kind. Refactor needed.
#[allow(clippy::borrowed_box)] // Used throughout, not much of a pain
#[allow(clippy::too_many_arguments)] // FIXME: this function does way too much
fn apply(
global_options: &cli::GlobalOptions,
standalone_action: StandaloneAction,
Expand All @@ -693,6 +710,7 @@ fn apply(
general_scoper: &Box<dyn Scoper>,
language_scopers: &[Box<dyn LanguageScoper>],
pipeline: Pipeline<'_>,
line_prefix: Option<&str>,
) -> std::result::Result<bool, ApplicationError> {
debug!("Building view.");
let mut builder = ScopedViewBuilder::new(source);
Expand Down Expand Up @@ -743,10 +761,24 @@ fn apply(
for line in lines {
if !global_options.only_matching || line.has_any_in_scope() {
if global_options.line_numbers {
if let Some(p) = line_prefix {
write!(destination, "{p}:").unwrap();
}

let x = line
.scopes_with_ranges()
.into_iter()
.filter(|(_, s)| matches!(s, RWScope(Scope::In(_, _))))
.map(|(r, _)| (r.start, r.end))
.map(|(start, end)| format!("{start}-{end}"))
.collect_vec()
.join(";");

// `ColoredString` needs to be 'evaluated' to do anything; make sure
// to not forget even if this is moved outside of `format!`.
#[allow(clippy::to_string_in_format_args)]
destination.push_str(&format!("{}:", i.to_string().green().to_string()));
destination
.push_str(&format!("{}:{x}:", i.to_string().green().to_string()));
}

destination.push_str(&line.to_string());
Expand Down
17 changes: 17 additions & 0 deletions src/scoping/view.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::borrow::Cow;
use std::fmt;
use std::ops::Range;

use itertools::Itertools;
use log::{debug, trace, warn};
Expand Down Expand Up @@ -38,6 +39,22 @@ impl<'viewee> ScopedView<'viewee> {
&self.scopes
}

/// docs...
#[must_use]
pub fn scopes_with_ranges(&self) -> Vec<(Range<usize>, &RWScope<'viewee>)> {
let mut res = Vec::with_capacity(self.scopes.0.len());
let mut start = 0;

for scope in &self.scopes().0 {
let s: &str = scope.into();
let end = start + s.len();
res.push((start..end, scope));
start = end;
}

res
}

/// Return a builder for a view of the given input.
///
/// For API discoverability.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ args:
- gone
stdin: ~
stdout:
- "subdir/valid-utf8\n"
- "2:unique string for precise searching: 0a1a09c8-2995-4ac5-9d60-01a0f02920e8\n"
- "2:unique string for precise searching: gone\n"
- "\n"
- "subdir/valid-utf8:2:37-73:unique string for precise searching: 0a1a09c8-2995-4ac5-9d60-01a0f02920e8\n"
- "subdir/valid-utf8:2:37-41:unique string for precise searching: gone\n"
exit_code: 0
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,12 @@ args:
- baz
stdin: ~
stdout:
- "1.py\n"
- "1:# This string is found and touched: foo\n"
- "1:# This string is found and touched: baz\n"
- "4:def foo(bar: int) -> int:\n"
- "4:def baz(bar: int) -> int:\n"
- "\n"
- "subdir/2.py\n"
- "1:def foo(bar: int) -> int:\n"
- "1:def baz(bar: int) -> int:\n"
- "\n"
- "subdir/subdir/3.py\n"
- "1:def foo(bar: int) -> int:\n"
- "1:def baz(bar: int) -> int:\n"
- "\n"
- "1.py:1:36-39:# This string is found and touched: foo\n"
- "1.py:1:36-39:# This string is found and touched: baz\n"
- "1.py:4:4-7:def foo(bar: int) -> int:\n"
- "1.py:4:4-7:def baz(bar: int) -> int:\n"
- "subdir/2.py:1:4-7:def foo(bar: int) -> int:\n"
- "subdir/2.py:1:4-7:def baz(bar: int) -> int:\n"
- "subdir/subdir/3.py:1:4-7:def foo(bar: int) -> int:\n"
- "subdir/subdir/3.py:1:4-7:def baz(bar: int) -> int:\n"
exit_code: 0
6 changes: 2 additions & 4 deletions tests/snapshots/cli__tests__go-ignores-vendor-directory.snap
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
source: tests/cli.rs
expression: "CommandSnap {\n args,\n stdin: None,\n stdout: stdout.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec(),\n exit_code,\n}"
expression: "CommandSnap\n{\n args, stdin: None, stdout:\n stdout.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec(),\n exit_code,\n}"
info:
stderr: []
---
Expand All @@ -9,7 +9,5 @@ args:
- comments
stdin: ~
stdout:
- "found.go\n"
- "3:// This is found\n"
- "\n"
- "found.go:3:0-16:// This is found\n"
exit_code: 0
14 changes: 6 additions & 8 deletions tests/snapshots/cli__tests__go-search-files-macos.snap
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
---
source: tests/cli.rs
expression: "CommandSnap {\n args,\n stdin: stdin.map(|s|\n s.split_inclusive('\\n').map(|s| s.to_owned()).collect_vec()),\n stdout: stdout.split_inclusive('\\n').map(|s| s.to_owned()).collect_vec(),\n exit_code,\n}"
expression: "CommandSnap\n{\n args, stdin:\n stdin.map(|s|\n s.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec()), stdout:\n stdout.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec(),\n exit_code,\n}"
info:
stderr: ""
stderr: []
---
args:
- "--sorted"
Expand All @@ -11,10 +11,8 @@ args:
- "[fF]izz"
stdin: ~
stdout:
- "tests/langs/go/fizzbuzz.go\n"
- "5:// fizzBuzz prints the numbers from 1 to a specified limit.\n"
- "6:// For multiples of 3, it prints \"Fizz\" instead of the number,\n"
- "8:// it prints \"FizzBuzz\".\n"
- "25:\t// Run the FizzBuzz function for numbers from 1 to 100\n"
- "\n"
- "tests/langs/go/fizzbuzz.go:5:3-7:// fizzBuzz prints the numbers from 1 to a specified limit.\n"
- "tests/langs/go/fizzbuzz.go:6:34-38:// For multiples of 3, it prints \"Fizz\" instead of the number,\n"
- "tests/langs/go/fizzbuzz.go:8:14-18:// it prints \"FizzBuzz\".\n"
- "tests/langs/go/fizzbuzz.go:25:12-16:\t// Run the FizzBuzz function for numbers from 1 to 100\n"
exit_code: 0
12 changes: 6 additions & 6 deletions tests/snapshots/cli__tests__go-search.snap
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
---
source: tests/cli.rs
expression: "CommandSnap {\n args,\n stdin: stdin.map(|s|\n s.split_inclusive('\\n').map(|s| s.to_owned()).collect_vec()),\n stdout: stdout.split_inclusive('\\n').map(|s| s.to_owned()).collect_vec(),\n exit_code,\n}"
expression: "CommandSnap\n{\n args, stdin:\n stdin.map(|s|\n s.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec()), stdout:\n stdout.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec(),\n exit_code,\n}"
info:
stderr: ""
stderr: []
---
args:
- "--go"
Expand Down Expand Up @@ -37,8 +37,8 @@ stdin:
- "\tfizzBuzz(100)\n"
- "}\n"
stdout:
- "5:// fizzBuzz prints the numbers from 1 to a specified limit.\n"
- "6:// For multiples of 3, it prints \"Fizz\" instead of the number,\n"
- "8:// it prints \"FizzBuzz\".\n"
- "25:\t// Run the FizzBuzz function for numbers from 1 to 100\n"
- "5:3-7:// fizzBuzz prints the numbers from 1 to a specified limit.\n"
- "6:34-38:// For multiples of 3, it prints \"Fizz\" instead of the number,\n"
- "8:14-18:// it prints \"FizzBuzz\".\n"
- "25:12-16:\t// Run the FizzBuzz function for numbers from 1 to 100\n"
exit_code: 0
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,8 @@ args:
- baz
stdin: ~
stdout:
- "subdir/2.py\n"
- "1:def foo(bar: int) -> int:\n"
- "1:def baz(bar: int) -> int:\n"
- "\n"
- "subdir/subdir/3.py\n"
- "1:def foo(bar: int) -> int:\n"
- "1:def baz(bar: int) -> int:\n"
- "\n"
- "subdir/2.py:1:4-7:def foo(bar: int) -> int:\n"
- "subdir/2.py:1:4-7:def baz(bar: int) -> int:\n"
- "subdir/subdir/3.py:1:4-7:def foo(bar: int) -> int:\n"
- "subdir/subdir/3.py:1:4-7:def baz(bar: int) -> int:\n"
exit_code: 0
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,12 @@ args:
- baz
stdin: ~
stdout:
- "1-shebanged\n"
- "9:def foo(bar: int) -> int:\n"
- "9:def baz(bar: int) -> int:\n"
- "\n"
- "1.py\n"
- "4:def foo(bar: int) -> int:\n"
- "4:def baz(bar: int) -> int:\n"
- "\n"
- "subdir/2.py\n"
- "1:def foo(bar: int) -> int:\n"
- "1:def baz(bar: int) -> int:\n"
- "\n"
- "subdir/subdir/3.py\n"
- "1:def foo(bar: int) -> int:\n"
- "1:def baz(bar: int) -> int:\n"
- "\n"
- "1-shebanged:9:4-7:def foo(bar: int) -> int:\n"
- "1-shebanged:9:4-7:def baz(bar: int) -> int:\n"
- "1.py:4:4-7:def foo(bar: int) -> int:\n"
- "1.py:4:4-7:def baz(bar: int) -> int:\n"
- "subdir/2.py:1:4-7:def foo(bar: int) -> int:\n"
- "subdir/2.py:1:4-7:def baz(bar: int) -> int:\n"
- "subdir/subdir/3.py:1:4-7:def foo(bar: int) -> int:\n"
- "subdir/subdir/3.py:1:4-7:def baz(bar: int) -> int:\n"
exit_code: 0
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
source: tests/cli.rs
expression: "CommandSnap {\n args,\n stdin: stdin.map(|s|\n s.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec()),\n stdout: stdout.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec(),\n exit_code,\n}"
expression: "CommandSnap\n{\n args, stdin:\n stdin.map(|s|\n s.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec()), stdout:\n stdout.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec(),\n exit_code,\n}"
info:
stderr: []
---
Expand All @@ -12,6 +12,6 @@ stdin:
- "A\n"
- B
stdout:
- "1:X\n"
- "2:B"
- "1:0-1:X\n"
- "2::B"
exit_code: 0
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
source: tests/cli.rs
expression: "CommandSnap {\n args,\n stdin: stdin.map(|s|\n s.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec()),\n stdout: stdout.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec(),\n exit_code,\n}"
expression: "CommandSnap\n{\n args, stdin:\n stdin.map(|s|\n s.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec()), stdout:\n stdout.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec(),\n exit_code,\n}"
info:
stderr: []
---
Expand All @@ -11,6 +11,6 @@ stdin:
- "A\n"
- B
stdout:
- "1:A\n"
- "2:B"
- "1:0-1:A\n"
- "2:0-1:B"
exit_code: 0
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
source: tests/cli.rs
expression: "CommandSnap {\n args,\n stdin: stdin.map(|s|\n s.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec()),\n stdout: stdout.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec(),\n exit_code,\n}"
expression: "CommandSnap\n{\n args, stdin:\n stdin.map(|s|\n s.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec()), stdout:\n stdout.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec(),\n exit_code,\n}"
info:
stderr: []
---
Expand All @@ -13,5 +13,5 @@ stdin:
- "A\n"
- B
stdout:
- "1:X\n"
- "1:0-1:X\n"
exit_code: 0
4 changes: 2 additions & 2 deletions tests/snapshots/cli__tests__python-multiple-scopes.snap
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
source: tests/cli.rs
expression: "CommandSnap {\n args,\n stdin: stdin.map(|s|\n s.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec()),\n stdout: stdout.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec(),\n exit_code,\n}"
expression: "CommandSnap\n{\n args, stdin:\n stdin.map(|s|\n s.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec()), stdout:\n stdout.split_inclusive('\\n').map(ToOwned::to_owned).collect_vec(),\n exit_code,\n}"
info:
stderr: []
---
Expand All @@ -16,5 +16,5 @@ stdin:
- "def A(): return \"A string in a func\"\n"
- "class A: pass"
stdout:
- "3:def A(): return \"A string in a func\"\n"
- "3:17-18:def A(): return \"A string in a func\"\n"
exit_code: 0
Loading
Loading