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
use std::fs::{File, OpenOptions};
use std::path::PathBuf;

use anyhow::{Context, Result};

use duct::cmd;
use tempfile::{NamedTempFile, Builder};

#[cfg(not(windows))]
pub fn command_exists(cmd: &str) -> bool {
    let output = cmd!("which", cmd)
        .read()
        .unwrap_or_else(|_| String::new());

    !output.trim().is_empty()
}

pub fn open_file_with_mode(path: &str) -> Result<File> {
    let mut options = OpenOptions::new();
    options.write(true).create(true);

    let (mode, clean_path) = if let Some(s) = path.strip_prefix('+') {
        (true, s)  // '+' を除いたパスと追記モード
    } else {
        (false, path)  // 通常のパスとトランケートモード
    };

    if mode {
        options.append(true);  // 追記モード
    } else {
        options.truncate(true);  // 切り詰めモード
    }

    let file = options.open(clean_path)
        .with_context(|| format!("Failed to open file: {}", clean_path))?;

    Ok(file)
}

pub fn create_temp_file(tempdir_placeholder: &Option<&str>) -> Result<PathBuf> {
    let temp_file = if let Some(dir) = tempdir_placeholder {
        // 指定されたディレクトリに一時ファイルを作成
        Builder::new().prefix("tempfile").tempfile_in(dir)?
    } else {
        // デフォルトの一時ファイルディレクトリに一時ファイルを作成
        NamedTempFile::new()?
    };

    // 一時ファイルのパスを返す
    Ok(temp_file.path().to_path_buf())
}