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
use std::env::current_dir;
use std::fmt;
use std::fs::{create_dir_all, remove_dir_all, rename, File, OpenOptions};
use std::io::{self, Seek as _, SeekFrom, Write};
use std::path::{Path, PathBuf};

use anyhow::{anyhow, Context as _};
use serde::Serialize;

use crate::Result;

#[derive(Serialize, Debug, Clone, PartialEq, Eq, Hash)]
pub struct AbsPathBuf(PathBuf);

impl AbsPathBuf {
    pub fn try_new(path: PathBuf) -> Result<Self> {
        if path.is_absolute() {
            Ok(Self(path))
        } else {
            Err(anyhow!("Path is not absolute : {}", path.display()))
        }
    }

    fn expand<P: AsRef<Path>>(path: P) -> Result<PathBuf> {
        Ok(shellexpand::full(&path.as_ref().to_string_lossy())?.parse()?)
    }

    pub fn cwd() -> Result<Self> {
        Ok(Self(current_dir()?))
    }

    pub fn join_expand<P: AsRef<Path>>(&self, path: P) -> Result<Self> {
        Ok(self.join(Self::expand(path)?))
    }

    pub fn join<P: AsRef<Path>>(&self, path: P) -> Self {
        Self(self.0.join(path.as_ref().components().collect::<PathBuf>()))
    }

    pub fn parent(&self) -> Option<Self> {
        if let Some(parent) = self.0.parent() {
            Some(Self(parent.to_owned()))
        } else {
            None
        }
    }

    pub fn search_dir_contains(&self, file_name: &str) -> Option<Self> {
        for dir in self.0.ancestors() {
            let mut file_path = dir.join(file_name);
            if file_path.is_file() {
                file_path.pop();
                return Some(Self(file_path));
            }
        }
        None
    }

    pub fn save_pretty(
        &self,
        save: impl FnOnce(File) -> Result<()>,
        overwrite: bool,
        base_dir: Option<&AbsPathBuf>,
        cnsl: &mut dyn Write,
    ) -> Result<Option<bool>> {
        write!(
            cnsl,
            "Saving {} ... ",
            self.strip_prefix_if(base_dir).display()
        )?;
        let result = self.save(save, overwrite);
        let msg = match result {
            Ok(Some(true)) => "overwritten",
            Ok(Some(false)) => "saved",
            Ok(None) => "already exists",
            Err(_) => "failed",
        };
        writeln!(cnsl, "{}", msg)?;
        result
    }

    // returns Some(true): overwritten, Some(false): created, None: skipped
    pub fn save(
        &self,
        save: impl FnOnce(File) -> Result<()>,
        overwrite: bool,
    ) -> Result<Option<bool>> {
        let is_existed = self.as_ref().is_file();
        if !overwrite && is_existed {
            return Ok(None);
        }
        self.create_dir_all_and_open(false, true)
            .with_context(|| format!("Could not open file : {}", self))
            .and_then(|mut file| {
                // truncate file before write
                file.seek(SeekFrom::Start(0))?;
                file.set_len(0)?;
                Ok(file)
            })
            .and_then(save)?;
        Ok(Some(is_existed))
    }

    pub fn load_pretty<T>(
        &self,
        load: impl FnOnce(File) -> Result<T>,
        base_dir: Option<&AbsPathBuf>,
        cnsl: &mut dyn Write,
    ) -> Result<T> {
        write!(
            cnsl,
            "Loading {} ... ",
            self.strip_prefix_if(base_dir).display()
        )?;
        let result = self.load(load);
        let msg = match result {
            Ok(_) => "loaded",
            Err(_) => "failed",
        };
        writeln!(cnsl, "{}", msg)?;
        result
    }

    pub fn load<T>(&self, load: impl FnOnce(File) -> Result<T>) -> Result<T> {
        OpenOptions::new()
            .read(true)
            .open(&self.0)
            .with_context(|| format!("Could not open file : {}", self))
            .and_then(load)
    }

    pub fn remove_dir_all_pretty(
        &self,
        base_dir: Option<&AbsPathBuf>,
        cnsl: &mut dyn Write,
    ) -> Result<bool> {
        write!(
            cnsl,
            "Removing {} ... ",
            self.strip_prefix_if(base_dir).display()
        )?;
        let result = self.remove_dir_all();
        let msg = match result {
            Ok(true) => "removed",
            Ok(false) => "not existed",
            Err(_) => "failed",
        };
        writeln!(cnsl, "{}", msg)?;
        result
    }

    fn remove_dir_all(&self) -> Result<bool> {
        if !self.as_ref().exists() {
            return Ok(false);
        }
        remove_dir_all(self.as_ref())?;
        Ok(true)
    }

    pub fn move_from_pretty(
        &self,
        from: &AbsPathBuf,
        base_dir: Option<&AbsPathBuf>,
        cnsl: &mut dyn Write,
    ) -> Result<()> {
        write!(
            cnsl,
            "Moving {} to {} ... ",
            from.strip_prefix_if(base_dir).display(),
            self.strip_prefix_if(base_dir).display()
        )?;
        let result = self.move_from(from);
        let msg = match result {
            Ok(_) => "moved",
            Err(_) => "failed",
        };
        writeln!(cnsl, "{}", msg)?;
        result
    }

    fn move_from(&self, from: &AbsPathBuf) -> Result<()> {
        rename(from.as_ref(), self.as_ref())?;
        Ok(())
    }

    pub fn create_dir_all_and_open(&self, is_read: bool, is_write: bool) -> io::Result<File> {
        if let Some(dir) = self.parent() {
            create_dir_all(dir.as_ref())?;
        }
        self.open(is_read, is_write)
    }

    pub fn create_dir_all(&self) -> io::Result<()> {
        create_dir_all(self.as_ref())
    }

    fn open(&self, is_read: bool, is_write: bool) -> io::Result<File> {
        OpenOptions::new()
            .read(is_read)
            .write(is_write)
            .create(true)
            .open(&self.0)
    }

    pub fn strip_prefix(&self, base: &AbsPathBuf) -> &Path {
        self.0
            .strip_prefix(&base.0)
            .unwrap_or_else(|_| self.0.as_path())
    }

    fn strip_prefix_if(&self, base: Option<&AbsPathBuf>) -> &Path {
        if let Some(base) = base {
            self.strip_prefix(base)
        } else {
            self.0.as_path()
        }
    }
}

impl AsRef<PathBuf> for AbsPathBuf {
    fn as_ref(&self) -> &PathBuf {
        &self.0
    }
}

impl fmt::Display for AbsPathBuf {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.display().fmt(f)
    }
}

pub trait ToAbs {
    fn to_abs_expand(&self, base: &AbsPathBuf) -> Result<AbsPathBuf>;

    fn to_abs(&self, base: &AbsPathBuf) -> AbsPathBuf;
}

impl<T: AsRef<Path>> ToAbs for T {
    fn to_abs_expand(&self, base: &AbsPathBuf) -> Result<AbsPathBuf> {
        base.join_expand(self)
    }

    fn to_abs(&self, base: &AbsPathBuf) -> AbsPathBuf {
        base.join(self)
    }
}