summaryrefslogtreecommitdiffstats
path: root/src/common/utils.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/common/utils.rs')
-rw-r--r--src/common/utils.rs62
1 files changed, 61 insertions, 1 deletions
diff --git a/src/common/utils.rs b/src/common/utils.rs
index 8e2ce7d..5b81871 100644
--- a/src/common/utils.rs
+++ b/src/common/utils.rs
@@ -58,7 +58,8 @@ pub fn disk_space(disks: &[Disk], path: &Path) -> String {
}
/// Print the path on the stdout.
-pub fn print_on_quit(path_string: &str) {
+pub fn print_on_quit<S: std::fmt::Display>(path_string: S) {
+ log_info!("print on quit {path_string}");
println!("{path_string}")
}
@@ -131,6 +132,21 @@ pub fn set_clipboard(content: String) {
let _ = ctx.get_contents();
}
+/// Copy the filename to the clipboard. Only the filename.
+pub fn filename_to_clipboard(path: &std::path::Path) {
+ let Some(filename) = path.file_name() else {
+ return;
+ };
+ let filename = filename.to_string_lossy().to_string();
+ set_clipboard(filename)
+}
+
+/// Copy the filepath to the clipboard. The absolute path.
+pub fn filepath_to_clipboard(path: &std::path::Path) {
+ let path = path.to_string_lossy().to_string();
+ set_clipboard(path)
+}
+
/// Convert a row into a `crate::fm::ContentWindow` index.
/// Just remove the header rows.
pub fn row_to_window_index(row: u16) -> usize {
@@ -227,3 +243,47 @@ where
Ok(false)
}
}
+
+/// Rename a file giving it a new file name.
+/// It uses `std::fs::rename` and `std::fs:create_dir_all` and has same limitations.
+/// If the new name contains intermediate slash (`'/'`) like: `"a/b/d"`,
+/// all intermediate folders will be created in the parent folder of `old_path` if needed.
+///
+/// # Errors
+///
+/// It may fail for the same reasons as [`std::fs::rename`] and [`std::fs::create_dir_all`].
+/// See those for more details.
+pub fn rename<P, Q>(old_path: P, new_name: Q) -> Result<std::path::PathBuf>
+where
+ P: AsRef<std::path::Path>,
+ Q: AsRef<std::path::Path>,
+{
+ let Some(old_parent) = old_path.as_ref().parent() else {
+ return Err(anyhow::anyhow!(
+ "no parent for {old_path}",
+ old_path = old_path.as_ref().display()
+ ));
+ };
+ let new_path = old_parent.join(new_name);
+ let Some(new_parent) = new_path.parent() else {
+ return Err(anyhow::anyhow!(
+ "no parent for {new_path}",
+ new_path = new_path.display()
+ ));
+ };
+
+ log_info!(
+ "renaming: {} -> {}",
+ old_path.as_ref().display(),
+ new_path.display()
+ );
+ log_line!(
+ "renaming: {} -> {}",
+ old_path.as_ref().display(),
+ new_path.display()
+ );
+
+ std::fs::create_dir_all(new_parent)?;
+ std::fs::rename(old_path, &new_path)?;
+ Ok(new_path)
+}