summaryrefslogtreecommitdiffstats
path: root/src/common/utils.rs
blob: 5b818719d6605f2192918b63918b1e95c9fa5065 (plain)
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
use std::borrow::Borrow;
use std::fs::metadata;
use std::io::BufRead;
use std::os::unix::fs::MetadataExt;
use std::path::Path;

use anyhow::{Context, Result};
use copypasta::{ClipboardContext, ClipboardProvider};
use rand::Rng;
use sysinfo::{Disk, DiskExt};
use tuikit::term::Term;

use crate::common::{CALC_PDF_PATH, THUMBNAIL_PATH};
use crate::log_info;
use crate::log_line;
use crate::modes::human_size;
use crate::modes::nvim;
use crate::modes::ContentWindow;
use crate::modes::Users;

/// Returns a `Display` instance after `tuikit::term::Term` creation.
pub fn init_term() -> Result<Term> {
    let term: Term<()> = Term::new()?;
    term.enable_mouse_support()?;
    Ok(term)
}

/// Returns the disk owning a path.
/// None if the path can't be found.
///
/// We sort the disks by descending mount point size, then
/// we return the first disk whose mount point match the path.
pub fn disk_used_by_path<'a>(disks: &'a [Disk], path: &Path) -> Option<&'a Disk> {
    let mut disks: Vec<&Disk> = disks.iter().collect();
    disks.sort_by_key(|disk| disk.mount_point().as_os_str().len());
    disks.reverse();
    disks
        .into_iter()
        .find(|&disk| path.starts_with(disk.mount_point()))
}

fn disk_space_used(disk: Option<&Disk>) -> String {
    match disk {
        None => "".to_owned(),
        Some(disk) => human_size(disk.available_space()),
    }
}

/// Returns the disk space of the disk holding this path.
/// We can't be sure what's the disk of a given path, so we have to look
/// if the mount point is a parent of given path.
/// This solution is ugly but... for a lack of a better one...
pub fn disk_space(disks: &[Disk], path: &Path) -> String {
    if path.as_os_str().is_empty() {
        return "".to_owned();
    }
    disk_space_used(disk_used_by_path(disks, path))
}

/// Print the path on the stdout.
pub fn print_on_quit<S: std::fmt::Display>(path_string: S) {
    log_info!("print on quit {path_string}");
    println!("{path_string}")
}

/// Returns the buffered lines from a text file.
pub fn read_lines<P>(
    filename: P,
) -> std::io::Result<std::io::Lines<std::io::BufReader<std::fs::File>>>
where
    P: AsRef<std::path::Path>,
{
    let file = std::fs::File::open(filename)?;
    Ok(std::io::BufReader::new(file).lines())
}

/// Extract a filename from a path reference.
/// May fail if the filename isn't utf-8 compliant.
pub fn filename_from_path(path: &std::path::Path) -> Result<&str> {
    path.file_name()
        .unwrap_or_default()
        .to_str()
        .context("couldn't parse the filename")
}

/// Uid of the current user.
/// Read from `/proc/self`.
/// Should never fail.
pub fn current_uid() -> Result<u32> {
    Ok(metadata("/proc/self").map(|metadata| metadata.uid())?)
}

/// Get the current username as a String.
/// Read from `/proc/self` and then `/etc/passwd` and should never fail.
pub fn current_username() -> Result<String> {
    Users::new()
        .get_user_by_uid(current_uid()?)
        .context("Couldn't read my own name")
        .cloned()
}

/// True iff the command is available in $PATH.
pub fn is_program_in_path<S>(program: S) -> bool
where
    S: Into<String> + std::fmt::Display,
{
    if let Ok(path) = std::env::var("PATH") {
        for p in path.split(':') {
            let p_str = &format!("{p}/{program}");
            if std::path::Path::new(p_str).exists() {
                return true;
            }
        }
    }
    false
}

/// Extract the lines of a string
pub fn extract_lines(content: String) -> Vec<String> {
    content.lines().map(|line| line.to_string()).collect()
}

pub fn set_clipboard(content: String) {
    log_info!("copied to clipboard: {}", content);
    let Ok(mut ctx) = ClipboardContext::new() else {
        return;
    };
    let Ok(_) = ctx.set_contents(content) else {
        return;
    };
    // For some reason, it's not writen if you don't read it back...
    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 {
    row as usize - ContentWindow::HEADER_ROWS
}

/// Convert a string into a valid, expanded and canonicalized path.
/// Doesn't check if the path exists.
pub fn string_to_path(path_string: &str) -> Result<std::path::PathBuf> {
    let expanded_cow_path = shellexpand::tilde(&path_string);
    let expanded_target: &str = expanded_cow_path.borrow();
    Ok(std::fs::canonicalize(expanded_target)?)
}

pub fn args_is_empty(args: &[String]) -> bool {
    args.is_empty() || args[0] == *""
}

/// True if the executable is "sudo"
pub fn is_sudo_command(executable: &str) -> bool {
    matches!(executable, "sudo")
}

/// Open the path in neovim.
pub fn open_in_current_neovim(path: &Path, nvim_server: &str) {
    let command = &format!(
        "<esc>:e {path}<cr><esc>:set number<cr><esc>:close<cr>",
        path = path.display()
    );
    match nvim(nvim_server, command) {
        Ok(()) => log_line!(
            "Opened {path} in neovim at {nvim_server}",
            path = path.display()
        ),
        Err(error) => log_line!(
            "Couldn't open {path} in neovim. Error {error:?}",
            path = path.display()
        ),
    }
}

/// Creates a random string.
/// The string starts with `fm-` and contains 7 random alphanumeric characters.
pub fn random_name() -> String {
    let mut rand_str = String::with_capacity(10);
    rand_str.push_str("fm-");
    rand::thread_rng()
        .sample_iter(&rand::distributions::Alphanumeric)
        .take(7)
        .for_each(|ch| rand_str.push(ch as char));
    rand_str.push_str(".txt");
    rand_str
}

/// Clear the temporary file used by fm for previewing.
pub fn clear_tmp_file() {
    let _ = std::fs::remove_file(THUMBNAIL_PATH);
    let _ = std::fs::remove_file(CALC_PDF_PATH);
}

/// True if the directory is empty,
/// False if it's not.
/// Err if the path doesn't exists or isn't accessible by
/// the user.
pub fn is_dir_empty(path: &std::path::Path) -> Result<bool> {
    Ok(path.read_dir()?.next().is_none())
}

pub fn path_to_string<P>(path: &P) -> String
where
    P: AsRef<std::path::Path>,
{
    path.as_ref().to_string_lossy().into_owned()
}

/// True iff the last modification of given path happened less than `seconds` ago.
/// If the path has a modified time in future (ie. poorly configured iso file) it
/// will log an error and returns false.
pub fn has_last_modification_happened_less_than<P>(path: P, seconds: u64) -> Result<bool>
where
    P: AsRef<std::path::Path>,
{
    let modified = path.as_ref().metadata()?.modified()?;
    if let Ok(elapsed) = modified.elapsed() {
        let need_refresh = elapsed < std::time::Duration::new(seconds, 0);
        Ok(need_refresh)
    } else {
        let dt: chrono::DateTime<chrono::offset::Utc> = modified.into();
        let fmt = dt.format("%Y/%m/%d %T");
        log_info!(
            "Error for {path} modified datetime {fmt} is in future",
            path = path.as_ref().display(),
        );
        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.
///