| 1 | use std::env::current_dir; |
| 2 | use std::io::Write; |
| 3 | use std::path::{Path, PathBuf}; |
| 4 | use std::process::Command; |
| 5 | use std::{fs, io}; |
| 6 | |
| 7 | use anyhow::{bail, ensure, Context, Result}; |
| 8 | use serde::Deserialize; |
| 9 | use skidder::{Metadata, ParserDefinition}; |
| 10 | use walkdir::WalkDir; |
| 11 | |
| 12 | use crate::flags::Import; |
| 13 | const LICENSE_FILE_NAMES: &[&str] = &["LICENSE", "LICENSE.txt", "LICENCE", "LICENCE", "COPYING"]; |
| 14 | const LICENSE_SEARCH: &[(&str, &str)] = &[ |
| 15 | ("unlicense", "unlicense"), |
| 16 | ("EUROPEAN UNION PUBLIC LICENCE v. 1.2", "EUPL-1.2"), |
| 17 | ("The Artistic License 2.0", "Artistic-2.0"), |
| 18 | ("Apache License", "Apache-2.0"), |
| 19 | ("GNU GENERAL PUBLIC LICENSE", "GPL-3.0"), |
| 20 | ("MIT License", "MIT"), |
| 21 | ("DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE", "WTFPL"), |
| 22 | ("BSD 3-Clause License", "BSD-3-Clause"), |
| 23 | ]; |
| 24 | |
| 25 | impl Import { |
| 26 | fn repo(&self) -> Result<PathBuf> { |
| 27 | match &self.repo { |
| 28 | Some(path) => Ok(path.clone()), |
| 29 | None => Ok(current_dir()?), |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | pub fn run(self) -> Result<()> { |
| 34 | let repo = self.repo()?; |
| 35 | for path in &self.path { |
| 36 | let Some(dir_name) = path.file_name().and_then(|file_name| file_name.to_str()) else { |
| 37 | bail!("invalid path {path:?}"); |
| 38 | }; |
| 39 | let mut src_path = path.to_owned(); |
| 40 | let grammar_name = match dir_name.rsplit_once(':') { |
| 41 | Some((dir_name, grammar_name)) => { |
| 42 | src_path.set_file_name(dir_name); |
| 43 | grammar_name |
| 44 | } |
| 45 | None => dir_name, |
| 46 | }; |
| 47 | src_path.push("src"); |
| 48 | let mut dst_path = repo.join(grammar_name); |
| 49 | fs::create_dir_all(&dst_path) |
| 50 | .with_context(|| format!("failed to create {}", dst_path.display()))?; |
| 51 | if !src_path.join("parser.c").exists() { |
| 52 | eprintln!( |
| 53 | "skipping grammar {grammar_name}: no parser.c found at {}!", |
| 54 | src_path.display() |
| 55 | ); |
| 56 | continue; |
| 57 | } |
| 58 | src_path.pop(); |
| 59 | println!("importing {grammar_name}"); |
| 60 | for dir in ["src", "../common"] { |
| 61 | let src_path = src_path.join(dir); |
| 62 | if !src_path.exists() { |
| 63 | continue; |
| 64 | } |
| 65 | dst_path.push(dir.strip_prefix("../").unwrap_or(dir)); |
| 66 | for file in WalkDir::new(&src_path) { |
| 67 | let file = file?; |
| 68 | if !file.file_type().is_file() { |
| 69 | continue; |
| 70 | } |
| 71 | let Some(file_name) = file.file_name().to_str() else { |
| 72 | continue; |
| 73 | }; |
| 74 | let Some((_, extension)) = file_name.rsplit_once('.') else { |
| 75 | continue; |
| 76 | }; |
| 77 | if !(matches!(extension, "h" | "c" | "cc") |
| 78 | || extension == "scm" && self.import_queries |
| 79 | || file_name == "grammar.json") |
| 80 | || file_name.starts_with("parser_abi") && extension == "c" |
| 81 | { |
| 82 | continue; |
| 83 | } |
| 84 | let relative_path = file.path().strip_prefix(&src_path).unwrap(); |
| 85 | let dst_path = dst_path.join(relative_path); |
| 86 | fs::create_dir_all(dst_path.parent().unwrap()).with_context(|| { |
| 87 | format!("failed to create {}", dst_path.parent().unwrap().display()) |
| 88 | })?; |
| 89 | let res = if matches!(file_name, "parser.c" | "grammar.json") |
| 90 | && file.path().parent() == Some(&src_path) |
| 91 | && dir == "src" |
| 92 | { |
| 93 | import_compressed(file.path(), &dst_path)?; |
| 94 | continue; |
| 95 | } else if matches!(extension, "h" | "c" | "cc") |
| 96 | && src_path.join("../../common").exists() |
| 97 | { |
| 98 | fs::read_to_string(file.path()).and_then(|contents| { |
| 99 | let contents = contents.replace("../../common/", "../common/"); |
| 100 | fs::write(&dst_path, contents) |
| 101 | }) |
| 102 | } else { |
| 103 | fs::copy(file.path(), &dst_path).map(|_| ()) |
| 104 | }; |
| 105 | res.with_context(|| { |
| 106 | format!( |
| 107 | "failed to copy {} to {}", |
| 108 | file.path().display(), |
| 109 | dst_path.display() |
| 110 | ) |
| 111 | })?; |
| 112 | } |
| 113 | dst_path.pop(); |
| 114 | } |
| 115 | let license_file = LICENSE_FILE_NAMES |
| 116 | .iter() |
| 117 | .map(|name| src_path.join(name)) |
| 118 | .find(|src_path| src_path.exists()); |
| 119 | let mut license = None; |
| 120 | if let Some(license_file) = license_file { |
| 121 | let license_file_content = fs::read_to_string(&license_file) |
| 122 | .with_context(|| format!("failed to read {}", license_file.display()))?; |
| 123 | fs::write(dst_path.join("LICENSE"), &license_file_content).with_context(|| { |
| 124 | format!("failed to write {}", dst_path.join("LICENSE").display()) |
| 125 | })?; |
| 126 | license = LICENSE_SEARCH |
| 127 | .iter() |
| 128 | .find(|(needle, _)| license_file_content.contains(needle)) |
| 129 | .map(|(_, license)| (*license).to_owned()); |
| 130 | if license.is_none() { |
| 131 | eprintln!("failed to identify license in {}", license_file.display()); |
| 132 | } |
| 133 | } else { |
| 134 | eprintln!("warning: {grammar_name} does not have a LICENSE file!"); |
| 135 | } |
| 136 | if self.metadata { |
| 137 | let metadata_path = dst_path.join("metadata.json"); |
| 138 | let rev = |
| 139 | git_output(&["rev-parse", "HEAD"], &src_path, false).with_context(|| { |
| 140 | format!("failed to obtain git revision at {}", src_path.display()) |
| 141 | })?; |
| 142 | let repo = git_output(&["remote", "get-url", "origin"], &src_path, false) |
| 143 | .with_context(|| { |
| 144 | format!("failed to obtain git remote at {}", src_path.display()) |
| 145 | })?; |
| 146 | let package_metadata: Option<PackageJson> = |
| 147 | fs::read_to_string(src_path.join("package.json")) |
| 148 | .ok() |
| 149 | .and_then(|json| serde_json::from_str(&json).ok()); |
| 150 | if let Some(package_metadata) = package_metadata { |
| 151 | match &license { |
| 152 | Some(license) if license != &package_metadata.license => eprintln!("warning: license in package identifier differs from detected license {license} != {}", &package_metadata.license), |
| 153 | _ => license = Some(package_metadata.license), |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | let old_metadata = Metadata::read(&metadata_path) |
| 158 | .ok() |
| 159 | .and_then(Metadata::parser_definition) |
| 160 | .filter(|old_meta| old_meta.repo == repo && !old_meta.license.is_empty()); |
| 161 | |
| 162 | if let Some(old_metadata) = &old_metadata { |
| 163 | match &license { |
| 164 | Some(license) => { |
| 165 | if license != &old_metadata.license { |
| 166 | eprintln!( |
| 167 | "warning: license has changed {} => {license}", |
| 168 | old_metadata.license |
| 169 | ); |
| 170 | } |
| 171 | } |
| 172 | None => { |
| 173 | eprintln!( |
| 174 | "warning: couldn't determine license for {grammar_name}, keeping {:?}", |
| 175 | old_metadata.license |
| 176 | ); |
| 177 | license = Some(old_metadata.license.clone()) |
| 178 | } |
| 179 | } |
| 180 | } |
| 181 | if license.is_none() { |
| 182 | eprintln!("warning: couldn't import determine license for {grammar_name}",); |
| 183 | } |
| 184 | |
| 185 | let metadata = Metadata::ParserDefinition(ParserDefinition { |
| 186 | repo, |
| 187 | rev, |
| 188 | license: license.unwrap_or_default(), |
| 189 | compressed: true, |
| 190 | }); |
| 191 | metadata.write(&metadata_path).with_context(|| { |
| 192 | format!( |
| 193 | "failed to write metadata.json to {}", |
| 194 | metadata_path.display() |
| 195 | ) |
| 196 | })? |
| 197 | } |
| 198 | } |
| 199 | Ok(()) |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | #[derive(Deserialize)] |
| 204 | struct PackageJson { |
| 205 | license: String, |
| 206 | } |
| 207 | |
| 208 | fn git_output(args: &[&str], dir: &Path, verbose: bool) -> Result<String> { |
| 209 | let mut cmd = Command::new("git"); |
| 210 | cmd.args(args).current_dir(dir); |
| 211 | if verbose { |
| 212 | println!("{}: git {}", dir.display(), args.join(" ")) |
| 213 | } |
| 214 | let res = cmd.output().context("failed to invoke git")?; |
| 215 | if !res.status.success() { |
| 216 | let _ = io::stdout().write_all(&res.stdout); |
| 217 | let _ = io::stderr().write_all(&res.stderr); |
| 218 | bail!("git returned non-zero exit-code: {}", res.status); |
| 219 | } |
| 220 | String::from_utf8(res.stdout) |
| 221 | .context("git returned invalid utf8") |
| 222 | .map(|output| output.trim_end().to_string()) |
| 223 | } |
| 224 | |
| 225 | pub fn import_compressed(src: &Path, dst: &Path) -> anyhow::Result<()> { |
| 226 | let success = Command::new("zstd") |
| 227 | .args(["--ultra", "-22", "-f", "-o"]) |
| 228 | .arg(dst) |
| 229 | .arg(src) |
| 230 | .status() |
| 231 | .with_context(|| format!("failed to compress {}", src.display()))? |
| 232 | .success(); |
| 233 | ensure!(success, "failed to compress {}", src.display()); |
| 234 | Ok(()) |
| 235 | } |