Skip to main content

qtbridge_build_utils/
file_system_utils.rs

1// Copyright (C) 2025 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only
3
4use std::env;
5use std::fs;
6use std::path::{self, Path, PathBuf};
7
8pub fn write_to_file(path: &Path, content: &str) -> Result<(), String> {
9    fs::write(path, content)
10        .map_err(|err| format!("Failed to write to file '{}'.\nError: {err}", path.display()))
11}
12
13pub fn write_to_file_if_changed(path: &Path, content: &str) -> Result<(), String> {
14    // Do not overwrite file and do not update its timestamp if contents remain the same.
15    // Used for files with generated code to avoid rebuilding of those files on every build.
16    let mut need_write = true;
17    if path.is_file() {
18        let old_content = read_file_content(path)?;
19        // Compare line by line ignoring line endings.
20        let old_lines = old_content.lines();
21        let new_lines = content.lines();
22        if old_lines.eq(new_lines) {
23            need_write = false;
24        }
25    }
26
27    if need_write {
28        write_to_file(path, content)?
29    }
30
31    Ok(())
32}
33
34pub fn read_file_content(path: &Path) -> Result<String, String> {
35    fs::read_to_string(path)
36        .map_err(|err| format!("Failed to read content of file '{}'.\nError: {err}", path.display()))
37}
38
39pub fn get_manifest_dir() -> Result<PathBuf, String> {
40    Ok(env::var("CARGO_MANIFEST_DIR")
41        .map_err(|err| format!("Failed to get environment variable 'CARGO_MANIFEST_DIR'.\nError:{err}"))?
42        .into())
43}
44
45pub fn get_exe_dir() -> Result<PathBuf, String> {
46     let exe_path = env::current_exe()
47        .map_err(|err| format!("Failed to get the path of the current executable.\nError:{err}"))?;
48    parent_dir(&exe_path)
49}
50
51pub fn get_workspace_dir() -> Result<PathBuf, String> {
52    let start_dir: PathBuf = match get_manifest_dir() {
53        Ok(dir) => dir,
54        Err(_) => std::env::current_dir()
55            .expect("Failed to get current dir")
56    };
57
58    find_file_upwards(&start_dir, "Cargo.lock", 10)
59        .ok_or_else(|| "Failed to find workspace root".to_string())
60        .and_then(|lock_path| parent_dir(&lock_path))
61}
62
63pub fn get_target_dir() -> Result<PathBuf, String> {
64    // Environment variable "CARGO_TARGET_DIR" is not set when running build script.
65    // It is the way to configure cargo from the user side.
66    // So we can't rely on this variable.
67    let path = get_workspace_dir()?.join("target");
68    Ok(path)
69}
70
71pub fn find_file_upwards(start_dir: &Path, filename: &str, max_search_depth: u32) -> Option<PathBuf> {
72    // Start from the given directory
73    let mut cur_dir = start_dir;
74
75    for _level in 0..=max_search_depth {
76        let file_path = cur_dir.join(filename);
77        if file_path.is_file() {
78            return Some(file_path)
79        }
80
81        // Go one level up after the each attempt
82        cur_dir = cur_dir.parent()?;
83    }
84
85    None
86}
87
88pub fn find_files(root: &Path, recursively: bool, predicate: impl Fn(&Path) -> bool) -> Result<Vec<PathBuf>, String> {
89    let mut dir_queue = Vec::from([PathBuf::from(root)]);
90    let mut result = Vec::new();
91
92    while let Some(dir_path) = dir_queue.pop() {
93        let dir_entries = fs::read_dir(&dir_path)
94            .map_err(|err| format!("Failed to get entries of directory '{}'.\nError: {err}", dir_path.display()))?;
95
96        for entry in dir_entries {
97            let entry = entry
98                .map_err(|err| format!("Failed to get directory entry.\nError: {err}"))?;
99            let metadata = entry.metadata()
100                .map_err(|err| format!("Failed to get dir entry metadata.\nError:{err}"))?;
101            let path = entry.path();
102            if metadata.is_file() {
103                if predicate(&path) {
104                    result.push(path);
105                }
106            }
107            else if metadata.is_dir() && recursively {
108                dir_queue.push(path);
109            }
110        }
111    }
112
113    result.sort_unstable();
114
115    Ok(result)
116}
117
118pub fn find_all_files(root: &Path, recursively: bool) -> Result<Vec<PathBuf>, String> {
119    find_files(root, recursively, |_| true)
120}
121
122pub fn find_files_with_extension(dir: &Path, ext: &str) -> Result<Vec<PathBuf>, String> {
123    find_files(dir, true,
124        |path| path.extension().is_some_and(|path_ext| path_ext == ext))
125}
126
127pub fn get_relative_path(input: &Path, base: &Path) -> Result<PathBuf, String> {
128    match input.strip_prefix(base) {
129        Ok(result) => Ok(result.to_path_buf()),
130        Err(_) => {
131            let abs_input = absolute_path(input)?;
132            let abs_base = absolute_path(base)?;
133            abs_input.strip_prefix(abs_base)
134                .map(|path| path.to_path_buf())
135                .map_err(|err| format!("Failed to strip path '{}' from '{}'.\nError: {err}", input.display(), base.display()))
136        }
137    }
138}
139
140pub fn get_path_from(from_dir: &Path, to: &Path) -> Result<PathBuf, String> {
141    let abs_from = absolute_path(from_dir)?;
142    let abs_to = absolute_path(to)?;
143
144    let equal_comps = abs_from.components()
145        .zip(abs_to.components())
146        .take_while(|(lhs, rhs)| lhs == rhs)
147        .count();
148
149    let mut result = PathBuf::from("./");
150    abs_from.components()
151        .skip(equal_comps)
152        .for_each(|_| result.push(".."));
153
154    abs_to.iter()
155        .skip(equal_comps)
156        .for_each(|comp| result.push(comp));
157
158    Ok(result)
159}
160
161pub fn absolute_path(input: &Path) -> Result<PathBuf, String> {
162    let absolute = path::absolute(input)
163        .map_err(|err| format!("Failed to get absolute path from '{}'.\nError: {err}", input.display()))?;
164
165    #[cfg(target_os = "linux")]
166    let absolute = resolve_dots_in_path(&absolute);
167
168    Ok(absolute)
169}
170
171/// Resolve parent directories ("..") and current directory (".") components
172/// in the input path. This is needed because `std::path::absolute()` does not handle that
173/// on POSIX platforms.
174pub fn resolve_dots_in_path(input: &Path) -> PathBuf {
175    let mut comps = Vec::new();
176    let mut changed = false;
177
178    input.components()
179        .for_each(|comp| {
180            let comp_str = comp.as_os_str()
181                .to_string_lossy()
182                .to_string();
183            match comp_str.as_str() {
184                ".." => {
185                    if comps.last().is_some_and(|c| c != "..") {
186                        // Resolve ".." by dropping parent subfolder
187                        comps.pop();
188                        changed = true
189                    }
190                    else {
191                        // No explicit parent subfolder in the path. Keep ".." as is.
192                        comps.push(comp_str);
193                    }
194                },
195                "." => {
196                    if comps.is_empty() {
197                        comps.push(comp_str);
198                    }
199                    else {
200                        // Ignore "." if it is not at the beginning.
201                        changed = true;
202                    }
203                },
204                _ => {
205                    comps.push(comp_str);
206                }
207            }
208        });
209    match changed {
210        true => PathBuf::from_iter(comps),
211        false => PathBuf::from(input),
212    }
213}
214
215/// Return path using '/' as directory separator
216pub fn normalize_dir_separators(input: &Path) -> PathBuf {
217    let str = input
218        .as_os_str()
219        .to_string_lossy()
220        .to_string();
221    str.replace('\\', "/")
222        .into()
223}
224
225pub fn remove_file(path: &Path) -> Result<(), String> {
226    fs::remove_file(path)
227        .map_err(|err| format!("Failed to remove file '{}'.\nError: {err}", path.display()))
228}
229
230pub fn remove_dir_all(path: &Path) -> Result<(), String> {
231    fs::remove_dir_all(path)
232        .map_err(|err| format!("Failed to remove directory '{}'.\nError: {err}", path.display()))
233}
234
235pub fn parent_dir(path: &Path) -> Result<PathBuf, String> {
236    Ok(path.parent()
237        .ok_or_else(|| format!("Failed to get parent dir for {}", path.display()))?
238        .to_path_buf())
239}
240
241pub fn create_dirs(path: &Path) -> Result<(), String> {
242    fs::create_dir_all(path)
243        .map_err(|err| format!("Failed to create output directory '{}': {err}", path.display()))
244}