summaryrefslogtreecommitdiff
path: root/src/util.rs
blob: 1f6952319d159124979765617eaf0f0737418161 (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
use crate::error::SiteError;
use libc::{timespec, utimensat, AT_FDCWD, AT_SYMLINK_NOFOLLOW};
use log::{debug, error, trace};
use std::ffi::CString;
use std::os::unix::ffi::OsStrExt;
use std::path::{Component, Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

pub fn canonicalize(path: &Path) -> Result<PathBuf, SiteError> {
    path.canonicalize()
        .map_err(|e| SiteError::Canonicalize(path.into(), e))
}

pub fn mkdir(path: &Path) -> Result<(), SiteError> {
    debug!("creating directory {}", path.display());
    std::fs::create_dir_all(path).map_err(|e| SiteError::CreateDir(path.into(), e))?;
    Ok(())
}

pub fn copy(src: &Path, dest: &Path) -> Result<(), SiteError> {
    trace!("copying: {} -> {}", src.display(), dest.display());
    std::fs::copy(src, dest).map_err(|e| SiteError::CopyFile(src.into(), dest.into(), e))?;
    let mtime = get_mtime(src)?;
    set_mtime(dest, mtime)?;
    Ok(())
}

pub fn get_mtime(src: &Path) -> Result<SystemTime, SiteError> {
    let metadata = std::fs::metadata(src).map_err(|e| SiteError::FileMetadata(src.into(), e))?;
    let mtime = metadata
        .modified()
        .map_err(|e| SiteError::FileMtime(src.into(), e))?;
    Ok(mtime)
}

pub fn set_mtime(filename: &Path, mtime: SystemTime) -> Result<(), SiteError> {
    let mtime = timespec(mtime)?;
    let times = [mtime, mtime];
    let times: *const timespec = &times[0];

    let pathbuf = filename.to_path_buf();
    let path = path_to_cstring(filename);

    // We have to use unsafe here to be able call the libc functions
    // below.
    unsafe {
        if utimensat(AT_FDCWD, path.as_ptr(), times, AT_SYMLINK_NOFOLLOW) == -1 {
            let error = std::io::Error::last_os_error();
            error!("utimensat failed on {:?}", path);
            return Err(SiteError::Utimensat(pathbuf, error));
        }
    }
    Ok(())
}

pub fn copy_file_from_source(filename: &Path, output: &Path) -> Result<(), SiteError> {
    debug!("copying {} -> {}", filename.display(), output.display());
    if let Some(parent) = output.parent() {
        trace!("parent: {}", parent.display());
        if !parent.exists() {
            trace!("create parent {}", parent.display());
            std::fs::create_dir_all(parent).map_err(|e| SiteError::CreateDir(parent.into(), e))?;
        }
    } else {
        trace!("does not have parent: {}", output.display());
    }
    copy(filename, output)?;

    Ok(())
}

pub fn join_subpath(parent: &Path, sub: &Path) -> PathBuf {
    let sub: PathBuf = sub
        .components()
        .filter(|c| *c != Component::RootDir)
        .collect();
    parent.join(sub)
}

pub fn make_relative_link<P: AsRef<Path>>(page: P, target: P) -> PathBuf {
    let page = page.as_ref();
    let target = target.as_ref().to_path_buf();

    assert!(page.is_absolute());
    assert!(target.is_absolute());

    let mut relative = PathBuf::new();
    let mut page = page;
    loop {
        if let Some(parent) = page.parent() {
            if let Ok(sub) = target.strip_prefix(parent) {
                let sub = sub.to_path_buf();
                return join_subpath(&relative, &sub);
            }
            relative.push("..");
            page = parent;
        } else {
            return join_subpath(&relative, &target);
        }
    }
}

pub fn make_path_relative_to(dir: &Path, path: &Path) -> PathBuf {
    path.strip_prefix(&dir)
        .unwrap_or_else(|_| panic!("remove prefix {} from {}", dir.display(), path.display()))
        .into()
}

pub fn make_path_absolute(path: &Path) -> PathBuf {
    Path::new("/").join(&path)
}

fn timespec(time: SystemTime) -> Result<timespec, SiteError> {
    let dur = time
        .duration_since(UNIX_EPOCH)
        .map_err(SiteError::UnixTime)?;
    let tv_sec = dur.as_secs() as libc::time_t;
    let tv_nsec = dur.subsec_nanos() as libc::c_long;
    Ok(timespec { tv_sec, tv_nsec })
}

fn path_to_cstring(path: &Path) -> CString {
    let path = path.as_os_str();
    let path = path.as_bytes();
    CString::new(path).unwrap()
}

#[cfg(test)]
mod test {
    use super::{
        join_subpath, make_path_absolute, make_path_relative_to, make_relative_link, Path, PathBuf,
    };

    #[test]
    fn joins_relative() {
        assert_eq!(
            join_subpath(Path::new("foo"), Path::new("bar")),
            PathBuf::from("foo/bar")
        );
    }

    #[test]
    fn joins_absolute() {
        assert_eq!(
            join_subpath(Path::new("foo"), Path::new("/bar")),
            PathBuf::from("foo/bar")
        );
    }

    #[test]
    fn makes_relative_link_to_child() {
        assert_eq!(
            make_relative_link("/foo/bar", "/foo/bar/yo"),
            PathBuf::from("bar/yo")
        );
    }

    #[test]
    fn makes_relative_link_to_sibling() {
        assert_eq!(
            make_relative_link("/foo/bar", "/foo/yo"),
            PathBuf::from("yo")
        );
    }

    #[test]
    fn makes_relative_link_to_cousin() {
        assert_eq!(
            make_relative_link("/foo/bar/yo", "/foo/baz/yoyo"),
            PathBuf::from("../baz/yoyo")
        );
    }

    #[test]
    fn makes_relative_link_to_unrelated_page() {
        assert_eq!(
            make_relative_link("/foo/bar", "/yo/yoyo"),
            PathBuf::from("../yo/yoyo")
        );
    }

    #[test]
    fn makes_relative_path() {
        assert_eq!(
            make_path_relative_to(Path::new("/foo"), Path::new("/foo/bar/yo.mdwn")),
            PathBuf::from("bar/yo.mdwn")
        );
    }

    #[test]
    fn makes_absolute_path() {
        assert_eq!(
            make_path_absolute(Path::new("/foo/bar")),
            PathBuf::from("/foo/bar")
        );
    }
}