diff options
author | Akshay <[email protected]> | 2021-10-25 17:38:52 +0100 |
---|---|---|
committer | Akshay <[email protected]> | 2021-10-25 17:38:52 +0100 |
commit | 5f0a1e67c64082c848418daa2b51020eb42c5c12 (patch) | |
tree | 1d6d7db9ee5532e76d23b9f509a8299d0d34dc52 /bin/src/fix/single.rs | |
parent | 781c42cc9ce2e6a3f1024ea1f4e3f071cc8f2dd4 (diff) |
rework cli, use subcommands instead
Diffstat (limited to 'bin/src/fix/single.rs')
-rw-r--r-- | bin/src/fix/single.rs | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/bin/src/fix/single.rs b/bin/src/fix/single.rs new file mode 100644 index 0000000..d430693 --- /dev/null +++ b/bin/src/fix/single.rs | |||
@@ -0,0 +1,59 @@ | |||
1 | use std::{borrow::Cow, convert::TryFrom}; | ||
2 | |||
3 | use lib::{Report, LINTS}; | ||
4 | use rnix::{TextRange, TextSize}; | ||
5 | |||
6 | use crate::err::SingleFixErr; | ||
7 | use crate::fix::Source; | ||
8 | |||
9 | pub struct SingleFixResult<'δ> { | ||
10 | pub src: Source<'δ>, | ||
11 | } | ||
12 | |||
13 | fn pos_to_byte(line: usize, col: usize, src: &str) -> Result<TextSize, SingleFixErr> { | ||
14 | let mut byte: TextSize = TextSize::of(""); | ||
15 | for (_, l) in src.lines().enumerate().take_while(|(i, _)| i <= &line) { | ||
16 | byte += TextSize::of(l); | ||
17 | } | ||
18 | byte += TextSize::try_from(col).map_err(|_| SingleFixErr::Conversion(col))?; | ||
19 | |||
20 | if usize::from(byte) >= src.len() { | ||
21 | Err(SingleFixErr::OutOfBounds(line, col)) | ||
22 | } else { | ||
23 | Ok(byte) | ||
24 | } | ||
25 | } | ||
26 | |||
27 | fn find(offset: TextSize, src: &str) -> Result<Report, SingleFixErr> { | ||
28 | // we don't really need the source to form a completely parsed tree | ||
29 | let parsed = rnix::parse(src); | ||
30 | |||
31 | let elem_at = parsed | ||
32 | .node() | ||
33 | .child_or_token_at_range(TextRange::empty(offset)) | ||
34 | .ok_or(SingleFixErr::NoOp)?; | ||
35 | |||
36 | LINTS | ||
37 | .get(&elem_at.kind()) | ||
38 | .map(|rules| { | ||
39 | rules | ||
40 | .iter() | ||
41 | .filter_map(|rule| rule.validate(&elem_at)) | ||
42 | .filter(|report| report.total_suggestion_range().is_some()) | ||
43 | .next() | ||
44 | }) | ||
45 | .flatten() | ||
46 | .ok_or(SingleFixErr::NoOp) | ||
47 | } | ||
48 | |||
49 | pub fn single(line: usize, col: usize, src: &str) -> Result<SingleFixResult, SingleFixErr> { | ||
50 | let mut src = Cow::from(src); | ||
51 | let offset = pos_to_byte(line, col, &*src)?; | ||
52 | let report = find(offset, &*src)?; | ||
53 | |||
54 | report.apply(src.to_mut()); | ||
55 | |||
56 | Ok(SingleFixResult { | ||
57 | src | ||
58 | }) | ||
59 | } | ||