1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
|
use std::{default::Default, fmt, fs, path::PathBuf, str::FromStr};
use crate::{dirs, err::ConfigErr};
use clap::Clap;
use vfs::ReadOnlyVfs;
#[derive(Clap, Debug)]
#[clap(version, author, about)]
pub struct Opts {
#[clap(subcommand)]
pub cmd: SubCommand,
}
#[derive(Clap, Debug)]
pub enum SubCommand {
/// Lints and suggestions for the nix programming language
Check(Check),
/// Find and fix issues raised by statix-check
Fix(Fix),
/// Fix exactly one issue at provided position
Single(Single),
/// Print detailed explanation for a lint warning
Explain(Explain),
}
#[derive(Clap, Debug)]
pub struct Check {
/// File or directory to run check on
#[clap(default_value = ".", parse(from_os_str))]
target: PathBuf,
/// Globs of file patterns to skip
#[clap(short, long)]
ignore: Vec<String>,
/// Don't respect .gitignore files
#[clap(short, long)]
unrestricted: bool,
/// Output format.
/// Supported values: stderr, errfmt, json (on feature flag only)
#[clap(short = 'o', long, default_value_t, parse(try_from_str))]
pub format: OutFormat,
/// Enable "streaming" mode, accept file on stdin, output diagnostics on stdout
#[clap(short, long = "stdin")]
pub streaming: bool,
}
impl Check {
pub fn vfs(&self) -> Result<ReadOnlyVfs, ConfigErr> {
if self.streaming {
use std::io::{self, BufRead};
let src = io::stdin()
.lock()
.lines()
.map(|l| l.unwrap())
.collect::<Vec<String>>()
.join("\n");
Ok(ReadOnlyVfs::singleton("<stdin>", src.as_bytes()))
} else {
let ignore = dirs::build_ignore_set(&self.ignore, &self.target, self.unrestricted)?;
let files = dirs::walk_nix_files(ignore, &self.target)?;
vfs(files.collect::<Vec<_>>())
}
}
}
#[derive(Clap, Debug)]
pub struct Fix {
/// File or directory to run fix on
#[clap(default_value = ".", parse(from_os_str))]
target: PathBuf,
/// Globs of file patterns to skip
#[clap(short, long)]
ignore: Vec<String>,
/// Don't respect .gitignore files
#[clap(short, long)]
unrestricted: bool,
/// Do not fix files in place, display a diff instead
#[clap(short, long = "dry-run")]
pub diff_only: bool,
/// Enable "streaming" mode, accept file on stdin, output diagnostics on stdout
#[clap(short, long = "stdin")]
pub streaming: bool,
}
pub enum FixOut {
Diff,
Stream,
Write,
}
impl Fix {
pub fn vfs(&self) -> Result<ReadOnlyVfs, ConfigErr> {
if self.streaming {
use std::io::{self, BufRead};
let src = io::stdin()
.lock()
.lines()
.map(|l| l.unwrap())
.collect::<Vec<String>>()
.join("\n");
Ok(ReadOnlyVfs::singleton("<stdin>", src.as_bytes()))
} else {
let ignore = dirs::build_ignore_set(&self.ignore, &self.target, self.unrestricted)?;
let files = dirs::walk_nix_files(ignore, &self.target)?;
vfs(files.collect::<Vec<_>>())
}
}
// i need this ugly helper because clap's data model
// does not reflect what i have in mind
pub fn out(&self) -> FixOut {
if self.diff_only {
FixOut::Diff
} else if self.streaming {
FixOut::Stream
} else {
FixOut::Write
}
}
}
#[derive(Clap, Debug)]
pub struct Single {
/// File to run single-fix on
#[clap(parse(from_os_str))]
pub target: Option<PathBuf>,
/// Position to attempt a fix at
#[clap(short, long, parse(try_from_str = parse_line_col))]
pub position: (usize, usize),
/// Do not fix files in place, display a diff instead
#[clap(short, long = "dry-run")]
pub diff_only: bool,
/// Enable "streaming" mode, accept file on stdin, output diagnostics on stdout
#[clap(short, long = "stdin")]
pub streaming: bool,
}
impl Single {
pub fn vfs(&self) -> Result<ReadOnlyVfs, ConfigErr> {
if self.streaming {
use std::io::{self, BufRead};
let src = io::stdin()
.lock()
.lines()
.map(|l| l.unwrap())
.collect::<Vec<String>>()
.join("\n");
Ok(ReadOnlyVfs::singleton("<stdin>", src.as_bytes()))
} else {
let src = std::fs::read_to_string(self.target.as_ref().unwrap())
.map_err(ConfigErr::InvalidPath)?;
Ok(ReadOnlyVfs::singleton("<stdin>", src.as_bytes()))
}
}
pub fn out(&self) -> FixOut {
if self.diff_only {
FixOut::Diff
} else if self.streaming {
FixOut::Stream
} else {
FixOut::Write
}
}
}
#[derive(Clap, Debug)]
pub struct Explain {
/// Warning code to explain
#[clap(parse(try_from_str = parse_warning_code))]
pub target: u32,
}
fn parse_line_col(src: &str) -> Result<(usize, usize), ConfigErr> {
let parts = src.split(',');
match parts.collect::<Vec<_>>().as_slice() {
[line, col] => {
let l = line
.parse::<usize>()
.map_err(|_| ConfigErr::InvalidPosition(src.to_owned()))?;
let c = col
.parse::<usize>()
.map_err(|_| ConfigErr::InvalidPosition(src.to_owned()))?;
Ok((l, c))
}
_ => Err(ConfigErr::InvalidPosition(src.to_owned())),
}
}
fn parse_warning_code(src: &str) -> Result<u32, ConfigErr> {
let mut char_stream = src.chars();
let severity = char_stream
.next()
.ok_or_else(|| ConfigErr::InvalidWarningCode(src.to_owned()))?
.to_ascii_lowercase();
match severity {
'w' => char_stream
.collect::<String>()
.parse::<u32>()
.map_err(|_| ConfigErr::InvalidWarningCode(src.to_owned())),
_ => Ok(0),
}
}
fn vfs(files: Vec<PathBuf>) -> Result<ReadOnlyVfs, ConfigErr> {
let mut vfs = ReadOnlyVfs::default();
for file in files.iter() {
if let Ok(data) = fs::read_to_string(&file) {
let _id = vfs.alloc_file_id(&file);
vfs.set_file_contents(&file, data.as_bytes());
} else {
println!("{} contains non-utf8 content", file.display());
};
}
Ok(vfs)
}
#[derive(Debug, Copy, Clone)]
pub enum OutFormat {
#[cfg(feature = "json")]
Json,
Errfmt,
StdErr,
}
impl Default for OutFormat {
fn default() -> Self {
OutFormat::StdErr
}
}
impl fmt::Display for OutFormat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match self {
#[cfg(feature = "json")]
Self::Json => "json",
Self::Errfmt => "errfmt",
Self::StdErr => "stderr",
}
)
}
}
impl FromStr for OutFormat {
type Err = &'static str;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value.to_ascii_lowercase().as_str() {
#[cfg(feature = "json")]
"json" => Ok(Self::Json),
#[cfg(not(feature = "json"))]
"json" => Err("statix was not compiled with the `json` feature flag"),
"errfmt" => Ok(Self::Errfmt),
"stderr" => Ok(Self::StdErr),
_ => Err("unknown output format, try: json, errfmt"),
}
}
}
|