flay-rs 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,312 @@
1
+ //! `Flay#process(*files)`: the handler Flay picks for each file, parsing
2
+ //! the files in parallel, why a file is skipped and the warnings Flay
3
+ //! prints for it.
4
+
5
+ use rayon::prelude::*;
6
+
7
+ use crate::matcher::{filter_sexp, Filter};
8
+ use crate::sexp::Value;
9
+ use crate::{erb, parse_file, Flay, ParsedFile, ProcessOptions, RubyException, Skip};
10
+
11
+ /// How `Flay#process` handles a file, chosen by its extension the way Flay
12
+ /// calls `process_<ext>` when it responds to it.
13
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
14
+ pub enum Handler {
15
+ /// `process_rb`.
16
+ Ruby,
17
+ /// `process_erb`, once the `flay_erb` plugin is loaded.
18
+ Erb,
19
+ /// `process_sexp(file)`, which fails on the file name.
20
+ ProcessSexp,
21
+ /// `process_fuzzy(file)`, which takes two arguments.
22
+ ProcessFuzzy,
23
+ /// Any other extension: warns, then `process_rb`.
24
+ Unknown,
25
+ }
26
+
27
+ /// A file's handler and the extension it was chosen by.
28
+ #[derive(Clone, Debug, PartialEq, Eq)]
29
+ pub struct FileHandler {
30
+ pub handler: Handler,
31
+ /// `File.extname(file).sub(/^\./, "")`, or `"rb"` when that is empty.
32
+ pub extension: String,
33
+ }
34
+
35
+ /// The handler for `path`. `.erb` files are ERB only when `erb_plugin_loaded`.
36
+ pub fn handler_for(path: &str, erb_plugin_loaded: bool) -> FileHandler {
37
+ let extname = ruby_extname(path);
38
+ let extension = match extname.strip_prefix('.').unwrap_or(extname) {
39
+ "" => "rb",
40
+ other => other,
41
+ };
42
+ let handler = match extension {
43
+ "rb" => Handler::Ruby,
44
+ "erb" if erb_plugin_loaded => Handler::Erb,
45
+ "sexp" => Handler::ProcessSexp,
46
+ "fuzzy" => Handler::ProcessFuzzy,
47
+ _ => Handler::Unknown,
48
+ };
49
+ FileHandler { handler, extension: extension.to_string() }
50
+ }
51
+
52
+ /// `File.extname(path)` on a POSIX system: the basename's text from its last
53
+ /// dot, ignoring leading dots; `"."` for a name ending in a dot.
54
+ fn ruby_extname(path: &str) -> &str {
55
+ let trimmed = path.trim_end_matches('/');
56
+ let basename = trimmed.rsplit('/').next().unwrap_or(trimmed);
57
+ let name = basename.trim_start_matches('.');
58
+ match name.rfind('.') {
59
+ Some(dot) => &name[dot..],
60
+ None => "",
61
+ }
62
+ }
63
+
64
+ /// A parsed file after `Flay#filter_sexp`: its tree without the sexps a
65
+ /// filter is satisfied by, and the exception a filter raised, if any.
66
+ #[derive(Clone, Debug)]
67
+ pub struct FilteredFile {
68
+ pub parsed: ParsedFile,
69
+ pub filter_result: Result<(), RubyException>,
70
+ }
71
+
72
+ /// Parses and filters each file whose handler parses it, in parallel, in
73
+ /// input order; `None` for the files `process_sexp` and `process_fuzzy`
74
+ /// handle.
75
+ pub fn parse_files(
76
+ paths: &[String],
77
+ handlers: &[Handler],
78
+ ruby_version: &str,
79
+ filters: &[Filter],
80
+ ) -> Result<Vec<Option<FilteredFile>>, rayon::ThreadPoolBuildError> {
81
+ // Deeply nested code recurses deeply in the translator.
82
+ let pool = rayon::ThreadPoolBuilder::new().stack_size(256 << 20).build()?;
83
+ Ok(pool.install(|| {
84
+ paths
85
+ .par_iter()
86
+ .zip(handlers)
87
+ .map(|(path, handler)| {
88
+ let parsed = match handler {
89
+ Handler::Ruby | Handler::Unknown => parse_file(path, ruby_version),
90
+ Handler::Erb => erb::parse_erb_file(path, ruby_version),
91
+ Handler::ProcessSexp | Handler::ProcessFuzzy => return None,
92
+ };
93
+ Some(filter_parsed_file(parsed, filters))
94
+ })
95
+ .collect()
96
+ }))
97
+ }
98
+
99
+ /// `Flay#filter_sexp` on a parsed file's tree.
100
+ fn filter_parsed_file(mut parsed: ParsedFile, filters: &[Filter]) -> FilteredFile {
101
+ let mut filter_result = Ok(());
102
+ if !filters.is_empty() {
103
+ if let Ok((tree, Value::Sexp(root))) = &mut parsed.outcome {
104
+ filter_result = filter_sexp(tree, *root, filters);
105
+ tree.finish();
106
+ }
107
+ }
108
+ FilteredFile { parsed, filter_result }
109
+ }
110
+
111
+ /// Why Flay skipped a file.
112
+ #[derive(Clone, Copy, Debug, PartialEq)]
113
+ pub enum SkipReason<'a> {
114
+ /// `process_sexp(file)` raised `NoMethodError` on the file name.
115
+ ProcessSexp,
116
+ /// `process_fuzzy(file)` raised `ArgumentError`.
117
+ ProcessFuzzy,
118
+ /// Reading the file raised (see [`Skip::Unreadable`]).
119
+ Unreadable(&'a str),
120
+ /// Parsing raised `RubyParser::SyntaxError` with this message.
121
+ SyntaxError(&'a str),
122
+ /// Translating raised another exception.
123
+ Raised(&'a RubyException),
124
+ }
125
+
126
+ /// Why Flay skips a file with this handler and parse result, or `None` when
127
+ /// it processes the file.
128
+ pub fn skip_reason(handler: Handler, parsed: Option<&FilteredFile>) -> Option<SkipReason<'_>> {
129
+ match (handler, parsed) {
130
+ (Handler::ProcessSexp, _) => Some(SkipReason::ProcessSexp),
131
+ (Handler::ProcessFuzzy, _) => Some(SkipReason::ProcessFuzzy),
132
+ (_, Some(filtered)) => match &filtered.parsed.outcome {
133
+ Ok(_) => None,
134
+ Err(Skip::Unreadable(message)) => Some(SkipReason::Unreadable(message)),
135
+ Err(Skip::SyntaxError(message)) => Some(SkipReason::SyntaxError(message)),
136
+ Err(Skip::Raised(exception)) => Some(SkipReason::Raised(exception)),
137
+ },
138
+ (_, None) => None,
139
+ }
140
+ }
141
+
142
+ /// The message of `process_fuzzy(file)`'s `ArgumentError`.
143
+ pub const PROCESS_FUZZY_MESSAGE: &str = "wrong number of arguments (given 1, expected 2)";
144
+
145
+ /// `"Processing #{file}"`, warned for each file with `verbose`.
146
+ pub fn processing_warning(path: &str) -> String {
147
+ format!("Processing {path}")
148
+ }
149
+
150
+ /// The warning for a file whose extension has no handler.
151
+ pub fn unknown_file_type_warning(extension: &str) -> String {
152
+ format!(" Unknown file type: {extension}, defaulting to ruby")
153
+ }
154
+
155
+ /// The two warnings for a skipped file: the exception's message, stripped
156
+ /// as `String#strip` does, then `skipping`.
157
+ pub fn skip_warnings(path: &str, message: &str) -> [String; 2] {
158
+ let stripped = message.trim_matches(|c: char| c.is_ascii_whitespace() || c == '\0');
159
+ [format!(" {stripped}"), format!(" skipping {path}")]
160
+ }
161
+
162
+ /// The message of the `NoMethodError` that `process_sexp(file)` raises when
163
+ /// `filter_sexp` calls `delete_if` on the file name, in the wording of the
164
+ /// given `RUBY_VERSION`.
165
+ pub fn process_sexp_message(ruby_version: &str) -> String {
166
+ let mut parts = ruby_version.split('.').map(|part| part.parse::<u32>().unwrap_or(0));
167
+ let version = (parts.next().unwrap_or(0), parts.next().unwrap_or(0));
168
+ if ruby_version == "latest" || version >= (3, 4) {
169
+ "undefined method 'delete_if' for an instance of String".to_string()
170
+ } else {
171
+ "undefined method `delete_if' for an instance of String".to_string()
172
+ }
173
+ }
174
+
175
+ /// The options of `Flay#process` that [`Flay::process`] reads.
176
+ #[derive(Clone, Debug)]
177
+ pub struct ProcessFilesOptions<'a> {
178
+ pub process: ProcessOptions,
179
+ /// Whether `Flay.load_plugins` loaded `flay_erb`.
180
+ pub erb_plugin_loaded: bool,
181
+ /// `option[:filters]`.
182
+ pub filters: &'a [Filter],
183
+ /// `option[:verbose]`.
184
+ pub verbose: bool,
185
+ /// The `RUBY_VERSION` Flay would run under.
186
+ pub ruby_version: &'a str,
187
+ }
188
+
189
+ /// What [`Flay::process`] did besides adding nodes.
190
+ #[derive(Clone, Debug, Default, PartialEq)]
191
+ pub struct ProcessReport {
192
+ /// The messages Flay passes to `warn`, in order.
193
+ pub warnings: Vec<String>,
194
+ /// The exception a filter raised, which ends `process` (the files
195
+ /// before it stay processed).
196
+ pub exception: Option<RubyException>,
197
+ }
198
+
199
+ impl Flay {
200
+ /// `Flay#process(*files)`. With `verbose`, an ERB file whose Ruby fails
201
+ /// to parse does not have that Ruby printed (the Ruby binding prints it).
202
+ pub fn process(
203
+ &mut self,
204
+ paths: &[String],
205
+ options: &ProcessFilesOptions,
206
+ ) -> Result<ProcessReport, rayon::ThreadPoolBuildError> {
207
+ let handlers: Vec<FileHandler> =
208
+ paths.iter().map(|path| handler_for(path, options.erb_plugin_loaded)).collect();
209
+ let kinds: Vec<Handler> = handlers.iter().map(|handler| handler.handler).collect();
210
+ let parsed = parse_files(paths, &kinds, options.ruby_version, options.filters)?;
211
+
212
+ let mut report = ProcessReport::default();
213
+ for ((path, handler), parsed) in paths.iter().zip(&handlers).zip(parsed) {
214
+ if options.verbose {
215
+ report.warnings.push(processing_warning(path));
216
+ }
217
+ if handler.handler == Handler::Unknown {
218
+ report.warnings.push(unknown_file_type_warning(&handler.extension));
219
+ }
220
+ if let Some(reason) = skip_reason(handler.handler, parsed.as_ref()) {
221
+ let message = match reason {
222
+ SkipReason::ProcessSexp => process_sexp_message(options.ruby_version),
223
+ SkipReason::ProcessFuzzy => PROCESS_FUZZY_MESSAGE.to_string(),
224
+ SkipReason::Unreadable(message) | SkipReason::SyntaxError(message) => message.to_string(),
225
+ SkipReason::Raised(exception) => exception.message.clone(),
226
+ };
227
+ report.warnings.extend(skip_warnings(path, &message));
228
+ continue;
229
+ }
230
+ let Some(filtered) = parsed else { continue };
231
+ if let Err(exception) = filtered.filter_result {
232
+ report.exception = Some(exception);
233
+ return Ok(report);
234
+ }
235
+ self.process_parsed(filtered.parsed, options.process);
236
+ }
237
+ Ok(report)
238
+ }
239
+ }
240
+
241
+ #[cfg(test)]
242
+ mod tests {
243
+ use super::*;
244
+
245
+ #[test]
246
+ fn extname_follows_ruby() {
247
+ assert_eq!(ruby_extname("a/b.rb"), ".rb");
248
+ assert_eq!(ruby_extname("a.b/c"), "");
249
+ assert_eq!(ruby_extname(".bashrc"), "");
250
+ assert_eq!(ruby_extname("..rb"), "");
251
+ assert_eq!(ruby_extname("e."), ".");
252
+ assert_eq!(ruby_extname("x.tar.gz"), ".gz");
253
+ }
254
+
255
+ #[test]
256
+ fn handlers_follow_the_extension() {
257
+ assert_eq!(handler_for("a.rb", false), FileHandler { handler: Handler::Ruby, extension: "rb".into() });
258
+ assert_eq!(handler_for("bin/tool", false), FileHandler { handler: Handler::Ruby, extension: "rb".into() });
259
+ assert_eq!(handler_for("e.", false), FileHandler { handler: Handler::Ruby, extension: "rb".into() });
260
+ assert_eq!(handler_for("a.erb", false).handler, Handler::Unknown);
261
+ assert_eq!(handler_for("a.erb", true).handler, Handler::Erb);
262
+ assert_eq!(handler_for("a.sexp", false).handler, Handler::ProcessSexp);
263
+ assert_eq!(handler_for("a.fuzzy", false).handler, Handler::ProcessFuzzy);
264
+ assert_eq!(
265
+ handler_for("Rakefile.rake", false),
266
+ FileHandler { handler: Handler::Unknown, extension: "rake".into() }
267
+ );
268
+ }
269
+
270
+ #[test]
271
+ fn process_sexp_message_follows_the_ruby_version() {
272
+ assert_eq!(process_sexp_message("3.4.1"), "undefined method 'delete_if' for an instance of String");
273
+ assert_eq!(process_sexp_message("3.3.0"), "undefined method `delete_if' for an instance of String");
274
+ }
275
+
276
+ #[test]
277
+ fn process_warns_and_skips_like_flay() {
278
+ let directory = std::env::temp_dir().join(format!("flay-core-process-{}", std::process::id()));
279
+ std::fs::create_dir_all(&directory).unwrap();
280
+ let write = |name: &str, source: &str| {
281
+ let path = directory.join(name);
282
+ std::fs::write(&path, source).unwrap();
283
+ path.to_string_lossy().into_owned()
284
+ };
285
+ let good = write("good.rake", "def a\n [1, 2, 3].map { |x| x * 2 }\nend\n");
286
+ let bad = write("bad.rb", "def a(\n");
287
+ let fuzzy = write("c.fuzzy", "");
288
+ let missing = directory.join("missing.rb").to_string_lossy().into_owned();
289
+ let paths = vec![good.clone(), bad.clone(), fuzzy.clone(), missing.clone()];
290
+
291
+ let mut flay = Flay::new();
292
+ let options = ProcessFilesOptions {
293
+ process: ProcessOptions { mass_threshold: crate::DEFAULT_MASS, fuzzy: None },
294
+ erb_plugin_loaded: false,
295
+ filters: &[],
296
+ verbose: false,
297
+ ruby_version: "3.4.0",
298
+ };
299
+ let report = flay.process(&paths, &options).unwrap();
300
+ std::fs::remove_dir_all(&directory).unwrap();
301
+
302
+ assert_eq!(report.exception, None);
303
+ assert_eq!(report.warnings[0], " Unknown file type: rake, defaulting to ruby");
304
+ assert!(report.warnings[1].starts_with(&format!(" {bad}:1 :: ")));
305
+ assert_eq!(report.warnings[2], format!(" skipping {bad}"));
306
+ assert_eq!(report.warnings[3], format!(" {PROCESS_FUZZY_MESSAGE}"));
307
+ assert_eq!(report.warnings[4], format!(" skipping {fuzzy}"));
308
+ assert_eq!(report.warnings[5], format!(" No such file or directory @ rb_sysopen - {missing}"));
309
+ assert_eq!(report.warnings[6], format!(" skipping {missing}"));
310
+ assert_eq!(report.warnings.len(), 7);
311
+ }
312
+ }