1use crate::parser::SqlDialect;
4use crate::redactor::StrategyKind;
5use serde::{Deserialize, Serialize};
6use std::path::PathBuf;
7
8#[derive(Debug)]
10pub struct RedactConfig {
11 pub input: PathBuf,
13 pub output: Option<PathBuf>,
15 pub dialect: SqlDialect,
17 pub rules: Vec<Rule>,
19 pub default_strategy: StrategyKind,
21 pub seed: Option<u64>,
23 pub locale: String,
25 pub tables_filter: Option<Vec<String>>,
27 pub exclude: Vec<String>,
29 pub strict: bool,
31 pub progress: bool,
33 pub dry_run: bool,
35}
36
37impl RedactConfig {
38 pub fn builder() -> RedactConfigBuilder {
40 RedactConfigBuilder::default()
41 }
42
43 pub fn validate(&self) -> anyhow::Result<()> {
45 if !self.input.exists() {
47 anyhow::bail!("Input file not found: {:?}", self.input);
48 }
49
50 if !is_valid_locale(&self.locale) && self.strict {
52 anyhow::bail!(
53 "Unsupported locale: {}. Use --locale with a supported value.",
54 self.locale
55 );
56 }
57
58 self.default_strategy.validate()?;
59
60 for rule in &self.rules {
62 rule.validate()?;
63 }
64
65 Ok(())
66 }
67}
68
69fn is_valid_locale(locale: &str) -> bool {
71 matches!(
72 locale.to_lowercase().as_str(),
73 "en" | "en_us" | "de_de" | "fr_fr" | "zh_cn" | "zh_tw" | "ja_jp" | "pt_br" | "ar_sa"
74 )
75}
76
77#[derive(Default)]
79pub struct RedactConfigBuilder {
80 input: Option<PathBuf>,
81 output: Option<PathBuf>,
82 dialect: Option<SqlDialect>,
83 config_file: Option<PathBuf>,
84 null_patterns: Vec<String>,
85 hash_patterns: Vec<String>,
86 fake_patterns: Vec<String>,
87 mask_patterns: Vec<String>,
88 constant_patterns: Vec<String>,
89 seed: Option<u64>,
90 locale: String,
91 tables_filter: Option<Vec<String>>,
92 exclude: Vec<String>,
93 strict: bool,
94 progress: bool,
95 dry_run: bool,
96}
97
98impl RedactConfigBuilder {
99 pub fn input(mut self, path: PathBuf) -> Self {
100 self.input = Some(path);
101 self
102 }
103
104 pub fn output(mut self, path: Option<PathBuf>) -> Self {
105 self.output = path;
106 self
107 }
108
109 pub fn dialect(mut self, dialect: SqlDialect) -> Self {
110 self.dialect = Some(dialect);
111 self
112 }
113
114 pub fn config_file(mut self, path: Option<PathBuf>) -> Self {
115 self.config_file = path;
116 self
117 }
118
119 pub fn null_patterns(mut self, patterns: Vec<String>) -> Self {
120 self.null_patterns = patterns;
121 self
122 }
123
124 pub fn hash_patterns(mut self, patterns: Vec<String>) -> Self {
125 self.hash_patterns = patterns;
126 self
127 }
128
129 pub fn fake_patterns(mut self, patterns: Vec<String>) -> Self {
130 self.fake_patterns = patterns;
131 self
132 }
133
134 pub fn mask_patterns(mut self, patterns: Vec<String>) -> Self {
135 self.mask_patterns = patterns;
136 self
137 }
138
139 pub fn constant_patterns(mut self, patterns: Vec<String>) -> Self {
140 self.constant_patterns = patterns;
141 self
142 }
143
144 pub fn seed(mut self, seed: Option<u64>) -> Self {
145 self.seed = seed;
146 self
147 }
148
149 pub fn locale(mut self, locale: String) -> Self {
150 self.locale = locale;
151 self
152 }
153
154 pub fn tables_filter(mut self, tables: Option<Vec<String>>) -> Self {
155 self.tables_filter = tables;
156 self
157 }
158
159 pub fn exclude(mut self, exclude: Vec<String>) -> Self {
160 self.exclude = exclude;
161 self
162 }
163
164 pub fn strict(mut self, strict: bool) -> Self {
165 self.strict = strict;
166 self
167 }
168
169 pub fn progress(mut self, progress: bool) -> Self {
170 self.progress = progress;
171 self
172 }
173
174 pub fn dry_run(mut self, dry_run: bool) -> Self {
175 self.dry_run = dry_run;
176 self
177 }
178
179 pub fn build(self) -> anyhow::Result<RedactConfig> {
181 let input = self
182 .input
183 .ok_or_else(|| anyhow::anyhow!("Input file is required"))?;
184 let dialect = self.dialect.unwrap_or(SqlDialect::MySql);
185 let locale = if self.locale.is_empty() {
186 "en".to_string()
187 } else {
188 self.locale
189 };
190
191 let yaml_config = if let Some(ref path) = self.config_file {
193 Some(RedactYamlConfig::load(path)?)
194 } else {
195 None
196 };
197
198 let mut rules = Vec::new();
200
201 if let Some(ref yaml) = yaml_config {
203 rules.extend(yaml.rules.clone());
204 }
205
206 for pattern in &self.null_patterns {
208 rules.push(Rule {
209 column: pattern.clone(),
210 strategy: StrategyKind::Null,
211 });
212 }
213
214 for pattern in &self.hash_patterns {
215 rules.push(Rule {
216 column: pattern.clone(),
217 strategy: StrategyKind::Hash {
218 preserve_domain: false,
219 },
220 });
221 }
222
223 for pattern in &self.fake_patterns {
224 rules.push(Rule {
225 column: pattern.clone(),
226 strategy: StrategyKind::Fake {
227 generator: "name".to_string(),
228 },
229 });
230 }
231
232 for pattern in &self.mask_patterns {
233 if let Some((mask_pattern, column)) = pattern.split_once('=') {
235 rules.push(Rule {
236 column: column.to_string(),
237 strategy: StrategyKind::Mask {
238 pattern: mask_pattern.to_string(),
239 },
240 });
241 }
242 }
243
244 for pattern in &self.constant_patterns {
245 if let Some((column, value)) = pattern.split_once('=') {
247 rules.push(Rule {
248 column: column.to_string(),
249 strategy: StrategyKind::Constant {
250 value: value.to_string(),
251 },
252 });
253 }
254 }
255
256 let default_strategy = yaml_config
258 .as_ref()
259 .and_then(|y| y.defaults.as_ref())
260 .map(|d| d.strategy.clone())
261 .unwrap_or(StrategyKind::Skip);
262
263 let seed = self
265 .seed
266 .or_else(|| yaml_config.as_ref().and_then(|y| y.seed));
267
268 let locale = if locale != "en" {
270 locale
271 } else {
272 yaml_config
273 .as_ref()
274 .and_then(|y| y.locale.clone())
275 .unwrap_or(locale)
276 };
277
278 let mut exclude = self.exclude;
280 if let Some(ref yaml) = yaml_config {
281 if let Some(ref skip) = yaml.skip_tables {
282 exclude.extend(skip.iter().cloned());
283 }
284 }
285
286 Ok(RedactConfig {
287 input,
288 output: self.output,
289 dialect,
290 rules,
291 default_strategy,
292 seed,
293 locale,
294 tables_filter: self.tables_filter,
295 exclude,
296 strict: self.strict,
297 progress: self.progress,
298 dry_run: self.dry_run,
299 })
300 }
301}
302
303#[derive(Debug, Clone, Serialize, Deserialize)]
305pub struct Rule {
306 pub column: String,
308 #[serde(flatten)]
310 pub strategy: StrategyKind,
311}
312
313impl Rule {
314 pub fn validate(&self) -> anyhow::Result<()> {
316 if self.column.is_empty() {
317 anyhow::bail!("Rule column pattern cannot be empty");
318 }
319 self.strategy.validate()
320 }
321}
322
323#[derive(Debug, Clone, Serialize, Deserialize)]
325pub struct RedactYamlConfig {
326 #[serde(skip_serializing_if = "Option::is_none")]
328 pub seed: Option<u64>,
329
330 #[serde(skip_serializing_if = "Option::is_none")]
332 pub locale: Option<String>,
333
334 #[serde(skip_serializing_if = "Option::is_none")]
336 pub defaults: Option<Defaults>,
337
338 #[serde(default)]
340 pub rules: Vec<Rule>,
341
342 #[serde(skip_serializing_if = "Option::is_none")]
344 pub skip_tables: Option<Vec<String>>,
345}
346
347impl RedactYamlConfig {
348 pub fn load(path: &PathBuf) -> anyhow::Result<Self> {
350 let content = std::fs::read_to_string(path)?;
351 let config: Self = serde_yaml_ng::from_str(&content)?;
352 Ok(config)
353 }
354
355 pub fn save(&self, path: &PathBuf) -> anyhow::Result<()> {
357 let content = serde_yaml_ng::to_string(self)?;
358 std::fs::write(path, content)?;
359 Ok(())
360 }
361}
362
363#[derive(Debug, Clone, Serialize, Deserialize)]
365pub struct Defaults {
366 pub strategy: StrategyKind,
368}