Skip to main content

ctranslate2_src_build_support/
windows_crt_patch.rs

1use std::fs;
2use std::io;
3use std::path::Path;
4
5fn conditional_replace(content: &str, target_flag: &str) -> String {
6    let mut result = String::new();
7    let mut prev_line = "";
8
9    for line in content.lines() {
10        let mut new_line = line.to_string();
11        if prev_line.contains("else()") {
12            if line.contains("/MT") {
13                new_line = line.replace("/MT", target_flag);
14            } else if line.contains("/MD") {
15                new_line = line.replace("/MD", target_flag);
16            }
17        }
18        result.push_str(&new_line);
19        result.push('\n');
20        prev_line = line;
21    }
22
23    result
24}
25
26pub fn patch_cmake_runtime_flags<P: AsRef<Path>>(path: P, use_md: bool) -> io::Result<()> {
27    let path = path.as_ref();
28    let content = fs::read_to_string(path)?;
29
30    let target_flag = if use_md { "/MD" } else { "/MT" };
31    let multi_threaded_target = if use_md {
32        "\"MultiThreaded$<$<CONFIG:Debug>:Debug>DLL\""
33    } else {
34        "\"MultiThreaded$<$<CONFIG:Debug>:Debug>\""
35    };
36    let mut new_content = conditional_replace(&content, target_flag);
37
38    new_content = new_content.replace(
39        "\"MultiThreaded$<$<CONFIG:Debug>:Debug>DLL\"",
40        multi_threaded_target,
41    );
42    new_content = new_content.replace(
43        "\"MultiThreaded$<$<CONFIG:Debug>:Debug>\"",
44        multi_threaded_target,
45    );
46
47    if new_content != content {
48        fs::write(path, new_content)?;
49    }
50
51    Ok(())
52}