1use std::collections::HashSet;
4use std::path::Path;
5
6#[derive(Debug, Clone, PartialEq, Eq, Hash)]
7pub enum CheckKey {
8 Make(String),
9 Cargo(String),
10 Go(String),
11 Npm(String),
12 Pnpm(String),
13 Yarn(String),
14 Ruff(String),
15 Tool(String),
16}
17
18impl CheckKey {
19 pub fn key_text(&self) -> String {
20 match self {
21 CheckKey::Make(target) => format!("make {target}"),
22 CheckKey::Cargo(subcmd) => format!("cargo {subcmd}"),
23 CheckKey::Go(subcmd) => format!("go {subcmd}"),
24 CheckKey::Npm(script) => format!("npm run {script}"),
25 CheckKey::Pnpm(script) => format!("pnpm run {script}"),
26 CheckKey::Yarn(script) => format!("yarn {script}"),
27 CheckKey::Ruff(subcmd) => format!("ruff {subcmd}"),
28 CheckKey::Tool(tool) => tool.clone(),
29 }
30 }
31
32 pub fn matches(&self, other: &CheckKey) -> bool {
33 if self == other {
34 return true;
35 }
36 match (self, other) {
37 (CheckKey::Npm(s1), CheckKey::Pnpm(s2))
38 | (CheckKey::Npm(s1), CheckKey::Yarn(s2))
39 | (CheckKey::Pnpm(s1), CheckKey::Npm(s2))
40 | (CheckKey::Pnpm(s1), CheckKey::Yarn(s2))
41 | (CheckKey::Yarn(s1), CheckKey::Npm(s2))
42 | (CheckKey::Yarn(s1), CheckKey::Pnpm(s2)) => s1 == s2,
43 _ => false,
44 }
45 }
46}
47
48pub fn split_pipeline_and_chain(line: &str) -> Vec<String> {
49 let mut parts = Vec::new();
50 let mut current = String::new();
51 let mut in_quote = None;
52 let chars: Vec<char> = line.chars().collect();
53 let mut i = 0;
54
55 while i < chars.len() {
56 let ch = chars[i];
57 match in_quote {
58 Some(q) => {
59 current.push(ch);
60 if ch == q {
61 in_quote = None;
62 }
63 i += 1;
64 }
65 None => {
66 if ch == '"' || ch == '\'' {
67 in_quote = Some(ch);
68 current.push(ch);
69 i += 1;
70 } else if (ch == '&' && i + 1 < chars.len() && chars[i + 1] == '&')
71 || (ch == '|' && i + 1 < chars.len() && chars[i + 1] == '|')
72 {
73 let trimmed = current.trim();
74 if !trimmed.is_empty() {
75 parts.push(trimmed.to_string());
76 }
77 current.clear();
78 i += 2;
79 } else if ch == ';' || ch == '|' {
80 let trimmed = current.trim();
81 if !trimmed.is_empty() {
82 parts.push(trimmed.to_string());
83 }
84 current.clear();
85 i += 1;
86 } else {
87 current.push(ch);
88 i += 1;
89 }
90 }
91 }
92 }
93 let trimmed = current.trim();
94 if !trimmed.is_empty() {
95 parts.push(trimmed.to_string());
96 }
97 parts
98}
99
100fn tokenize_cmd(s: &str) -> Vec<String> {
101 let mut tokens = Vec::new();
102 let mut current = String::new();
103 let mut in_quote = None;
104
105 for ch in s.chars() {
106 match in_quote {
107 Some(q) => {
108 current.push(ch);
109 if ch == q {
110 in_quote = None;
111 }
112 }
113 None => {
114 if ch == '"' || ch == '\'' {
115 in_quote = Some(ch);
116 current.push(ch);
117 } else if ch.is_whitespace() {
118 if !current.is_empty() {
119 tokens.push(current);
120 current = String::new();
121 }
122 } else {
123 current.push(ch);
124 }
125 }
126 }
127 }
128 if !current.is_empty() {
129 tokens.push(current);
130 }
131 tokens
132}
133
134fn unquote(s: &str) -> &str {
135 if (s.starts_with('"') && s.ends_with('"') && s.len() >= 2)
136 || (s.starts_with('\'') && s.ends_with('\'') && s.len() >= 2)
137 {
138 &s[1..s.len() - 1]
139 } else {
140 s
141 }
142}
143
144fn is_env_assignment(s: &str) -> bool {
145 let Some(eq_idx) = s.find('=') else {
146 return false;
147 };
148 if eq_idx == 0 {
149 return false;
150 }
151 let key = &s[..eq_idx];
152 let mut chars = key.chars();
153 let Some(first) = chars.next() else {
154 return false;
155 };
156 if !first.is_ascii_alphabetic() && first != '_' {
157 return false;
158 }
159 chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
160}
161
162fn is_uv_flag_with_arg(flag: &str) -> bool {
163 if flag.contains('=') {
164 return false;
165 }
166 matches!(
167 flag,
168 "--extra"
169 | "-e"
170 | "--package"
171 | "-p"
172 | "--python"
173 | "--directory"
174 | "--project"
175 | "--env-file"
176 | "--with"
177 | "--with-requirements"
178 | "--from"
179 | "--allow-insecure-host"
180 )
181}
182
183fn is_uvx_flag_with_arg(flag: &str) -> bool {
184 if flag.contains('=') {
185 return false;
186 }
187 matches!(
188 flag,
189 "--from" | "--with" | "--python" | "--package" | "-p" | "-e"
190 )
191}
192
193fn is_python_binary(tok: &str) -> bool {
194 if tok == "python" || tok == "python3" {
195 return true;
196 }
197 if let Some(rest) = tok.strip_prefix("python3.") {
198 return rest.chars().all(|c| c.is_ascii_digit());
199 }
200 false
201}
202
203fn unwrap_wrappers(tokens: &[String]) -> &[String] {
204 let mut idx = 0;
205 while idx < tokens.len() {
206 let tok = unquote(&tokens[idx]);
207
208 if is_env_assignment(tok) {
210 idx += 1;
211 continue;
212 }
213
214 if tok == "env" {
216 idx += 1;
217 while idx < tokens.len() {
218 let t = unquote(&tokens[idx]);
219 if t == "-i" || t.starts_with("-u") || is_env_assignment(t) {
220 idx += 1;
221 } else {
222 break;
223 }
224 }
225 continue;
226 }
227
228 if tok == "xargs" {
230 idx += 1;
231 while idx < tokens.len() {
232 let t = unquote(&tokens[idx]);
233 if t.starts_with('-') {
234 if matches!(t, "-I" | "-n" | "-L" | "-s" | "-E" | "-d" | "-a") {
235 idx += 1;
236 if idx < tokens.len() && !unquote(&tokens[idx]).starts_with('-') {
237 idx += 1;
238 }
239 } else {
240 idx += 1;
241 }
242 } else {
243 break;
244 }
245 }
246 continue;
247 }
248
249 if tok == "uv" && idx + 1 < tokens.len() && unquote(&tokens[idx + 1]) == "run" {
251 idx += 2;
252 while idx < tokens.len() {
253 let t = unquote(&tokens[idx]);
254 if t.starts_with('-') {
255 if is_uv_flag_with_arg(t) {
256 idx += 1;
257 if idx < tokens.len() && !unquote(&tokens[idx]).starts_with('-') {
258 idx += 1;
259 }
260 } else {
261 idx += 1;
262 }
263 } else {
264 break;
265 }
266 }
267 continue;
268 }
269
270 if tok == "uvx" {
272 idx += 1;
273 while idx < tokens.len() {
274 let t = unquote(&tokens[idx]);
275 if t.starts_with('-') {
276 if is_uvx_flag_with_arg(t) {
277 idx += 1;
278 if idx < tokens.len() && !unquote(&tokens[idx]).starts_with('-') {
279 idx += 1;
280 }
281 } else {
282 idx += 1;
283 }
284 } else {
285 break;
286 }
287 }
288 continue;
289 }
290
291 if tok == "poetry" && idx + 1 < tokens.len() && unquote(&tokens[idx + 1]) == "run" {
293 idx += 2;
294 while idx < tokens.len() {
295 let t = unquote(&tokens[idx]);
296 if t.starts_with('-') {
297 if matches!(t, "-C" | "--directory") {
298 idx += 1;
299 if idx < tokens.len() && !unquote(&tokens[idx]).starts_with('-') {
300 idx += 1;
301 }
302 } else {
303 idx += 1;
304 }
305 } else {
306 break;
307 }
308 }
309 continue;
310 }
311
312 if tok == "pipenv" && idx + 1 < tokens.len() && unquote(&tokens[idx + 1]) == "run" {
314 idx += 2;
315 while idx < tokens.len() && unquote(&tokens[idx]).starts_with('-') {
316 idx += 1;
317 }
318 continue;
319 }
320
321 if tok == "pdm" && idx + 1 < tokens.len() && unquote(&tokens[idx + 1]) == "run" {
323 idx += 2;
324 while idx < tokens.len() && unquote(&tokens[idx]).starts_with('-') {
325 idx += 1;
326 }
327 continue;
328 }
329
330 if tok == "npx" {
332 idx += 1;
333 while idx < tokens.len() {
334 let t = unquote(&tokens[idx]);
335 if t.starts_with('-') {
336 if matches!(t, "-p" | "--package") {
337 idx += 1;
338 if idx < tokens.len() && !unquote(&tokens[idx]).starts_with('-') {
339 idx += 1;
340 }
341 } else {
342 idx += 1;
343 }
344 } else {
345 break;
346 }
347 }
348 continue;
349 }
350
351 if tok == "pnpm" && idx + 1 < tokens.len() && unquote(&tokens[idx + 1]) == "exec" {
353 idx += 2;
354 while idx < tokens.len() && unquote(&tokens[idx]).starts_with('-') {
355 idx += 1;
356 }
357 continue;
358 }
359
360 if tok == "bunx" {
362 idx += 1;
363 while idx < tokens.len() && unquote(&tokens[idx]).starts_with('-') {
364 idx += 1;
365 }
366 continue;
367 }
368
369 if is_python_binary(tok) {
371 let mut m_idx = idx + 1;
372 while m_idx < tokens.len() {
373 let t = unquote(&tokens[m_idx]);
374 if t == "-m" {
375 break;
376 }
377 if t.starts_with('-') {
378 m_idx += 1;
379 } else {
380 break;
381 }
382 }
383 if m_idx < tokens.len() && unquote(&tokens[m_idx]) == "-m" && m_idx + 1 < tokens.len() {
384 idx = m_idx + 1;
385 continue;
386 }
387 }
388
389 break;
390 }
391 &tokens[idx..]
392}
393
394fn is_pnpm_builtin(s: &str) -> bool {
395 matches!(
396 s,
397 "install"
398 | "i"
399 | "add"
400 | "remove"
401 | "rm"
402 | "update"
403 | "up"
404 | "link"
405 | "unlink"
406 | "import"
407 | "rebuild"
408 | "prune"
409 | "fetch"
410 | "publish"
411 | "pack"
412 | "exec"
413 | "dlx"
414 | "create"
415 | "init"
416 )
417}
418
419fn is_yarn_builtin(s: &str) -> bool {
420 matches!(
421 s,
422 "install"
423 | "add"
424 | "remove"
425 | "upgrade"
426 | "config"
427 | "create"
428 | "cache"
429 | "link"
430 | "unlink"
431 | "publish"
432 | "pack"
433 | "init"
434 | "dlx"
435 | "node"
436 )
437}
438
439fn extract_check_key_from_tokens(tokens: &[String]) -> Option<CheckKey> {
440 if tokens.is_empty() {
441 return None;
442 }
443 let cmd = unquote(&tokens[0]);
444 match cmd {
445 "make" => {
446 let mut i = 1;
447 while i < tokens.len() {
448 let t = unquote(&tokens[i]);
449 if t.starts_with('-') {
450 if (t == "-C" || t == "-f") && i + 1 < tokens.len() {
451 i += 2;
452 } else {
453 i += 1;
454 }
455 } else if is_env_assignment(t) {
456 i += 1;
457 } else {
458 return Some(CheckKey::Make(t.to_string()));
459 }
460 }
461 None
462 }
463 "cargo" => {
464 let mut i = 1;
465 while i < tokens.len() {
466 let t = unquote(&tokens[i]);
467 if t.starts_with('+') || t.starts_with('-') {
468 i += 1;
469 } else {
470 return Some(CheckKey::Cargo(t.to_string()));
471 }
472 }
473 None
474 }
475 "go" => {
476 let mut i = 1;
477 while i < tokens.len() {
478 let t = unquote(&tokens[i]);
479 if t.starts_with('-') {
480 i += 1;
481 } else {
482 return Some(CheckKey::Go(t.to_string()));
483 }
484 }
485 None
486 }
487 "npm" => {
488 let mut i = 1;
489 while i < tokens.len() {
490 let t = unquote(&tokens[i]);
491 if t.starts_with('-') {
492 i += 1;
493 } else if t == "test" || t == "t" {
494 return Some(CheckKey::Npm("test".to_string()));
495 } else if t == "run" || t == "run-script" {
496 i += 1;
497 while i < tokens.len() {
498 let script = unquote(&tokens[i]);
499 if script.starts_with('-') {
500 i += 1;
501 } else {
502 return Some(CheckKey::Npm(script.to_string()));
503 }
504 }
505 return None;
506 } else {
507 return None;
508 }
509 }
510 None
511 }
512 "pnpm" => {
513 let mut i = 1;
514 while i < tokens.len() {
515 let t = unquote(&tokens[i]);
516 if t.starts_with('-') {
517 i += 1;
518 } else if t == "test" || t == "t" {
519 return Some(CheckKey::Pnpm("test".to_string()));
520 } else if t == "run" {
521 i += 1;
522 while i < tokens.len() {
523 let script = unquote(&tokens[i]);
524 if script.starts_with('-') {
525 i += 1;
526 } else {
527 return Some(CheckKey::Pnpm(script.to_string()));
528 }
529 }
530 return None;
531 } else if !is_pnpm_builtin(t) {
532 return Some(CheckKey::Pnpm(t.to_string()));
533 } else {
534 return None;
535 }
536 }
537 None
538 }
539 "yarn" => {
540 let mut i = 1;
541 while i < tokens.len() {
542 let t = unquote(&tokens[i]);
543 if t.starts_with('-') {
544 i += 1;
545 } else if t == "run" {
546 i += 1;
547 while i < tokens.len() {
548 let script = unquote(&tokens[i]);
549 if script.starts_with('-') {
550 i += 1;
551 } else {
552 return Some(CheckKey::Yarn(script.to_string()));
553 }
554 }
555 return None;
556 } else if !is_yarn_builtin(t) {
557 return Some(CheckKey::Yarn(t.to_string()));
558 } else {
559 return None;
560 }
561 }
562 None
563 }
564 "ruff" => {
565 let mut i = 1;
566 while i < tokens.len() {
567 let t = unquote(&tokens[i]);
568 if t.starts_with('-') {
569 i += 1;
570 } else if t == "check" || t == "format" {
571 return Some(CheckKey::Ruff(t.to_string()));
572 } else {
573 return None;
574 }
575 }
576 None
577 }
578 "pytest" | "pre-commit" | "pyright" | "mypy" | "eslint" | "vitest" | "jest" | "tsc"
579 | "tox" | "nox" | "black" | "isort" => Some(CheckKey::Tool(cmd.to_string())),
580 _ => None,
581 }
582}
583
584pub fn extract_check_keys(line: &str) -> Vec<CheckKey> {
585 let mut keys = Vec::new();
586 for part in split_pipeline_and_chain(line) {
587 let tokens = tokenize_cmd(&part);
588 let unwrapped = unwrap_wrappers(&tokens);
589 if let Some(key) = extract_check_key_from_tokens(unwrapped) {
590 keys.push(key);
591 }
592 }
593 keys
594}
595
596fn is_identifier_char(c: char) -> bool {
597 c.is_alphanumeric() || c == '_' || c == '-'
598}
599
600fn contains_word_phrase(haystack: &str, needle: &str) -> bool {
601 let mut start = 0;
602 while let Some(pos) = haystack[start..].find(needle) {
603 let actual_pos = start + pos;
604 let end_pos = actual_pos + needle.len();
605
606 let before_ok = if actual_pos == 0 {
607 true
608 } else {
609 let prev_char = haystack[..actual_pos].chars().next_back().unwrap();
610 !is_identifier_char(prev_char)
611 };
612
613 let after_ok = if end_pos == haystack.len() {
614 true
615 } else {
616 let next_char = haystack[end_pos..].chars().next().unwrap();
617 !is_identifier_char(next_char)
618 };
619
620 if before_ok && after_ok {
621 return true;
622 }
623 start = actual_pos + 1;
624 }
625 false
626}
627
628fn blyte_toml_comment_covers(blyte_toml_content: &str, key: &CheckKey) -> bool {
629 blyte_toml_content.lines().any(|line| {
630 let trimmed = line.trim();
631 let Some(after_hash) = trimmed.strip_prefix('#') else {
632 return false;
633 };
634 let comment = after_hash.trim();
635 if contains_word_phrase(comment, &key.key_text()) {
636 return true;
637 }
638 match key {
639 CheckKey::Npm(s) if s == "test" => contains_word_phrase(comment, "npm test"),
640 CheckKey::Pnpm(s) if s == "test" => {
641 contains_word_phrase(comment, "pnpm test")
642 || contains_word_phrase(comment, "npm test")
643 }
644 CheckKey::Yarn(s) => contains_word_phrase(comment, &format!("yarn run {s}")),
645 _ => false,
646 }
647 })
648}
649
650fn has_python_project_file(root: &Path) -> bool {
651 let files = [
652 "pyproject.toml",
653 "setup.py",
654 "setup.cfg",
655 "tox.ini",
656 "noxfile.py",
657 "pytest.ini",
658 ];
659 files.iter().any(|f| root.join(f).exists())
660}
661
662pub fn is_project_file_missing(root: &Path, key: &CheckKey) -> bool {
663 match key {
664 CheckKey::Cargo(_) => !root.join("Cargo.toml").exists(),
665 CheckKey::Go(_) => !root.join("go.mod").exists(),
666 CheckKey::Npm(_) | CheckKey::Pnpm(_) | CheckKey::Yarn(_) => {
667 !root.join("package.json").exists()
668 }
669 CheckKey::Make(target) => {
670 let makefiles = ["Makefile", "makefile", "GNUmakefile"];
671 for mf in makefiles {
672 let path = root.join(mf);
673 if path.exists() {
674 if let Ok(content) = std::fs::read_to_string(&path) {
675 for line in content.lines() {
676 if line.starts_with('\t') || line.starts_with('#') {
677 continue;
678 }
679 let trimmed = line.trim_start();
680 if let Some(rest) = trimmed.strip_prefix(target.as_str()) {
681 if rest.starts_with(':') || rest.trim_start().starts_with(':') {
682 return false;
683 }
684 }
685 }
686 }
687 }
688 }
689 true
690 }
691 CheckKey::Ruff(_) => !has_python_project_file(root),
692 CheckKey::Tool(tool) => match tool.as_str() {
693 "pre-commit" => {
694 !root.join(".pre-commit-config.yaml").exists()
695 && !root.join(".pre-commit-config.yml").exists()
696 }
697 "eslint" | "vitest" | "jest" | "tsc" => !root.join("package.json").exists(),
698 "pytest" | "pyright" | "mypy" | "tox" | "nox" | "black" | "isort" => {
699 !has_python_project_file(root)
700 }
701 _ => false,
702 },
703 }
704}
705
706pub fn is_ci_step_covered(root: &Path, step: &str, gate: &str, blyte_toml_content: &str) -> bool {
709 let step_keys = extract_check_keys(step);
710 if step_keys.is_empty() {
711 return true;
712 }
713 let gate_keys: Vec<CheckKey> = gate.lines().flat_map(extract_check_keys).collect();
714
715 step_keys.iter().all(|key| {
716 if gate_keys.iter().any(|gk| gk.matches(key)) {
718 return true;
719 }
720 if blyte_toml_comment_covers(blyte_toml_content, key) {
722 return true;
723 }
724 if is_project_file_missing(root, key) {
726 return true;
727 }
728 false
729 })
730}
731
732pub fn missing_ci_steps(root: &Path, gate: &str, blyte_toml_content: &str) -> Vec<String> {
735 let ci_steps = crate::init::drop_overlapping(crate::init::detect_ci(root));
736 if ci_steps.is_empty() {
737 return Vec::new();
738 }
739 let mut seen_keys = HashSet::new();
740 let mut missing = Vec::new();
741
742 for step in ci_steps {
743 if is_ci_step_covered(root, &step, gate, blyte_toml_content) {
744 continue;
745 }
746 let step_keys = extract_check_keys(&step);
747 let mut is_new = false;
748 for key in step_keys {
749 if seen_keys.insert(key) {
750 is_new = true;
751 }
752 }
753 if is_new {
754 missing.push(step);
755 }
756 }
757 missing
758}
759
760pub fn format_gate_drift_warning(missing: &[String]) -> Option<String> {
762 if missing.is_empty() {
763 None
764 } else {
765 Some(format!(
766 "blyte: the gate is missing CI steps: {} (run blyte init --force to refresh blyte.toml)",
767 missing.join(", ")
768 ))
769 }
770}
771
772pub fn left_out_steps(blyte_toml_content: &str) -> Vec<(String, String)> {
775 let mut out = Vec::new();
776 for line in blyte_toml_content.lines() {
777 let trimmed = line.trim();
778 let Some(after_hash) = trimmed.strip_prefix('#') else {
779 continue;
780 };
781 let comment = after_hash.trim();
782
783 if let Some(rest) = comment.strip_prefix("setup") {
784 let rest = rest.trim_start();
785 if let Some(rest) = rest.strip_prefix('=') {
786 let rest = rest.trim_start();
787 if let Some((cmd_part, reason_part)) = rest.split_once("# left out:") {
788 let cmd_part = cmd_part.trim();
789 if cmd_part.starts_with('"') && cmd_part.ends_with('"') && cmd_part.len() >= 2 {
790 let cmd = cmd_part[1..cmd_part.len() - 1]
791 .replace("\\\"", "\"")
792 .replace("\\\\", "\\");
793 let reason = reason_part.trim().to_string();
794 out.push((format!("setup: {cmd}"), reason));
795 continue;
796 }
797 }
798 }
799 }
800
801 if let Some((command, after_from)) = comment.rsplit_once(": from ") {
802 let command = command.trim();
803 if command.is_empty() {
804 continue;
805 }
806 if let Some((file, rest)) = after_from.split_once(", ") {
807 if file.trim().is_empty() {
808 continue;
809 }
810 let rest = rest.trim();
811 if let Some(reason) = rest.strip_prefix("left out: ") {
812 out.push((command.to_string(), reason.trim().to_string()));
813 } else if rest.starts_with("failed on HEAD") {
814 out.push((command.to_string(), "failed on HEAD".to_string()));
815 }
816 }
817 }
818 }
819 out
820}