|
| 1 | +//! Shared multi-file extraction driver. |
| 2 | +//! |
| 3 | +//! The `simple` (direct tree-sitter) and `desugaring` (parse + desugar) |
| 4 | +//! extractors differ only in how a language's schema is built and how a single |
| 5 | +//! file is extracted. Everything else — threading, matching files to languages |
| 6 | +//! by glob, writing TRAP, and copying into the source archive — is identical |
| 7 | +//! and lives here, parameterised over the [`LanguageExtractor`] trait. |
| 8 | +
|
| 9 | +use globset::{GlobBuilder, GlobSetBuilder}; |
| 10 | +use rayon::prelude::*; |
| 11 | +use std::fs::File; |
| 12 | +use std::io::BufRead; |
| 13 | +use std::path::{Path, PathBuf}; |
| 14 | + |
| 15 | +use crate::diagnostics; |
| 16 | +use crate::file_paths; |
| 17 | +use crate::node_types::NodeTypeMap; |
| 18 | +use crate::trap; |
| 19 | + |
| 20 | +/// A language that [`run_extractor`] can process: it knows its file globs, its |
| 21 | +/// TRAP schema, and how to extract a single file. Implemented by |
| 22 | +/// [`super::simple::LanguageSpec`] (direct tree-sitter extraction) and |
| 23 | +/// [`super::desugaring::LanguageSpec`] (parse into an AST and desugar it). |
| 24 | +pub(crate) trait LanguageExtractor: Sync { |
| 25 | + /// The file-name globs that select files for this language. |
| 26 | + fn file_globs(&self) -> &[String]; |
| 27 | + /// Build the TRAP node-type schema used to validate emitted tuples. |
| 28 | + fn build_schema(&self) -> std::io::Result<NodeTypeMap>; |
| 29 | + /// Extract a single file's `source` into `trap_writer`. |
| 30 | + fn extract_file( |
| 31 | + &self, |
| 32 | + schema: &NodeTypeMap, |
| 33 | + diagnostics_writer: &mut diagnostics::LogWriter, |
| 34 | + trap_writer: &mut trap::Writer, |
| 35 | + path: &Path, |
| 36 | + source: &[u8], |
| 37 | + ); |
| 38 | +} |
| 39 | + |
| 40 | +/// Drive extraction over `languages` for every file listed in `file_lists`. |
| 41 | +/// |
| 42 | +/// Sets up the thread pool, builds a combined glob set, and for each input file |
| 43 | +/// dispatches to the matching language's [`LanguageExtractor::extract_file`], |
| 44 | +/// writing the resulting TRAP and a source-archive copy. |
| 45 | +pub(crate) fn run_extractor<L: LanguageExtractor>( |
| 46 | + prefix: &str, |
| 47 | + languages: &[L], |
| 48 | + trap_dir: &Path, |
| 49 | + source_archive_dir: &Path, |
| 50 | + file_lists: &[PathBuf], |
| 51 | + trap_compression: &Result<trap::Compression, String>, |
| 52 | +) -> std::io::Result<()> { |
| 53 | + tracing::info!("Extraction started"); |
| 54 | + let diagnostics = diagnostics::DiagnosticLoggers::new(prefix); |
| 55 | + let mut main_thread_logger = diagnostics.logger(); |
| 56 | + let num_threads = match crate::options::num_threads() { |
| 57 | + Ok(num) => num, |
| 58 | + Err(e) => { |
| 59 | + main_thread_logger.write( |
| 60 | + main_thread_logger |
| 61 | + .new_entry("configuration-error", "Configuration error") |
| 62 | + .message( |
| 63 | + "{}; defaulting to 1 thread.", |
| 64 | + &[diagnostics::MessageArg::Code(&e)], |
| 65 | + ) |
| 66 | + .severity(diagnostics::Severity::Warning), |
| 67 | + ); |
| 68 | + 1 |
| 69 | + } |
| 70 | + }; |
| 71 | + tracing::info!( |
| 72 | + "Using {} {}", |
| 73 | + num_threads, |
| 74 | + if num_threads == 1 { |
| 75 | + "thread" |
| 76 | + } else { |
| 77 | + "threads" |
| 78 | + } |
| 79 | + ); |
| 80 | + let trap_compression = match trap_compression { |
| 81 | + Ok(x) => *x, |
| 82 | + Err(e) => { |
| 83 | + main_thread_logger.write( |
| 84 | + main_thread_logger |
| 85 | + .new_entry("configuration-error", "Configuration error") |
| 86 | + .message("{}; using gzip.", &[diagnostics::MessageArg::Code(e)]) |
| 87 | + .severity(diagnostics::Severity::Warning), |
| 88 | + ); |
| 89 | + trap::Compression::Gzip |
| 90 | + } |
| 91 | + }; |
| 92 | + drop(main_thread_logger); |
| 93 | + |
| 94 | + rayon::ThreadPoolBuilder::new() |
| 95 | + .num_threads(num_threads) |
| 96 | + .build_global() |
| 97 | + .unwrap(); |
| 98 | + |
| 99 | + let file_lists: Vec<File> = file_lists |
| 100 | + .iter() |
| 101 | + .map(|file_list| { |
| 102 | + File::open(file_list) |
| 103 | + .unwrap_or_else(|_| panic!("Unable to open file list at {file_list:?}")) |
| 104 | + }) |
| 105 | + .collect(); |
| 106 | + |
| 107 | + let mut schemas = vec![]; |
| 108 | + for lang in languages { |
| 109 | + schemas.push(lang.build_schema()?); |
| 110 | + } |
| 111 | + |
| 112 | + // Construct a single globset containing all language globs, |
| 113 | + // and a mapping from glob index to language index. |
| 114 | + let (globset, glob_language_mapping) = { |
| 115 | + let mut builder = GlobSetBuilder::new(); |
| 116 | + let mut glob_lang_mapping = vec![]; |
| 117 | + for (i, lang) in languages.iter().enumerate() { |
| 118 | + for glob_str in lang.file_globs() { |
| 119 | + let glob = GlobBuilder::new(glob_str) |
| 120 | + .literal_separator(true) |
| 121 | + .build() |
| 122 | + .expect("invalid glob"); |
| 123 | + builder.add(glob); |
| 124 | + glob_lang_mapping.push(i); |
| 125 | + } |
| 126 | + } |
| 127 | + ( |
| 128 | + builder.build().expect("failed to build globset"), |
| 129 | + glob_lang_mapping, |
| 130 | + ) |
| 131 | + }; |
| 132 | + |
| 133 | + let path_transformer = file_paths::load_path_transformer()?; |
| 134 | + |
| 135 | + let lines: std::io::Result<Vec<String>> = file_lists |
| 136 | + .iter() |
| 137 | + .flat_map(|file_list| std::io::BufReader::new(file_list).lines()) |
| 138 | + .collect(); |
| 139 | + let lines = lines?; |
| 140 | + |
| 141 | + lines |
| 142 | + .par_iter() |
| 143 | + .try_for_each(|line| { |
| 144 | + let mut diagnostics_writer = diagnostics.logger(); |
| 145 | + let path = PathBuf::from(line).canonicalize()?; |
| 146 | + let src_archive_file = crate::file_paths::path_for( |
| 147 | + source_archive_dir, |
| 148 | + &path, |
| 149 | + "", |
| 150 | + path_transformer.as_ref(), |
| 151 | + ); |
| 152 | + let source = std::fs::read(&path)?; |
| 153 | + let mut trap_writer = trap::Writer::new(); |
| 154 | + |
| 155 | + match path.file_name() { |
| 156 | + None => { |
| 157 | + tracing::error!(?path, "No file name found, skipping file."); |
| 158 | + } |
| 159 | + Some(filename) => { |
| 160 | + let matches = globset.matches(filename); |
| 161 | + if matches.is_empty() { |
| 162 | + tracing::error!(?path, "No matching language found, skipping file."); |
| 163 | + } else { |
| 164 | + let mut languages_processed = vec![false; languages.len()]; |
| 165 | + |
| 166 | + for m in matches { |
| 167 | + let i = glob_language_mapping[m]; |
| 168 | + if languages_processed[i] { |
| 169 | + continue; |
| 170 | + } |
| 171 | + languages_processed[i] = true; |
| 172 | + let lang = &languages[i]; |
| 173 | + |
| 174 | + lang.extract_file( |
| 175 | + &schemas[i], |
| 176 | + &mut diagnostics_writer, |
| 177 | + &mut trap_writer, |
| 178 | + &path, |
| 179 | + &source, |
| 180 | + ); |
| 181 | + std::fs::create_dir_all(src_archive_file.parent().unwrap())?; |
| 182 | + std::fs::copy(&path, &src_archive_file)?; |
| 183 | + write_trap(trap_dir, &path, &trap_writer, trap_compression)?; |
| 184 | + } |
| 185 | + } |
| 186 | + } |
| 187 | + } |
| 188 | + Ok(()) as std::io::Result<()> |
| 189 | + }) |
| 190 | + .expect("failed to extract files"); |
| 191 | + |
| 192 | + let path = PathBuf::from("extras"); |
| 193 | + let mut trap_writer = trap::Writer::new(); |
| 194 | + crate::extractor::populate_empty_location(&mut trap_writer); |
| 195 | + |
| 196 | + let res = write_trap(trap_dir, &path, &trap_writer, trap_compression); |
| 197 | + tracing::info!("Extraction complete"); |
| 198 | + res |
| 199 | +} |
| 200 | + |
| 201 | +fn write_trap( |
| 202 | + trap_dir: &Path, |
| 203 | + path: &Path, |
| 204 | + trap_writer: &trap::Writer, |
| 205 | + trap_compression: trap::Compression, |
| 206 | +) -> std::io::Result<()> { |
| 207 | + let trap_file = crate::file_paths::path_for(trap_dir, path, trap_compression.extension(), None); |
| 208 | + std::fs::create_dir_all(trap_file.parent().unwrap())?; |
| 209 | + trap_writer.write_to_file(&trap_file, trap_compression) |
| 210 | +} |
0 commit comments