rch-common 1.0.26

Shared types and utilities for Remote Compilation Helper
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
//! Test code change generator for verifying remote compilation.
//!
//! This module provides utilities to create minimal, detectable, reversible
//! code changes that can verify whether remote compilation actually processes
//! the source code.

use anyhow::{Context, Result};
use chrono::Utc;
use std::fs;
use std::path::{Path, PathBuf};
use tracing::{error, info};

use crate::binary_hash::binary_contains_marker;

/// Represents a test modification to source code.
///
/// The change is designed to be:
/// - Minimal: Single file modification
/// - Detectable: Produces a different binary hash
/// - Reversible: Can be applied and reverted cleanly
/// - Deterministic: Same change always produces same result
#[derive(Debug, Clone)]
pub struct TestCodeChange {
    /// Path to the file being modified.
    pub file_path: PathBuf,
    /// Original file content before modification.
    pub original_content: String,
    /// Content with the test change applied.
    pub modified_content: String,
    /// Unique identifier for this change (appears in binary).
    pub change_id: String,
}

impl TestCodeChange {
    /// Create a test change that adds a unique marker constant.
    ///
    /// This adds a const string to the specified file that will be compiled
    /// into the binary, allowing verification that compilation actually occurred.
    ///
    /// # Arguments
    /// * `file_path` - Path to the source file to modify
    ///
    /// # Example
    /// ```no_run
    /// use std::path::Path;
    /// use rch_common::test_change::TestCodeChange;
    ///
    /// let change = TestCodeChange::for_file(Path::new("src/main.rs")).unwrap();
    /// println!("Change ID: {}", change.change_id);
    /// ```
    pub fn for_file(file_path: &Path) -> Result<Self> {
        let original = fs::read_to_string(file_path)
            .with_context(|| format!("Failed to read source file: {:?}", file_path))?;

        // Generate a unique change ID based on timestamp
        let change_id = format!("RCH_TEST_{}", Utc::now().timestamp_millis());

        // Modify: prefer modifying main function to prevent LTO elimination
        let modified = if original.contains("println!(\"Hello, world!\");") {
            original.replace(
                "println!(\"Hello, world!\");",
                &format!("println!(\"Hello, world! {}\");", change_id),
            )
        } else if original.contains("println!(\"Hello from test project!\");") {
            original.replace(
                "println!(\"Hello from test project!\");",
                &format!("println!(\"Hello from test project! {}\");", change_id),
            )
        } else if original.contains("println!(\"rch self-test\");") {
            original.replace(
                "println!(\"rch self-test\");",
                &format!("println!(\"rch self-test {}\");", change_id),
            )
        } else {
            // Fallback: append a function
            format!(
                "{}\n\n// RCH Self-Test Marker (auto-generated, safe to remove)\n\
                 #[unsafe(no_mangle)]\n\
                 #[allow(dead_code)]\n\
                 pub fn {}() -> &'static str {{ \"{}\" }}\n",
                original, change_id, change_id
            )
        };

        Ok(TestCodeChange {
            file_path: file_path.to_path_buf(),
            original_content: original,
            modified_content: modified,
            change_id,
        })
    }

    /// Create a test change for the main.rs file in a project directory.
    ///
    /// # Arguments
    /// * `project_dir` - Path to the Rust project root
    pub fn for_main_rs(project_dir: &Path) -> Result<Self> {
        let file_path = project_dir.join("src/main.rs");
        Self::for_file(&file_path)
    }

    /// Create a test change for lib.rs in a project directory.
    ///
    /// # Arguments
    /// * `project_dir` - Path to the Rust project root
    pub fn for_lib_rs(project_dir: &Path) -> Result<Self> {
        let file_path = project_dir.join("src/lib.rs");
        Self::for_file(&file_path)
    }

    /// Apply the test change to the file.
    ///
    /// This writes the modified content to the file path.
    pub fn apply(&self) -> Result<()> {
        info!(
            "Applying test change {} to {:?}",
            self.change_id, self.file_path
        );
        fs::write(&self.file_path, &self.modified_content)
            .with_context(|| format!("Failed to write modified content to {:?}", self.file_path))?;
        Ok(())
    }

    /// Revert the test change, restoring original content.
    pub fn revert(&self) -> Result<()> {
        info!(
            "Reverting test change {} from {:?}",
            self.change_id, self.file_path
        );
        fs::write(&self.file_path, &self.original_content).with_context(|| {
            format!("Failed to restore original content to {:?}", self.file_path)
        })?;
        Ok(())
    }

    /// Check if the compiled binary contains the test marker.
    ///
    /// This verifies that the remote compilation actually processed our change.
    ///
    /// # Arguments
    /// * `binary_path` - Path to the compiled binary
    ///
    /// # Returns
    /// `true` if the marker is found in the binary
    pub fn verify_in_binary(&self, binary_path: &Path) -> Result<bool> {
        binary_contains_marker(binary_path, &self.change_id)
    }
}

/// RAII guard for test changes that auto-reverts on drop.
///
/// This ensures that test changes are always cleaned up, even if the test
/// panics or returns early.
///
/// # Example
/// ```no_run
/// use std::path::Path;
/// use rch_common::test_change::{TestCodeChange, TestChangeGuard};
///
/// fn run_test() -> anyhow::Result<()> {
///     let change = TestCodeChange::for_main_rs(Path::new("/my/project"))?;
///     let guard = TestChangeGuard::new(change)?;
///     
///     // Do compilation and testing here...
///     // File will be automatically reverted when guard goes out of scope
///     
///     Ok(())
/// }
/// ```
pub struct TestChangeGuard {
    change: TestCodeChange,
    applied: bool,
}

impl TestChangeGuard {
    /// Create a new guard and apply the test change.
    ///
    /// The change is applied immediately upon creation.
    pub fn new(change: TestCodeChange) -> Result<Self> {
        let mut guard = Self {
            change,
            applied: false,
        };
        guard.change.apply()?;
        guard.applied = true;
        Ok(guard)
    }

    /// Get the change ID for this test modification.
    pub fn change_id(&self) -> &str {
        &self.change.change_id
    }

    /// Get the path to the modified file.
    pub fn file_path(&self) -> &Path {
        &self.change.file_path
    }

    /// Check if the compiled binary contains the test marker.
    pub fn verify_in_binary(&self, binary_path: &Path) -> Result<bool> {
        self.change.verify_in_binary(binary_path)
    }

    /// Manually revert the change without dropping the guard.
    ///
    /// After calling this, the guard will not revert again on drop.
    pub fn revert(mut self) -> Result<()> {
        if self.applied {
            self.change.revert()?;
            self.applied = false;
        }
        Ok(())
    }
}

impl Drop for TestChangeGuard {
    fn drop(&mut self) {
        if self.applied
            && let Err(e) = self.change.revert()
        {
            error!("Failed to revert test change: {}", e);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn init_test_logging() {
        let _ = tracing_subscriber::fmt()
            .with_test_writer()
            .with_max_level(tracing::Level::INFO)
            .try_init();
    }

    #[test]
    fn test_create_test_change() {
        init_test_logging();
        info!("TEST START: test_create_test_change");

        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.rs");
        let original_content = "fn main() {\n    println!(\"Hello\");\n}\n";
        fs::write(&file_path, original_content).unwrap();

        info!("INPUT: TestCodeChange::for_file({:?})", file_path);

        let change = TestCodeChange::for_file(&file_path).unwrap();

        info!("RESULT: change_id={}", change.change_id);
        info!(
            "RESULT: modified_content_len={}",
            change.modified_content.len()
        );

        assert!(change.change_id.starts_with("RCH_TEST_"));
        assert!(change.modified_content.contains(&change.change_id));
        assert!(change.modified_content.contains("// RCH Self-Test Marker"));
        assert_eq!(change.original_content, original_content);

        info!("VERIFY: Test change created successfully");
        info!("TEST PASS: test_create_test_change");
    }

    #[test]
    fn test_apply_and_revert() {
        init_test_logging();
        info!("TEST START: test_apply_and_revert");

        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.rs");
        let original_content = "fn main() {}\n";
        fs::write(&file_path, original_content).unwrap();

        let change = TestCodeChange::for_file(&file_path).unwrap();

        info!("INPUT: apply then revert test change");

        // Apply the change
        change.apply().unwrap();
        let after_apply = fs::read_to_string(&file_path).unwrap();
        info!(
            "AFTER APPLY: contains_marker={}",
            after_apply.contains(&change.change_id)
        );
        assert!(after_apply.contains(&change.change_id));

        // Revert the change
        change.revert().unwrap();
        let after_revert = fs::read_to_string(&file_path).unwrap();
        info!(
            "AFTER REVERT: equals_original={}",
            after_revert == original_content
        );
        assert_eq!(after_revert, original_content);

        info!("VERIFY: Apply and revert work correctly");
        info!("TEST PASS: test_apply_and_revert");
    }

    #[test]
    fn test_guard_auto_reverts() {
        init_test_logging();
        info!("TEST START: test_guard_auto_reverts");

        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.rs");
        let original_content = "fn main() {}\n";
        fs::write(&file_path, original_content).unwrap();

        let change_id: String;
        {
            let change = TestCodeChange::for_file(&file_path).unwrap();
            change_id = change.change_id.clone();
            let _guard = TestChangeGuard::new(change).unwrap();

            // While guard is alive, file should be modified
            let during = fs::read_to_string(&file_path).unwrap();
            info!(
                "DURING GUARD: contains_marker={}",
                during.contains(&change_id)
            );
            assert!(during.contains(&change_id));

            // Guard will be dropped here
        }

        // After guard dropped, file should be reverted
        let after = fs::read_to_string(&file_path).unwrap();
        info!("AFTER DROP: equals_original={}", after == original_content);
        assert_eq!(after, original_content);
        assert!(!after.contains(&change_id));

        info!("VERIFY: Guard auto-reverts on drop");
        info!("TEST PASS: test_guard_auto_reverts");
    }

    #[test]
    fn test_change_id_unique() {
        init_test_logging();
        info!("TEST START: test_change_id_unique");

        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.rs");
        fs::write(&file_path, "fn main() {}\n").unwrap();

        let change1 = TestCodeChange::for_file(&file_path).unwrap();
        // Small delay to ensure different timestamp
        std::thread::sleep(std::time::Duration::from_millis(2));
        let change2 = TestCodeChange::for_file(&file_path).unwrap();

        info!(
            "RESULT: change1_id={}, change2_id={}",
            change1.change_id, change2.change_id
        );

        assert_ne!(change1.change_id, change2.change_id);

        info!("VERIFY: Each change has unique ID");
        info!("TEST PASS: test_change_id_unique");
    }

    #[test]
    fn test_for_main_rs() {
        init_test_logging();
        info!("TEST START: test_for_main_rs");

        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path().join("src");
        fs::create_dir(&src_dir).unwrap();
        let main_rs = src_dir.join("main.rs");
        fs::write(&main_rs, "fn main() {}\n").unwrap();

        info!("INPUT: TestCodeChange::for_main_rs({:?})", temp_dir.path());

        let change = TestCodeChange::for_main_rs(temp_dir.path()).unwrap();

        info!("RESULT: file_path={:?}", change.file_path);

        assert_eq!(change.file_path, main_rs);

        info!("VERIFY: for_main_rs finds correct path");
        info!("TEST PASS: test_for_main_rs");
    }

    #[test]
    fn test_nonexistent_file_error() {
        init_test_logging();
        info!("TEST START: test_nonexistent_file_error");

        let result = TestCodeChange::for_file(Path::new("/nonexistent/file.rs"));

        info!("RESULT: is_err={}", result.is_err());

        assert!(result.is_err());

        info!("VERIFY: Nonexistent file returns error");
        info!("TEST PASS: test_nonexistent_file_error");
    }

    #[test]
    fn test_change_debug() {
        init_test_logging();
        info!("TEST START: test_change_debug");

        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.rs");
        fs::write(&file_path, "fn main() {}\n").unwrap();

        let change = TestCodeChange::for_file(&file_path).unwrap();
        let debug = format!("{:?}", change);

        assert!(debug.contains("TestCodeChange"));
        assert!(debug.contains("RCH_TEST_"));

        info!("TEST PASS: test_change_debug");
    }

    #[test]
    fn test_change_clone() {
        init_test_logging();
        info!("TEST START: test_change_clone");

        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.rs");
        fs::write(&file_path, "fn main() {}\n").unwrap();

        let change = TestCodeChange::for_file(&file_path).unwrap();
        let cloned = change.clone();

        assert_eq!(change.change_id, cloned.change_id);
        assert_eq!(change.file_path, cloned.file_path);
        assert_eq!(change.original_content, cloned.original_content);
        assert_eq!(change.modified_content, cloned.modified_content);

        info!("TEST PASS: test_change_clone");
    }

    #[test]
    fn test_for_lib_rs() {
        init_test_logging();
        info!("TEST START: test_for_lib_rs");

        let temp_dir = TempDir::new().unwrap();
        let src_dir = temp_dir.path().join("src");
        fs::create_dir(&src_dir).unwrap();
        let lib_rs = src_dir.join("lib.rs");
        fs::write(&lib_rs, "pub fn hello() {}\n").unwrap();

        let change = TestCodeChange::for_lib_rs(temp_dir.path()).unwrap();

        assert_eq!(change.file_path, lib_rs);
        assert!(change.change_id.starts_with("RCH_TEST_"));

        info!("TEST PASS: test_for_lib_rs");
    }

    #[test]
    fn test_for_lib_rs_nonexistent() {
        init_test_logging();
        info!("TEST START: test_for_lib_rs_nonexistent");

        let temp_dir = TempDir::new().unwrap();
        // Don't create src/lib.rs

        let result = TestCodeChange::for_lib_rs(temp_dir.path());
        assert!(result.is_err());

        info!("TEST PASS: test_for_lib_rs_nonexistent");
    }

    #[test]
    fn test_change_with_hello_world_pattern() {
        init_test_logging();
        info!("TEST START: test_change_with_hello_world_pattern");

        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("main.rs");
        let original = r#"fn main() {
    println!("Hello, world!");
}"#;
        fs::write(&file_path, original).unwrap();

        let change = TestCodeChange::for_file(&file_path).unwrap();

        // Should replace in println, not append function
        assert!(change.modified_content.contains("Hello, world!"));
        assert!(change.modified_content.contains(&change.change_id));
        assert!(!change.modified_content.contains("// RCH Self-Test Marker"));

        info!("TEST PASS: test_change_with_hello_world_pattern");
    }

    #[test]
    fn test_change_with_hello_from_test_project_pattern() {
        init_test_logging();
        info!("TEST START: test_change_with_hello_from_test_project_pattern");

        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("main.rs");
        let original = r#"fn main() {
    println!("Hello from test project!");
}"#;
        fs::write(&file_path, original).unwrap();

        let change = TestCodeChange::for_file(&file_path).unwrap();

        // Should replace in println, not append function
        assert!(change.modified_content.contains("Hello from test project!"));
        assert!(change.modified_content.contains(&change.change_id));
        assert!(!change.modified_content.contains("// RCH Self-Test Marker"));

        info!("TEST PASS: test_change_with_hello_from_test_project_pattern");
    }

    #[test]
    fn test_guard_change_id() {
        init_test_logging();
        info!("TEST START: test_guard_change_id");

        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.rs");
        fs::write(&file_path, "fn main() {}\n").unwrap();

        let change = TestCodeChange::for_file(&file_path).unwrap();
        let expected_id = change.change_id.clone();
        let guard = TestChangeGuard::new(change).unwrap();

        assert_eq!(guard.change_id(), expected_id);

        info!("TEST PASS: test_guard_change_id");
    }

    #[test]
    fn test_guard_file_path() {
        init_test_logging();
        info!("TEST START: test_guard_file_path");

        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.rs");
        fs::write(&file_path, "fn main() {}\n").unwrap();

        let change = TestCodeChange::for_file(&file_path).unwrap();
        let guard = TestChangeGuard::new(change).unwrap();

        assert_eq!(guard.file_path(), file_path);

        info!("TEST PASS: test_guard_file_path");
    }

    #[test]
    fn test_guard_manual_revert() {
        init_test_logging();
        info!("TEST START: test_guard_manual_revert");

        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.rs");
        let original_content = "fn main() {}\n";
        fs::write(&file_path, original_content).unwrap();

        let change = TestCodeChange::for_file(&file_path).unwrap();
        let guard = TestChangeGuard::new(change).unwrap();

        // File is modified
        let during = fs::read_to_string(&file_path).unwrap();
        assert!(during.contains("RCH_TEST_"));

        // Manually revert
        guard.revert().unwrap();

        // File is back to original
        let after = fs::read_to_string(&file_path).unwrap();
        assert_eq!(after, original_content);

        info!("TEST PASS: test_guard_manual_revert");
    }

    #[test]
    fn test_change_with_empty_file() {
        init_test_logging();
        info!("TEST START: test_change_with_empty_file");

        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("empty.rs");
        fs::write(&file_path, "").unwrap();

        let change = TestCodeChange::for_file(&file_path).unwrap();

        // Should append marker function
        assert!(change.modified_content.contains("// RCH Self-Test Marker"));
        assert!(change.modified_content.contains(&change.change_id));
        assert!(change.original_content.is_empty());

        info!("TEST PASS: test_change_with_empty_file");
    }

    #[test]
    fn test_multiple_apply_same_change() {
        init_test_logging();
        info!("TEST START: test_multiple_apply_same_change");

        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.rs");
        fs::write(&file_path, "fn main() {}\n").unwrap();

        let change = TestCodeChange::for_file(&file_path).unwrap();

        // Apply twice should work (idempotent write)
        change.apply().unwrap();
        change.apply().unwrap();

        let content = fs::read_to_string(&file_path).unwrap();
        assert!(content.contains(&change.change_id));

        info!("TEST PASS: test_multiple_apply_same_change");
    }

    #[test]
    fn test_apply_revert_apply() {
        init_test_logging();
        info!("TEST START: test_apply_revert_apply");

        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.rs");
        let original = "fn main() {}\n";
        fs::write(&file_path, original).unwrap();

        let change = TestCodeChange::for_file(&file_path).unwrap();

        // Apply
        change.apply().unwrap();
        assert!(
            fs::read_to_string(&file_path)
                .unwrap()
                .contains(&change.change_id)
        );

        // Revert
        change.revert().unwrap();
        assert_eq!(fs::read_to_string(&file_path).unwrap(), original);

        // Apply again
        change.apply().unwrap();
        assert!(
            fs::read_to_string(&file_path)
                .unwrap()
                .contains(&change.change_id)
        );

        info!("TEST PASS: test_apply_revert_apply");
    }

    #[test]
    fn test_guard_preserves_change() {
        init_test_logging();
        info!("TEST START: test_guard_preserves_change");

        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.rs");
        fs::write(&file_path, "fn main() {}\n").unwrap();

        let change = TestCodeChange::for_file(&file_path).unwrap();
        let original_content = change.original_content.clone();
        let modified_content = change.modified_content.clone();

        let guard = TestChangeGuard::new(change).unwrap();

        // Guard should give us the same change_id as the original change
        assert!(modified_content.contains(guard.change_id()));

        drop(guard);

        // After drop, file should be restored to original
        let after = fs::read_to_string(&file_path).unwrap();
        assert_eq!(after, original_content);

        info!("TEST PASS: test_guard_preserves_change");
    }

    #[test]
    fn test_change_id_format() {
        init_test_logging();
        info!("TEST START: test_change_id_format");

        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.rs");
        fs::write(&file_path, "fn main() {}\n").unwrap();

        let change = TestCodeChange::for_file(&file_path).unwrap();

        // Change ID should be RCH_TEST_ followed by a timestamp (number)
        assert!(change.change_id.starts_with("RCH_TEST_"));
        let timestamp_part = &change.change_id["RCH_TEST_".len()..];
        assert!(timestamp_part.parse::<i64>().is_ok());

        info!("TEST PASS: test_change_id_format");
    }
}