1use serde::Serialize;
13use std::collections::{HashMap, HashSet};
14
15#[derive(Debug, Serialize, PartialEq)]
16pub struct ImportedVar {
17 pub key: String,
18 pub value: String,
19 pub kind: String,
20 #[serde(skip_serializing_if = "std::ops::Not::not")]
24 pub public: bool,
25}
26
27#[derive(Debug, Serialize, PartialEq)]
28pub struct BundleImport {
29 pub vars: Vec<ImportedVar>,
30 pub warnings: Vec<String>,
31}
32
33fn is_ident(s: &str) -> bool {
34 let mut c = s.chars();
35 c.next()
36 .is_some_and(|f| f.is_ascii_alphabetic() || f == '_')
37 && c.all(|f| f.is_ascii_alphanumeric() || f == '_')
38}
39
40fn read_quoted(source: &str) -> Option<(String, String, String)> {
42 let b: Vec<char> = source.chars().collect();
43 let mut i = 0;
44 while i < b.len() && i < 2 && "fFuUrRbB".contains(b[i]) {
45 i += 1;
46 }
47 if i >= b.len() || (b[i] != '\'' && b[i] != '"') {
48 return None;
49 }
50 let prefix: String = b[..i].iter().collect::<String>().to_lowercase();
51 let quote = b[i];
52 let start = i + 1;
53 let mut end = start;
54 while end < b.len() {
55 if b[end] == '\\' {
56 end += 2;
57 continue;
58 }
59 if b[end] == quote {
60 break;
61 }
62 end += 1;
63 }
64 if end >= b.len() || b[end] != quote {
65 return None;
66 }
67 Some((
68 prefix,
69 b[start..end].iter().collect(),
70 b[end + 1..].iter().collect(),
71 ))
72}
73
74fn unescape_py(body: &str, raw: bool) -> Option<String> {
75 if raw {
76 return Some(body.to_string());
77 }
78 let mut out = String::new();
79 let mut it = body.chars();
80 while let Some(c) = it.next() {
81 if c != '\\' {
82 out.push(c);
83 continue;
84 }
85 match it.next()? {
86 'n' => out.push('\n'),
87 'r' => out.push('\r'),
88 't' => out.push('\t'),
89 '\\' => out.push('\\'),
90 '\'' => out.push('\''),
91 '"' => out.push('"'),
92 _ => return None,
93 }
94 }
95 Some(out)
96}
97
98fn convert_fstring(
100 body: &str,
101 bound: &HashMap<String, String>,
102) -> Option<(String, Vec<(String, String)>)> {
103 let c: Vec<char> = body.chars().collect();
104 let mut out = String::new();
105 let mut rewrote = Vec::new();
106 let mut i = 0;
107 while i < c.len() {
108 match c[i] {
109 '{' if c.get(i + 1) == Some(&'{') => {
110 out.push_str("{{");
111 i += 2;
112 }
113 '}' if c.get(i + 1) == Some(&'}') => {
114 out.push_str("}}");
115 i += 2;
116 }
117 '{' => {
118 let end = (i..c.len()).find(|&j| c[j] == '}')?;
119 let reference: String = c[i + 1..end].iter().collect();
120 let reference = reference.trim().to_string();
121 if !is_ident(&reference) {
122 return None;
123 }
124 let key = bound.get(&reference)?;
125 if *key != reference {
126 rewrote.push((reference.clone(), key.clone()));
127 }
128 out.push('{');
129 out.push_str(key);
130 out.push('}');
131 i = end + 1;
132 }
133 '}' => return None,
134 ch => {
135 out.push(ch);
136 i += 1;
137 }
138 }
139 }
140 Some((out, rewrote))
141}
142
143fn all_digits(s: &str) -> bool {
144 !s.is_empty() && s.chars().all(|c| c.is_ascii_digit())
145}
146
147fn signed(s: &str) -> &str {
148 s.strip_prefix(['-', '+']).unwrap_or(s)
149}
150
151fn is_radix_int(s: &str) -> bool {
152 let t = signed(s);
153 let Some(rest) = t.get(2..) else { return false };
154 match t.get(..2) {
155 Some("0x") | Some("0X") => !rest.is_empty() && rest.chars().all(|c| c.is_ascii_hexdigit()),
156 Some("0o") | Some("0O") => {
157 !rest.is_empty() && rest.chars().all(|c| ('0'..='7').contains(&c))
158 }
159 Some("0b") | Some("0B") => !rest.is_empty() && rest.chars().all(|c| c == '0' || c == '1'),
160 _ => false,
161 }
162}
163
164fn is_float(s: &str) -> bool {
165 let t = signed(s);
166 let (mant, exp) = match t.find(['e', 'E']) {
167 Some(i) => (&t[..i], Some(&t[i + 1..])),
168 None => (t, None),
169 };
170 if let Some(e) = exp {
171 if !all_digits(signed(e)) {
172 return false;
173 }
174 }
175 let mut parts = mant.splitn(2, '.');
176 let int = parts.next().unwrap_or("");
177 let frac = parts.next();
178 match frac {
179 None => all_digits(int),
180 Some(f) => {
181 (int.is_empty() || all_digits(int))
182 && (f.is_empty() || all_digits(f))
183 && !(int.is_empty() && f.is_empty())
184 }
185 }
186}
187
188fn strip_comment(s: &str) -> &str {
190 if let Some(i) = s.rfind(" #").or_else(|| s.rfind("\t#")) {
191 let tail = &s[i + 1..];
192 if !tail.contains('\'') && !tail.contains('"') {
193 return s[..i].trim_end();
194 }
195 }
196 s
197}
198
199fn kind_for_string(name: &str, body: &str) -> &'static str {
200 let looks_id = name.eq_ignore_ascii_case("id")
201 || name.eq_ignore_ascii_case("ids")
202 || name.to_lowercase().ends_with("_id")
203 || name.to_lowercase().ends_with("_ids");
204 let md = body
206 .strip_prefix('[')
207 .and_then(|b| b.strip_suffix(')'))
208 .and_then(|b| b.split_once("]("))
209 .is_some_and(|(label, target)| {
210 !label.contains(']')
211 && (target.starts_with("http://") || target.starts_with("https://"))
212 && !target.contains(char::is_whitespace)
213 && !target.contains(')')
214 });
215 let url = (body.starts_with("http://") || body.starts_with("https://"))
216 && !body.contains(char::is_whitespace);
217 if (all_digits(body) && body.len() >= 15) || (looks_id && all_digits(body) && body.len() >= 10)
218 {
219 "large_id"
220 } else if md {
221 "markdown_link"
222 } else if url {
223 "url"
224 } else {
225 "string"
226 }
227}
228
229fn secretish_name(name: &str) -> bool {
231 let n = name.to_ascii_lowercase();
232 [
233 "key",
234 "token",
235 "secret",
236 "password",
237 "passwd",
238 "pwd",
239 "auth",
240 "credential",
241 "salt",
242 "signature",
243 "private",
244 "webhook",
245 "cert",
246 ]
247 .iter()
248 .any(|w| n.contains(w))
249}
250
251fn url_is_public(url: &str) -> bool {
253 let u = url.trim().trim_start_matches('<').trim_end_matches('>');
254 let Some(rest) = u
255 .strip_prefix("https://")
256 .or_else(|| u.strip_prefix("http://"))
257 else {
258 return false;
259 };
260 let (authority, tail) = rest.split_once('/').unwrap_or((rest, ""));
261 if authority.contains('@') {
262 return false; }
264 let (path, query) = tail.split_once('?').unwrap_or((tail, ""));
265 let path = path.to_ascii_lowercase();
266 if path.contains("hook") {
267 return false; }
269 let tokenish = |seg: &str| {
271 seg.len() >= 24
272 && seg
273 .chars()
274 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
275 && seg.chars().any(|c| c.is_ascii_digit())
276 && seg.chars().any(|c| c.is_ascii_alphabetic())
277 };
278 if path.split('/').any(tokenish) {
279 return false;
280 }
281 let bad = [
282 "key", "token", "secret", "pass", "pwd", "sig", "auth", "code", "session",
283 ];
284 query
285 .split(['&', ';'])
286 .filter_map(|kv| kv.split('=').next())
287 .all(|k| {
288 let k = k.to_ascii_lowercase();
289 !bad.iter().any(|b| k.contains(b))
290 })
291}
292
293fn is_prose(v: &str) -> bool {
295 v.contains(' ')
296 && !v.contains('=')
297 && !v.split_whitespace().any(|w| {
298 w.len() >= 16
299 && w.chars().any(|c| c.is_ascii_digit())
300 && w.chars().any(|c| c.is_ascii_alphabetic())
301 })
302}
303
304fn is_public(name: &str, kind: &str, value: &str, public_keys: &HashSet<String>) -> bool {
308 if secretish_name(name) {
309 return false;
310 }
311 match kind {
312 "hex_int" | "bool" | "float" => true,
313 "int" => value.trim_start_matches(['-', '+']).len() <= 6,
314 "url" => url_is_public(value),
315 "markdown_link" => value
316 .split_once("](")
317 .map(|(_, t)| t.trim_end_matches(')'))
318 .is_some_and(url_is_public),
319 "template" => {
320 let mut rest = value.replace("{{", "").replace("}}", "");
322 let mut refs: Vec<String> = Vec::new();
323 while let Some(i) = rest.find('{') {
324 let Some(j) = rest[i..].find('}') else {
325 return false;
326 };
327 refs.push(rest[i + 1..i + j].to_string());
328 rest.replace_range(i..=i + j, "");
329 }
330 refs.iter().all(|r| public_keys.contains(r))
331 && (!rest.contains("://")
332 || url_is_public(&rest.replace(' ', ""))
333 || is_prose(&rest))
334 }
335 "string" => {
336 let t = value.trim();
337 if t.chars().count() <= 2 {
338 return true;
339 }
340 if t.starts_with('<') && t.ends_with('>') && t.contains("://") {
341 return url_is_public(t);
342 }
343 is_prose(t)
344 }
345 _ => false,
346 }
347}
348
349pub fn import_python_config(text: &str) -> BundleImport {
350 let mut vars: Vec<ImportedVar> = Vec::new();
351 let mut warnings: Vec<String> = Vec::new();
352 let mut bound: HashMap<String, String> = HashMap::new();
353 let mut taken: HashSet<String> = HashSet::new();
354 let mut rewrites: Vec<(String, String, usize)> = Vec::new();
355 let mut public_keys: HashSet<String> = HashSet::new();
356
357 for (index, raw) in text.lines().enumerate() {
358 let line_no = index + 1;
359 let line = raw.trim();
360 let Some(eq) = line.find('=') else { continue };
361 let name = line[..eq].trim_end();
362 if !is_ident(name) || line[eq + 1..].starts_with('=') {
363 continue;
364 }
365 let source_full = line[eq + 1..].trim_start();
366 let source = strip_comment(source_full).trim();
367
368 let (value, kind, extra): (String, &str, Option<String>);
369 let mut unread = false;
373 let quoted = read_quoted(source).filter(|(_, _, rest)| {
374 let r = rest.trim();
375 r.is_empty() || r.starts_with('#')
376 });
377 if let Some((prefix, body, _)) = quoted {
378 let is_f = prefix.contains('f');
379 match unescape_py(&body, prefix.contains('r')) {
380 None => {
381 warnings.push(format!(
382 "line {line_no}: unsupported escape in {name}; imported as source text"
383 ));
384 value = source.to_string();
385 kind = "string";
386 extra = None;
387 unread = true;
388 }
389 Some(body) if is_f => match convert_fstring(&body, &bound) {
390 None => {
391 warnings.push(format!(
392 "line {line_no}: {name} is an f-string with an expression a template cannot hold; imported as a string"
393 ));
394 value = body;
395 kind = "string";
396 extra = None;
397 unread = true;
398 }
399 Some((text, rewrote)) => {
400 for (from, to) in rewrote {
401 match rewrites.iter_mut().find(|r| r.0 == from) {
402 Some(r) => {
403 r.1 = to;
404 r.2 += 1;
405 }
406 None => rewrites.push((from, to, 1)),
407 }
408 }
409 kind = if text.contains(['{', '}']) {
412 "template"
413 } else {
414 kind_for_string(name, &text)
415 };
416 value = text;
417 extra = None;
418 }
419 },
420 Some(body) => {
421 kind = kind_for_string(name, &body);
422 value = body;
423 extra = None;
424 }
425 }
426 } else if is_radix_int(source) {
427 value = source.to_string();
428 kind = "hex_int";
429 extra = None;
430 } else if all_digits(signed(source)) {
431 value = source.to_string();
432 kind = "int";
433 extra = None;
434 } else if is_float(source) {
435 value = source.to_string();
436 kind = "float";
437 extra = None;
438 } else if source == "True" || source == "False" {
439 value = (source == "True").to_string();
440 kind = "bool";
441 extra = None;
442 } else if source == "None" {
443 value = String::new();
444 kind = "string";
445 extra = Some(format!("{name} is None; imported as an empty string"));
446 } else {
447 value = source.to_string();
448 kind = "string";
449 extra = Some(format!(
450 "{name} is not a supported literal; imported as source text"
451 ));
452 unread = true;
453 }
454 if let Some(w) = extra {
455 warnings.push(format!("line {line_no}: {w}"));
456 }
457
458 let mut key = name.to_string();
459 if taken.contains(name) {
460 let mut n = 2;
461 while taken.contains(&format!("{name}_{n}")) {
462 n += 1;
463 }
464 key = format!("{name}_{n}");
465 warnings.push(format!(
466 "line {line_no}: {name} is assigned more than once; the first stays {name}, this one is imported as {key}, and later references use {key}"
467 ));
468 }
469 taken.insert(key.clone());
470 bound.insert(name.to_string(), key.clone());
471 let public = !unread && is_public(name, kind, &value, &public_keys);
472 if public {
473 public_keys.insert(key.clone());
474 }
475 vars.push(ImportedVar {
476 key,
477 value,
478 kind: kind.to_string(),
479 public,
480 });
481 }
482
483 for (from, to, n) in rewrites {
484 warnings.push(format!(
485 "{n} later reference{} to {from} now {} {to}",
486 if n == 1 { "" } else { "s" },
487 if n == 1 { "uses" } else { "use" }
488 ));
489 }
490 BundleImport { vars, warnings }
491}
492
493#[cfg(test)]
494mod tests {
495 use super::*;
496
497 #[test]
498 fn matches_the_golden_files_the_typescript_twin_wrote() {
499 let root = concat!(env!("CARGO_MANIFEST_DIR"), "/../tests/fixtures/parity/");
500 for (src, gold) in [
501 ("bundle-import-synthetic.py", "bundle-import.json"),
502 ("bundle-discord-setup.py", "bundle-discord-setup.json"),
504 ] {
505 let src = std::fs::read_to_string(format!("{root}{src}")).unwrap();
506 let gold: serde_json::Value =
507 serde_json::from_str(&std::fs::read_to_string(format!("{root}{gold}")).unwrap())
508 .unwrap();
509 let got = serde_json::to_value(import_python_config(&src)).unwrap();
510 assert_eq!(got, gold);
511 }
512 }
513
514 #[test]
515 fn large_ids_stay_strings_and_nothing_is_executed() {
516 let r = import_python_config("owner = '708766134927442001'\nx = len(owner)\n");
517 assert_eq!(r.vars[0].kind, "large_id");
518 assert_eq!(r.vars[1].value, "len(owner)");
519 assert!(r.warnings[0].contains("not a supported literal"));
520 }
521}