1use std::path::{Path, PathBuf};
5use std::process::Command;
6
7use anyhow::{bail, Context, Result};
8use walkdir::{DirEntry, WalkDir};
9
10#[derive(Debug, Clone, Copy, Eq, PartialEq)]
11pub enum MacroDialect {
12 Html,
13 Xml,
14 Md,
17}
18
19#[derive(Debug, Clone)]
20pub struct MacroInvocation {
21 pub name: String,
22 pub dialect: MacroDialect,
23 pub name_start: usize,
24 pub open_brace: usize,
25 pub body_start: usize,
26 pub body_end: usize,
27 pub close_brace: usize,
28 pub name_line: usize,
29 pub name_column: usize,
30 pub indentation_column: usize,
32 pub body_start_line: usize,
33 pub body_start_column: usize,
34}
35
36impl MacroInvocation {
37 pub fn body<'a>(&self, source: &'a str) -> &'a str {
38 &source[self.body_start..self.body_end]
39 }
40}
41
42#[derive(Debug, Clone, Copy, Eq, PartialEq)]
43pub struct LineColumn {
44 pub line: usize,
45 pub column: usize,
46}
47
48#[derive(Debug)]
49pub struct SourceMap<'a> {
50 source: &'a str,
51 line_starts: Vec<usize>,
52}
53
54impl<'a> SourceMap<'a> {
55 pub fn new(source: &'a str) -> Self {
56 let mut line_starts = vec![0];
57 for (idx, byte) in source.bytes().enumerate() {
58 if byte == b'\n' {
59 line_starts.push(idx + 1);
60 }
61 }
62 Self {
63 source,
64 line_starts,
65 }
66 }
67
68 pub fn line_column(&self, byte: usize) -> LineColumn {
69 let line_idx = match self.line_starts.binary_search(&byte) {
70 Ok(idx) => idx,
71 Err(idx) => idx.saturating_sub(1),
72 };
73 let line_start = self.line_starts[line_idx];
74 let column = self
75 .source
76 .get(line_start..byte)
77 .map(str::chars)
78 .map(Iterator::count)
79 .unwrap_or_else(|| byte.saturating_sub(line_start));
80 LineColumn {
81 line: line_idx + 1,
82 column,
83 }
84 }
85
86 pub fn byte_for_line_column(&self, line: usize, column: usize) -> Option<usize> {
87 if line == 0 {
88 return None;
89 }
90 let line_start = *self.line_starts.get(line - 1)?;
91 let line_end = self
92 .line_starts
93 .get(line)
94 .map(|next_start| next_start.saturating_sub(1))
95 .unwrap_or(self.source.len());
96 let line_source = self.source.get(line_start..line_end)?;
97 if column == 0 {
98 return Some(line_start);
99 }
100 let char_count = line_source.chars().count();
101 if column == char_count {
102 return Some(line_end);
103 }
104 if column > char_count {
105 return None;
106 }
107 line_source
108 .char_indices()
109 .nth(column)
110 .map(|(offset, _)| line_start + offset)
111 }
112
113 pub fn span_snippet(&self, span: proc_macro2::Span) -> Option<&'a str> {
114 let start = span.start();
115 let end = span.end();
116 if start.line == 0 || end.line == 0 {
117 return None;
118 }
119 let start = self.byte_for_line_column(start.line, start.column)?;
120 let end = self.byte_for_line_column(end.line, end.column)?;
121 if start <= end && end <= self.source.len() {
122 Some(&self.source[start..end])
123 } else {
124 None
125 }
126 }
127
128 pub fn source_from_span_start(&self, span: proc_macro2::Span) -> Option<&'a str> {
129 let start = span.start();
130 if start.line == 0 {
131 return None;
132 }
133 let start = self.byte_for_line_column(start.line, start.column)?;
134 self.source.get(start..)
135 }
136}
137
138pub fn file_line_column_for_body_span(
139 inv: &MacroInvocation,
140 span: proc_macro2::Span,
141) -> Option<LineColumn> {
142 let start = span.start();
143 if start.line == 0 {
144 return None;
145 }
146
147 let line = inv.body_start_line + start.line - 1;
148 let column = if start.line == 1 {
149 inv.body_start_column + start.column
150 } else {
151 start.column
152 };
153 Some(LineColumn { line, column })
154}
155
156pub fn find_rust_files(paths: &[PathBuf]) -> Result<Vec<PathBuf>> {
157 let roots = if paths.is_empty() {
158 vec![PathBuf::from(".")]
159 } else {
160 paths.to_vec()
161 };
162
163 let mut files = Vec::new();
164 for root in roots {
165 if root.is_file() {
166 if root.extension().is_some_and(|ext| ext == "rs") {
167 files.push(root);
168 }
169 continue;
170 }
171
172 for entry in WalkDir::new(&root)
173 .into_iter()
174 .filter_entry(is_visible_entry)
175 {
176 let entry = entry.with_context(|| format!("failed to walk {}", root.display()))?;
177 if entry.file_type().is_file()
178 && entry.path().extension().is_some_and(|ext| ext == "rs")
179 && should_scan_path(entry.path())
180 {
181 files.push(entry.path().to_path_buf());
182 }
183 }
184 }
185
186 files.sort();
187 files.dedup();
188 Ok(files)
189}
190
191pub fn find_changed_rust_files(base: Option<&str>, staged: bool) -> Result<Vec<PathBuf>> {
192 let cwd = std::env::current_dir().context("resolve current directory")?;
193 find_changed_rust_files_in(&cwd, base, staged)
194}
195
196fn find_changed_rust_files_in(
197 dir: &Path,
198 base: Option<&str>,
199 staged: bool,
200) -> Result<Vec<PathBuf>> {
201 let toplevel = git_output(dir, &["rev-parse", "--show-toplevel"])?
205 .into_iter()
206 .next()
207 .map(PathBuf::from)
208 .context("git did not report a repository root")?;
209
210 let mut names = if staged {
211 git_output(
212 dir,
213 &[
214 "diff",
215 "--cached",
216 "--name-only",
217 "--diff-filter=ACMRTUXB",
218 "--",
219 "*.rs",
220 ],
221 )?
222 } else {
223 let mut names = git_output(
224 dir,
225 &[
226 "diff",
227 "--name-only",
228 "--diff-filter=ACMRTUXB",
229 base.unwrap_or("HEAD"),
230 "--",
231 "*.rs",
232 ],
233 )?;
234 names.extend(git_output(
235 dir,
236 &[
237 "ls-files",
238 "--others",
239 "--exclude-standard",
240 "--full-name",
241 "--",
242 "*.rs",
243 ],
244 )?);
245 names
246 };
247
248 names.sort();
249 names.dedup();
250
251 let mut files = Vec::new();
252 for name in names {
253 let rel = PathBuf::from(name);
254 let path = toplevel.join(&rel);
255 if path.exists() && should_scan_path(&rel) {
256 files.push(path);
257 }
258 }
259 Ok(files)
260}
261
262fn git_output(dir: &Path, args: &[&str]) -> Result<Vec<String>> {
263 let output = Command::new("git")
264 .args(args)
265 .current_dir(dir)
266 .output()
267 .with_context(|| "failed to run git")?;
268
269 if !output.status.success() {
270 bail!(
271 "`git {}` failed: {}",
272 args.join(" "),
273 String::from_utf8_lossy(&output.stderr).trim()
274 );
275 }
276
277 Ok(String::from_utf8_lossy(&output.stdout)
278 .lines()
279 .filter(|line| !line.is_empty())
280 .map(str::to_owned)
281 .collect())
282}
283
284fn is_visible_entry(entry: &DirEntry) -> bool {
285 if entry.depth() == 0 {
286 return true;
287 }
288 if !entry.file_type().is_dir() {
289 return true;
290 }
291 entry.file_name().to_str().is_some_and(|name| {
292 !name.starts_with('.') && !matches!(name, "target" | "node_modules" | "dist")
293 })
294}
295
296fn should_scan_path(path: &Path) -> bool {
297 if path.extension().is_none_or(|ext| ext != "rs") {
298 return false;
299 }
300 if path.components().any(|component| {
301 matches!(
302 component.as_os_str().to_str(),
303 Some(
304 ".git"
305 | ".claude"
306 | ".codex"
307 | ".worktrees"
308 | ".next"
309 | "target"
310 | "node_modules"
311 | "dist"
312 )
313 )
314 }) {
315 return false;
316 }
317 !is_generator_owned_golden(path) && !is_compile_fail_fixture(path)
318}
319
320fn is_generator_owned_golden(path: &Path) -> bool {
321 path.file_name()
322 .and_then(|name| name.to_str())
323 .is_some_and(|name| name.ends_with(".golden.rs"))
324 && path
325 .parent()
326 .and_then(Path::file_name)
327 .and_then(|name| name.to_str())
328 == Some("golden")
329 && path
330 .parent()
331 .and_then(Path::parent)
332 .and_then(Path::file_name)
333 .and_then(|name| name.to_str())
334 == Some("rsjs_macros")
335}
336
337fn is_compile_fail_fixture(path: &Path) -> bool {
338 let mut under_ui_tests = false;
339 let mut saw_tests = false;
340 for component in path
341 .components()
342 .filter_map(|component| component.as_os_str().to_str())
343 {
344 if component == "tests" {
345 saw_tests = true;
346 continue;
347 }
348 if saw_tests && component == "ui" {
349 under_ui_tests = true;
350 continue;
351 }
352 if under_ui_tests && component == "fail" {
353 return true;
354 }
355 }
356 false
357}
358
359pub fn find_macros(source: &str) -> Vec<MacroInvocation> {
360 let map = SourceMap::new(source);
361 let bytes = source.as_bytes();
362 let mut out = Vec::new();
363 let mut i = 0;
364 let bare_html_is_foreign = bare_html_is_imported_from_yew(source);
365
366 while i < bytes.len() {
367 if let Some(next) = skip_ignored(source, i) {
368 i = next;
369 continue;
370 }
371
372 if is_ident_start(bytes[i]) {
373 let name_start = i;
374 let name_end = parse_ident_end(bytes, i);
375 let name = &source[name_start..name_end];
376
377 if name == "macro_rules" {
378 if let Some(close_delimiter) = macro_rules_close_delimiter(source, name_end) {
379 i = close_delimiter + 1;
380 continue;
381 }
382 }
383
384 if let Some((open_delimiter, close_delimiter)) = macro_open_delimiter(source, name_end)
385 {
386 if let Some(close_delimiter_at) =
387 find_matching_delimiter(source, open_delimiter, close_delimiter)
388 {
389 if let Some(dialect) = macro_dialect(name) {
390 let foreign = qualified_macro_owner(source, name_start)
391 .is_some_and(|owner| owner != "proa_macros")
392 || (name == "html"
393 && qualified_macro_owner(source, name_start).is_none()
394 && bare_html_is_foreign);
395 if foreign || close_delimiter != b'}' {
396 i = close_delimiter_at + 1;
397 continue;
398 }
399
400 let name_pos = map.line_column(name_start);
401 let indentation_column = line_indentation_column(source, name_start);
402 let body_pos = map.line_column(open_delimiter + 1);
403 out.push(MacroInvocation {
404 name: name.to_owned(),
405 dialect,
406 name_start,
407 open_brace: open_delimiter,
408 body_start: open_delimiter + 1,
409 body_end: close_delimiter_at,
410 close_brace: close_delimiter_at,
411 name_line: name_pos.line,
412 name_column: name_pos.column,
413 indentation_column,
414 body_start_line: body_pos.line,
415 body_start_column: body_pos.column,
416 });
417 i = close_delimiter_at + 1;
418 continue;
419 }
420
421 i = close_delimiter_at + 1;
425 continue;
426 }
427 }
428 i = name_end;
429 continue;
430 }
431
432 i += 1;
433 }
434
435 out
436}
437
438fn macro_rules_close_delimiter(source: &str, after_macro_rules: usize) -> Option<usize> {
439 let bytes = source.as_bytes();
440 let mut cursor = skip_ws(bytes, after_macro_rules);
441 if bytes.get(cursor) != Some(&b'!') {
442 return None;
443 }
444 cursor = skip_ws(bytes, cursor + 1);
445 if !bytes.get(cursor).is_some_and(|byte| is_ident_start(*byte)) {
446 return None;
447 }
448 cursor = parse_ident_end(bytes, cursor);
449 cursor = skip_ws(bytes, cursor);
450 let close = match bytes.get(cursor).copied()? {
451 b'{' => b'}',
452 b'(' => b')',
453 b'[' => b']',
454 _ => return None,
455 };
456 find_matching_delimiter(source, cursor, close)
457}
458
459fn qualified_macro_owner(source: &str, name_start: usize) -> Option<&str> {
460 let prefix = source.get(..name_start)?.trim_end();
461 let before_separator = prefix.strip_suffix("::")?.trim_end();
462 let start = before_separator
463 .char_indices()
464 .rev()
465 .find_map(|(idx, ch)| (!ch.is_alphanumeric() && ch != '_').then_some(idx + ch.len_utf8()))
466 .unwrap_or(0);
467 before_separator
468 .get(start..)
469 .filter(|segment| !segment.is_empty())
470}
471
472fn bare_html_is_imported_from_yew(source: &str) -> bool {
473 let compact = compact_code_for_imports(source);
474 let mut yew_html = false;
475 let mut proa_html = false;
476 for statement in compact.split(';') {
477 yew_html |= use_statement_imports(statement, "yew", "html");
478 proa_html |= use_statement_imports(statement, "proa_macros", "html");
479 }
480 yew_html && !proa_html
481}
482
483fn compact_code_for_imports(source: &str) -> String {
484 let mut compact = String::with_capacity(source.len());
485 let mut cursor = 0;
486 while cursor < source.len() {
487 if let Some(next) = skip_ignored(source, cursor) {
488 cursor = next;
489 continue;
490 }
491 let ch = source[cursor..].chars().next().unwrap();
492 if !ch.is_whitespace() {
493 compact.push(ch);
494 }
495 cursor += ch.len_utf8();
496 }
497 compact
498}
499
500fn use_statement_imports(statement: &str, root: &str, target: &str) -> bool {
501 let marker = format!("use{root}::");
502 let Some(imports) = statement
503 .find(&marker)
504 .and_then(|start| statement.get(start + marker.len()..))
505 else {
506 return false;
507 };
508 if imports.contains('*') {
509 return true;
510 }
511
512 let bytes = imports.as_bytes();
513 let mut cursor = 0;
514 while cursor < bytes.len() {
515 if !is_ident_start(bytes[cursor]) {
516 cursor += 1;
517 continue;
518 }
519 let end = parse_ident_end(bytes, cursor);
520 if imports.get(cursor..end) == Some(target) {
521 return true;
522 }
523 cursor = end;
524 }
525 false
526}
527
528fn line_indentation_column(source: &str, byte: usize) -> usize {
529 let line_start = source
530 .get(..byte)
531 .and_then(|prefix| prefix.rfind('\n').map(|idx| idx + 1))
532 .unwrap_or(0);
533 source[line_start..byte]
534 .chars()
535 .take_while(|ch| ch.is_whitespace())
536 .count()
537}
538
539fn macro_dialect(name: &str) -> Option<MacroDialect> {
540 match name {
541 "html" | "html_sync" => Some(MacroDialect::Html),
542 "xml" | "xml_sync" => Some(MacroDialect::Xml),
543 "md" | "md_sync" => Some(MacroDialect::Md),
544 _ => None,
545 }
546}
547
548fn macro_open_delimiter(source: &str, after_name: usize) -> Option<(usize, u8)> {
549 let bytes = source.as_bytes();
550 let mut i = skip_ws(bytes, after_name);
551 if bytes.get(i) != Some(&b'!') {
552 return None;
553 }
554 i = skip_ws(bytes, i + 1);
555 let close_delimiter = match bytes.get(i).copied()? {
556 b'{' => b'}',
557 b'(' => b')',
558 b'[' => b']',
559 _ => return None,
560 };
561 Some((i, close_delimiter))
562}
563
564fn find_matching_delimiter(source: &str, open: usize, close_delimiter: u8) -> Option<usize> {
565 let bytes = source.as_bytes();
566 let open_delimiter = *bytes.get(open)?;
567 let mut depth = 1usize;
568 let mut i = open + 1;
569
570 while i < bytes.len() {
571 if let Some(next) = skip_ignored(source, i) {
572 i = next;
573 continue;
574 }
575
576 match bytes[i] {
577 byte if byte == open_delimiter => depth += 1,
578 byte if byte == close_delimiter => {
579 depth -= 1;
580 if depth == 0 {
581 return Some(i);
582 }
583 }
584 _ => {}
585 }
586 i += 1;
587 }
588
589 None
590}
591
592fn skip_ignored(source: &str, i: usize) -> Option<usize> {
593 let bytes = source.as_bytes();
594 match bytes.get(i).copied()? {
595 b'/' if bytes.get(i + 1) == Some(&b'/') => Some(skip_line_comment(bytes, i + 2)),
596 b'/' if bytes.get(i + 1) == Some(&b'*') => Some(skip_block_comment(bytes, i + 2)),
597 b'"' => Some(skip_string(bytes, i + 1)),
598 b'\'' if looks_like_char_literal(bytes, i) => Some(skip_char(bytes, i + 1)),
599 b'b' if bytes.get(i + 1) == Some(&b'"') => Some(skip_string(bytes, i + 2)),
600 b'r' => skip_raw_string(source, i, 0),
601 b'b' if bytes.get(i + 1) == Some(&b'r') => skip_raw_string(source, i, 1),
602 _ => None,
603 }
604}
605
606fn skip_line_comment(bytes: &[u8], mut i: usize) -> usize {
607 while i < bytes.len() && bytes[i] != b'\n' {
608 i += 1;
609 }
610 i
611}
612
613fn skip_block_comment(bytes: &[u8], mut i: usize) -> usize {
614 let mut depth = 1usize;
615 while i + 1 < bytes.len() {
616 match (bytes[i], bytes[i + 1]) {
617 (b'/', b'*') => {
618 depth += 1;
619 i += 2;
620 }
621 (b'*', b'/') => {
622 depth -= 1;
623 i += 2;
624 if depth == 0 {
625 return i;
626 }
627 }
628 _ => i += 1,
629 }
630 }
631 bytes.len()
632}
633
634fn skip_string(bytes: &[u8], mut i: usize) -> usize {
635 while i < bytes.len() {
636 match bytes[i] {
637 b'\\' => i = (i + 2).min(bytes.len()),
638 b'"' => return i + 1,
639 _ => i += 1,
640 }
641 }
642 bytes.len()
643}
644
645fn skip_raw_string(source: &str, i: usize, prefix_len: usize) -> Option<usize> {
646 let bytes = source.as_bytes();
647 let mut cursor = i + prefix_len + 1;
648 let mut hashes = 0usize;
649 while bytes.get(cursor) == Some(&b'#') {
650 hashes += 1;
651 cursor += 1;
652 }
653 if bytes.get(cursor) != Some(&b'"') {
654 return None;
655 }
656 cursor += 1;
657
658 while cursor < bytes.len() {
659 if bytes[cursor] == b'"' {
660 let end = cursor + 1 + hashes;
661 if end <= bytes.len() && bytes[cursor + 1..end].iter().all(|b| *b == b'#') {
662 return Some(end);
663 }
664 }
665 cursor += 1;
666 }
667
668 Some(bytes.len())
669}
670
671pub(crate) fn looks_like_char_literal(bytes: &[u8], i: usize) -> bool {
672 let Some(next) = bytes.get(i + 1).copied() else {
673 return false;
674 };
675 if is_ident_start(next) {
676 let ident_end = parse_ident_end(bytes, i + 1);
677 return bytes.get(ident_end) == Some(&b'\'');
678 }
679 true
680}
681
682pub(crate) fn skip_char(bytes: &[u8], mut i: usize) -> usize {
683 while i < bytes.len() {
684 match bytes[i] {
685 b'\\' => i = (i + 2).min(bytes.len()),
686 b'\'' => return i + 1,
687 _ => i += 1,
688 }
689 }
690 bytes.len()
691}
692
693fn skip_ws(bytes: &[u8], mut i: usize) -> usize {
694 while i < bytes.len() && bytes[i].is_ascii_whitespace() {
695 i += 1;
696 }
697 i
698}
699
700fn parse_ident_end(bytes: &[u8], mut i: usize) -> usize {
701 i += 1;
702 while i < bytes.len() && is_ident_continue(bytes[i]) {
703 i += 1;
704 }
705 i
706}
707
708fn is_ident_start(byte: u8) -> bool {
709 byte == b'_' || byte.is_ascii_alphabetic()
710}
711
712fn is_ident_continue(byte: u8) -> bool {
713 is_ident_start(byte) || byte.is_ascii_digit()
714}
715
716pub fn display_path(path: &Path) -> PathBuf {
717 let Ok(cwd) = std::env::current_dir() else {
718 return path.to_path_buf();
719 };
720 pathdiff::diff_paths(path, cwd).unwrap_or_else(|| path.to_path_buf())
721}
722
723#[cfg(test)]
724mod tests {
725 use super::*;
726 use std::str::FromStr;
727 use syn::spanned::Spanned;
728
729 #[test]
730 fn finds_supported_macros_and_ignores_strings_and_comments() {
731 let source = r#"
732 let ignored = "html_sync! { <div></div> }";
733 // html! { <div></div> }
734 proa_macros::html_sync! { <div>{name}</div> }
735 xml! { <svg:path /> }
736 let generated = quote! {
737 ::proa_macros::html_sync! {
738 < #tag #attr=#value >
739 #(#children)*
740 </ #tag >
741 }
742 };
743 "#;
744
745 let macros = find_macros(source);
746 assert_eq!(macros.len(), 2);
747 assert_eq!(macros[0].name, "html_sync");
748 assert_eq!(macros[0].dialect, MacroDialect::Html);
749 assert_eq!(macros[0].name_column, 25);
750 assert_eq!(macros[0].indentation_column, 12);
751 assert_eq!(macros[1].name, "xml");
752 assert_eq!(macros[1].dialect, MacroDialect::Xml);
753 }
754
755 #[test]
756 fn ignores_foreign_and_macro_generated_html_invocations() {
757 let source = r#"
758 use yew::prelude::*;
759
760 macro_rules! generated {
761 ($child:ident) => {
762 html_sync! { <div>{$child}</div> }
763 };
764 }
765
766 seq_macro::seq!(N in 0..3 {
767 html_sync! {
768 #(<span>{N}</span>)*
769 }
770 });
771
772 fn yew_view() -> Html {
773 html! {
774 <main>{ for items }</main>
775 }
776 }
777
778 fn proa_view() {
779 proa_macros::html_sync! { <main>"Proa"</main> }
780 }
781 "#;
782
783 let macros = find_macros(source);
784 assert_eq!(macros.len(), 1, "{macros:#?}");
785 assert_eq!(macros[0].name, "html_sync");
786 assert!(macros[0].body(source).contains("\"Proa\""));
787 }
788
789 #[test]
790 fn explicit_proa_html_import_wins_over_yew_glob() {
791 let source = r#"
792 use proa_macros::html;
793 use yew::prelude::*;
794
795 fn view() {
796 html! { <main>"Proa"</main> }
797 }
798 "#;
799
800 let macros = find_macros(source);
801 assert_eq!(macros.len(), 1, "{macros:#?}");
802 assert_eq!(macros[0].name, "html");
803 }
804
805 #[test]
806 fn ignores_qualified_foreign_html_macro() {
807 let source = r#"
808 fn view() {
809 yew::html! { <main>{ for items }</main> }
810 ::proa_macros::html_sync! { <main>"Proa"</main> }
811 }
812 "#;
813
814 let macros = find_macros(source);
815 assert_eq!(macros.len(), 1, "{macros:#?}");
816 assert_eq!(macros[0].name, "html_sync");
817 }
818
819 #[test]
820 fn source_map_columns_are_utf8_safe() {
821 let source = "let label = \"Rust→Zig\";\nhtml_sync! { <div>{self.title}</div> }\n";
822 let map = SourceMap::new(source);
823 let byte = source.find("Zig").unwrap();
824 let pos = map.line_column(byte);
825 assert_eq!(map.byte_for_line_column(pos.line, pos.column), Some(byte));
826
827 let body = r#"<div title="Rust→Zig" data-label={self.title}></div>"#;
828 let tokens = proc_macro2::TokenStream::from_str(body).unwrap();
829 let root = syn::parse2::<proa_dsl::parse::HtmlRoot>(tokens).unwrap();
830 let proa_dsl::parse::Node::Element(element) = &root.nodes[0] else {
831 panic!("expected element");
832 };
833 let proa_dsl::parse::Attribute::Dynamic { value, .. } = &element.attrs[1] else {
834 panic!("expected dynamic attr");
835 };
836 assert_eq!(
837 SourceMap::new(body).span_snippet(value.span()),
838 Some("self.title")
839 );
840 }
841
842 #[test]
843 fn finds_rs_files_under_visible_directories() {
844 let temp = tempfile::tempdir().unwrap();
845 let src = temp.path().join("src");
846 std::fs::create_dir(&src).unwrap();
847 std::fs::write(src.join("lib.rs"), "").unwrap();
848 std::fs::create_dir(temp.path().join("target")).unwrap();
849 std::fs::write(temp.path().join("target").join("ignored.rs"), "").unwrap();
850 let hidden_worktree = temp.path().join(".claude/worktrees/agent/src");
851 std::fs::create_dir_all(&hidden_worktree).unwrap();
852 std::fs::write(hidden_worktree.join("ignored.rs"), "").unwrap();
853
854 let files = find_rust_files(&[temp.path().to_path_buf()]).unwrap();
855 assert_eq!(files, vec![src.join("lib.rs")]);
856
857 let hidden = hidden_worktree.join("ignored.rs");
858 let files = find_rust_files(std::slice::from_ref(&hidden)).unwrap();
859 assert_eq!(files, vec![hidden]);
860 }
861
862 #[test]
863 fn directory_discovery_excludes_compile_fail_fixtures_but_explicit_files_are_allowed() {
864 let temp = tempfile::tempdir().unwrap();
865 let fail = temp
866 .path()
867 .join("crate/tests/ui/conformance/fail/broken.rs");
868 let pass = temp.path().join("crate/tests/ui/conformance/pass/valid.rs");
869 std::fs::create_dir_all(fail.parent().unwrap()).unwrap();
870 std::fs::create_dir_all(pass.parent().unwrap()).unwrap();
871 std::fs::write(&fail, "compile_error!(\"expected\");").unwrap();
872 std::fs::write(&pass, "fn valid() {}").unwrap();
873
874 let files = find_rust_files(&[temp.path().to_path_buf()]).unwrap();
875 assert_eq!(files, vec![pass]);
876
877 let files = find_rust_files(std::slice::from_ref(&fail)).unwrap();
878 assert_eq!(files, vec![fail]);
879 }
880
881 #[test]
882 fn directory_discovery_excludes_generator_owned_goldens_but_explicit_files_are_allowed() {
883 let temp = tempfile::tempdir().unwrap();
884 let golden_dir = temp.path().join("rsjs_macros/golden");
885 let other_golden_dir = temp.path().join("other/golden");
886 std::fs::create_dir_all(&golden_dir).unwrap();
887 std::fs::create_dir_all(&other_golden_dir).unwrap();
888
889 let generated = golden_dir.join("counter.golden.rs");
890 let handwritten = golden_dir.join("helpers.rs");
891 let unrelated = other_golden_dir.join("counter.golden.rs");
892 std::fs::write(&generated, "").unwrap();
893 std::fs::write(&handwritten, "").unwrap();
894 std::fs::write(&unrelated, "").unwrap();
895
896 let files = find_rust_files(&[temp.path().to_path_buf()]).unwrap();
897 assert_eq!(files, vec![unrelated, handwritten]);
898
899 let files = find_rust_files(std::slice::from_ref(&generated)).unwrap();
900 assert_eq!(files, vec![generated]);
901 }
902
903 fn git(dir: &Path, args: &[&str]) {
904 let status = Command::new("git")
905 .args(args)
906 .current_dir(dir)
907 .stdout(std::process::Stdio::null())
908 .stderr(std::process::Stdio::null())
909 .status()
910 .unwrap();
911 assert!(status.success(), "git {args:?} failed in {}", dir.display());
912 }
913
914 fn init_repo(dir: &Path) {
915 git(dir, &["init", "-q"]);
916 git(dir, &["config", "user.email", "test@example.com"]);
917 git(dir, &["config", "user.name", "Test"]);
918 }
919
920 #[test]
921 fn changed_files_resolve_against_repo_root_from_subdirectory() {
922 let temp = tempfile::tempdir().unwrap();
923 let root = temp.path().canonicalize().unwrap();
924 init_repo(&root);
925 std::fs::create_dir_all(root.join("crate/src")).unwrap();
926 std::fs::write(root.join("crate/src/lib.rs"), "pub fn a() {}\n").unwrap();
927 git(&root, &["add", "."]);
928 git(&root, &["commit", "-qm", "init"]);
929 std::fs::write(root.join("crate/src/lib.rs"), "pub fn b() {}\n").unwrap();
930
931 let files = find_changed_rust_files_in(&root.join("crate"), None, false).unwrap();
933 assert_eq!(files, vec![root.join("crate/src/lib.rs")]);
934 assert!(files[0].exists());
935 }
936
937 #[test]
938 fn changed_files_include_untracked_from_subdirectory() {
939 let temp = tempfile::tempdir().unwrap();
940 let root = temp.path().canonicalize().unwrap();
941 init_repo(&root);
942 std::fs::create_dir_all(root.join("crate/src")).unwrap();
943 std::fs::write(root.join("crate/src/lib.rs"), "pub fn a() {}\n").unwrap();
944 git(&root, &["add", "."]);
945 git(&root, &["commit", "-qm", "init"]);
946 std::fs::write(root.join("crate/src/new.rs"), "pub fn c() {}\n").unwrap();
947
948 let files = find_changed_rust_files_in(&root.join("crate/src"), None, false).unwrap();
949 assert_eq!(files, vec![root.join("crate/src/new.rs")]);
950 }
951
952 #[test]
953 fn changed_files_exclude_generator_owned_goldens() {
954 let temp = tempfile::tempdir().unwrap();
955 let root = temp.path().canonicalize().unwrap();
956 init_repo(&root);
957 std::fs::create_dir_all(root.join("rsjs_macros/golden")).unwrap();
958 std::fs::create_dir_all(root.join("rsjs_macros/src")).unwrap();
959 std::fs::write(
960 root.join("rsjs_macros/golden/counter.golden.rs"),
961 "generated v1\n",
962 )
963 .unwrap();
964 std::fs::write(root.join("rsjs_macros/src/lib.rs"), "pub fn before() {}\n").unwrap();
965 git(&root, &["add", "."]);
966 git(&root, &["commit", "-qm", "init"]);
967
968 std::fs::write(
969 root.join("rsjs_macros/golden/counter.golden.rs"),
970 "generated v2\n",
971 )
972 .unwrap();
973 std::fs::write(root.join("rsjs_macros/golden/new.golden.rs"), "generated\n").unwrap();
974 std::fs::write(root.join("rsjs_macros/src/lib.rs"), "pub fn after() {}\n").unwrap();
975 std::fs::write(
976 root.join("rsjs_macros/src/new.rs"),
977 "pub fn untracked() {}\n",
978 )
979 .unwrap();
980
981 let files = find_changed_rust_files_in(&root, None, false).unwrap();
982 assert_eq!(
983 files,
984 vec![
985 root.join("rsjs_macros/src/lib.rs"),
986 root.join("rsjs_macros/src/new.rs"),
987 ]
988 );
989 }
990
991 #[test]
992 fn changed_files_staged_selection() {
993 let temp = tempfile::tempdir().unwrap();
994 let root = temp.path().canonicalize().unwrap();
995 init_repo(&root);
996 std::fs::write(root.join("a.rs"), "pub fn a() {}\n").unwrap();
997 git(&root, &["add", "."]);
998 git(&root, &["commit", "-qm", "init"]);
999 std::fs::write(root.join("a.rs"), "pub fn b() {}\n").unwrap();
1000 std::fs::write(root.join("b.rs"), "pub fn c() {}\n").unwrap();
1001 git(&root, &["add", "a.rs"]);
1002
1003 let files = find_changed_rust_files_in(&root, None, true).unwrap();
1004 assert_eq!(files, vec![root.join("a.rs")]);
1005 }
1006
1007 #[test]
1008 fn changed_files_bad_base_ref_errors_instead_of_reporting_clean() {
1009 let temp = tempfile::tempdir().unwrap();
1010 let root = temp.path().canonicalize().unwrap();
1011 init_repo(&root);
1012 std::fs::write(root.join("a.rs"), "pub fn a() {}\n").unwrap();
1013 git(&root, &["add", "."]);
1014 git(&root, &["commit", "-qm", "init"]);
1015
1016 let error = find_changed_rust_files_in(&root, Some("no-such-ref"), false).unwrap_err();
1017 assert!(error.to_string().contains("git diff"), "{error}");
1018 }
1019
1020 #[test]
1021 fn changed_files_outside_repo_errors_instead_of_reporting_clean() {
1022 let temp = tempfile::tempdir().unwrap();
1023 let root = temp.path().canonicalize().unwrap();
1024 let error = find_changed_rust_files_in(&root, None, false).unwrap_err();
1025 assert!(error.to_string().contains("git"), "{error}");
1026 }
1027}