|
| 1 | +//! This module provides functionality for read from and write to Pants BUILD file. |
| 2 | +
|
| 3 | +use std::collections::BTreeSet; |
| 4 | +use std::error::Error; |
| 5 | +use std::fmt; |
| 6 | +use std::fmt::{Debug, Formatter}; |
| 7 | +use std::fs; |
| 8 | +use std::fs::File; |
| 9 | +use std::io::{BufRead, BufReader, BufWriter, Write}; |
| 10 | +use std::path::PathBuf; |
| 11 | +use std::string::ToString; |
| 12 | + |
| 13 | +/// Representation fof Pants address. |
| 14 | +#[derive(Clone, PartialOrd, Ord, PartialEq, Eq)] |
| 15 | +pub struct Address { |
| 16 | + pub folder: String, |
| 17 | + pub module_name: String, |
| 18 | +} |
| 19 | + |
| 20 | +impl Address { |
| 21 | + pub fn from_str(str: &str) -> Self { |
| 22 | + let split = str.split(':').collect::<Vec<_>>(); |
| 23 | + let folder = split[0].to_string(); |
| 24 | + let module_name = split[1].to_string(); |
| 25 | + Address { |
| 26 | + folder, |
| 27 | + module_name, |
| 28 | + } |
| 29 | + } |
| 30 | + /// In the case when 1 folder == 1 module return true. |
| 31 | + pub fn is_simple(&self) -> bool { |
| 32 | + self.folder.ends_with(&self.module_name) |
| 33 | + } |
| 34 | + |
| 35 | + /// Line corresponds to this address. |
| 36 | + pub fn match_line(&self, line: &str) -> bool { |
| 37 | + line.contains(&format!("'{}:{}'", self.folder, self.module_name)) // full address |
| 38 | + || (self.is_simple() && line.contains(&format!("'{}'", &self.folder))) // only folder |
| 39 | + || line.contains(&format!("':{}'", self.module_name)) // only module name |
| 40 | + } |
| 41 | + |
| 42 | + pub fn as_str(&self) -> String { |
| 43 | + if self.is_simple() { |
| 44 | + self.folder.to_string() |
| 45 | + } else { |
| 46 | + format!("{}:{}", self.folder, self.module_name) |
| 47 | + } |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +impl Debug for Address { |
| 52 | + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { |
| 53 | + write!(f, "{:?}:{:?}", self.folder, self.module_name) |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +/// Finds BUILD file and removes lines with unused dependencies, returns number of removed lines. |
| 58 | +pub fn remove_deps( |
| 59 | + module: &Address, |
| 60 | + deps: Vec<Address>, |
| 61 | + skip_marker: &str, |
| 62 | +) -> Result<usize, Box<dyn Error>> { |
| 63 | + let mut counter = 0; |
| 64 | + |
| 65 | + for entry in fs::read_dir(&module.folder)? { |
| 66 | + let entry = entry?; |
| 67 | + if entry.file_name() == "BUILD" { |
| 68 | + // read and filter unused dependencies |
| 69 | + let cleaned = { |
| 70 | + let file = BufReader::new(File::open(entry.path())?); |
| 71 | + |
| 72 | + let mut inside_module_section = module.is_simple(); |
| 73 | + let mut inside_module_dep_section = false; |
| 74 | + |
| 75 | + file.lines() |
| 76 | + .filter_map(|line| { |
| 77 | + let line = line.unwrap_or_else(|_| { |
| 78 | + panic!("Couldn't read line from {}/BUILD ", module.folder) |
| 79 | + }); |
| 80 | + |
| 81 | + if line.contains("name=") && line.contains(&module.module_name) { |
| 82 | + inside_module_section = true; |
| 83 | + } |
| 84 | + |
| 85 | + if inside_module_section && line.contains("dependencies") { |
| 86 | + inside_module_dep_section = true; |
| 87 | + } |
| 88 | + |
| 89 | + if inside_module_dep_section && line.contains(']') { |
| 90 | + inside_module_dep_section = false; |
| 91 | + inside_module_section = false; // actually no, but it's ok so simplifying |
| 92 | + } |
| 93 | + |
| 94 | + if inside_module_dep_section |
| 95 | + && !line.contains(skip_marker) |
| 96 | + && deps.iter().any(|target| target.match_line(&line)) |
| 97 | + { |
| 98 | + // we are in dependency block of required module |
| 99 | + // if line contents unused dep remove it from result |
| 100 | + counter += 1; |
| 101 | + None |
| 102 | + } else { |
| 103 | + Some(line) |
| 104 | + } |
| 105 | + }) |
| 106 | + .collect::<Vec<String>>() |
| 107 | + }; |
| 108 | + |
| 109 | + // write filtered dependencies back in BUILD file |
| 110 | + let mut file = BufWriter::new(File::create(entry.path())?); |
| 111 | + for line in cleaned { |
| 112 | + writeln!(file, "{}", line)?; |
| 113 | + } |
| 114 | + file.flush()?; |
| 115 | + break; |
| 116 | + } |
| 117 | + } |
| 118 | + Ok(counter) |
| 119 | +} |
| 120 | + |
| 121 | +/// Finds a BUILD file and inserts lines with undeclared dependencies, returns number of inserted lines. |
| 122 | +pub fn add_deps( |
| 123 | + module: &Address, |
| 124 | + deps: Vec<Address>, |
| 125 | + skip_marker: &str, |
| 126 | +) -> Result<usize, Box<dyn Error>> { |
| 127 | + let mut counter = 0; |
| 128 | + for entry in fs::read_dir(&module.folder)? { |
| 129 | + let entry = entry?; |
| 130 | + if entry.file_name() == "BUILD" { |
| 131 | + // read existed, add undeclared and sort |
| 132 | + |
| 133 | + let updated_deps = |
| 134 | + add_deps_to_file(entry.path(), &module, deps, &mut counter, skip_marker)?; |
| 135 | + |
| 136 | + // write filtered dependencies back in BUILD file |
| 137 | + let mut file = BufWriter::new(File::create(entry.path())?); |
| 138 | + for line in updated_deps { |
| 139 | + writeln!(file, "{}", line)?; |
| 140 | + } |
| 141 | + file.flush()?; |
| 142 | + break; |
| 143 | + } else { |
| 144 | + } |
| 145 | + } |
| 146 | + Ok(counter as usize) |
| 147 | +} |
| 148 | + |
| 149 | +/// Adds new deps to dependency block of the BUILD file. |
| 150 | +fn add_deps_to_file( |
| 151 | + file: PathBuf, |
| 152 | + module: &Address, |
| 153 | + deps: Vec<Address>, |
| 154 | + counter: &mut isize, |
| 155 | + skip_marker: &str, |
| 156 | +) -> Result<Vec<String>, Box<dyn Error>> { |
| 157 | + let file = BufReader::new(File::open(file)?); |
| 158 | + |
| 159 | + let deps_iter = deps |
| 160 | + .into_iter() |
| 161 | + .map(|dep| format!(" '{}',", dep.as_str())); |
| 162 | + |
| 163 | + let mut result: Vec<String> = Vec::new(); |
| 164 | + // we use BTreeSet because deps should be sorted and unique |
| 165 | + let mut updated_deps = BTreeSet::new(); |
| 166 | + let mut inside_module_section = module.is_simple(); |
| 167 | + let mut inside_module_dep_section = false; |
| 168 | + |
| 169 | + for line in file.lines() { |
| 170 | + let line = line?; |
| 171 | + |
| 172 | + if line.contains("name=") && line.contains(&module.module_name) { |
| 173 | + inside_module_section = true; |
| 174 | + } |
| 175 | + |
| 176 | + if line.contains(']') && inside_module_dep_section { |
| 177 | + // add undeclared to deps |
| 178 | + let before = updated_deps.len() as isize; |
| 179 | + updated_deps.extend(deps_iter.clone()); |
| 180 | + *counter += updated_deps.len() as isize - before; |
| 181 | + // add deps to file |
| 182 | + result.extend(updated_deps.clone()); |
| 183 | + result.push(line); |
| 184 | + inside_module_dep_section = false; |
| 185 | + inside_module_section = false; // actually no, but it's ok so simplifying |
| 186 | + continue; |
| 187 | + } |
| 188 | + |
| 189 | + if inside_module_dep_section { |
| 190 | + // we are into dep block just add new line into deps set |
| 191 | + if line.ends_with(',') || line.contains(skip_marker) { |
| 192 | + updated_deps.insert(line.replace('"', "'")); |
| 193 | + } else if !line.is_empty() { |
| 194 | + updated_deps.insert(line.replace('"', "'") + ","); |
| 195 | + }; |
| 196 | + continue; |
| 197 | + } |
| 198 | + |
| 199 | + if inside_module_section && line.contains("dependencies") { |
| 200 | + inside_module_dep_section = true; |
| 201 | + result.push(line); |
| 202 | + continue; |
| 203 | + } |
| 204 | + |
| 205 | + result.push(line); |
| 206 | + } |
| 207 | + |
| 208 | + Ok(result) |
| 209 | +} |
0 commit comments