Skip to main content

portable_symlink/
lib.rs

1#![doc = include_str!("../README.md")]
2#![forbid(unsafe_code)]
3#![warn(missing_docs)]
4
5use std::io;
6use std::path::Path;
7
8/// Creates a file-kind symbolic link at `link` that points to `target`.
9///
10/// Unix symbolic links do not carry a file or directory kind. On Unix, this
11/// function has the same behavior as [`symlink_dir`] and [`symlink_auto`].
12pub fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(target: P, link: Q) -> io::Result<()> {
13    platform::symlink_file(target.as_ref(), link.as_ref())
14}
15
16/// Creates a directory-kind symbolic link at `link` that points to `target`.
17///
18/// Unix symbolic links do not carry a file or directory kind. On Unix, this
19/// function has the same behavior as [`symlink_file`] and [`symlink_auto`].
20pub fn symlink_dir<P: AsRef<Path>, Q: AsRef<Path>>(target: P, link: Q) -> io::Result<()> {
21    platform::symlink_dir(target.as_ref(), link.as_ref())
22}
23
24/// Creates a symbolic link and selects its Windows kind from the target.
25///
26/// On Windows, a relative target is resolved against the parent of `link` for
27/// the kind probe. A missing target returns the probe error. Unix creates the
28/// link without reading the target.
29pub fn symlink_auto<P: AsRef<Path>, Q: AsRef<Path>>(target: P, link: Q) -> io::Result<()> {
30    platform::symlink_auto(target.as_ref(), link.as_ref())
31}
32
33/// Removes a file-kind symbolic link.
34///
35/// A path that is not a symbolic link is refused with
36/// [`io::ErrorKind::InvalidInput`]. Unix symbolic links do not carry a kind.
37pub fn remove_symlink_file<P: AsRef<Path>>(link: P) -> io::Result<()> {
38    platform::remove_symlink_file(link.as_ref())
39}
40
41/// Removes a directory-kind symbolic link or Windows junction.
42///
43/// A path that is not a symbolic link is refused with
44/// [`io::ErrorKind::InvalidInput`]. Unix symbolic links do not carry a kind.
45pub fn remove_symlink_dir<P: AsRef<Path>>(link: P) -> io::Result<()> {
46    platform::remove_symlink_dir(link.as_ref())
47}
48
49/// Removes a symbolic link after reading its Windows kind.
50///
51/// A path that is not a symbolic link is refused with
52/// [`io::ErrorKind::InvalidInput`]. The target is not followed or removed.
53pub fn remove_symlink_auto<P: AsRef<Path>>(link: P) -> io::Result<()> {
54    platform::remove_symlink_auto(link.as_ref())
55}
56
57#[cfg(unix)]
58mod platform {
59    use std::fs;
60    use std::io;
61    use std::os::unix::fs::symlink;
62    use std::path::Path;
63
64    pub(super) fn symlink_file(target: &Path, link: &Path) -> io::Result<()> {
65        symlink(target, link)
66    }
67
68    pub(super) fn symlink_dir(target: &Path, link: &Path) -> io::Result<()> {
69        symlink(target, link)
70    }
71
72    pub(super) fn symlink_auto(target: &Path, link: &Path) -> io::Result<()> {
73        symlink(target, link)
74    }
75
76    pub(super) fn remove_symlink_file(link: &Path) -> io::Result<()> {
77        refuse_non_symlink(link)?;
78        fs::remove_file(link)
79    }
80
81    pub(super) fn remove_symlink_dir(link: &Path) -> io::Result<()> {
82        refuse_non_symlink(link)?;
83        fs::remove_file(link)
84    }
85
86    pub(super) fn remove_symlink_auto(link: &Path) -> io::Result<()> {
87        refuse_non_symlink(link)?;
88        fs::remove_file(link)
89    }
90
91    fn refuse_non_symlink(link: &Path) -> io::Result<fs::Metadata> {
92        let metadata = fs::symlink_metadata(link)?;
93        if metadata.file_type().is_symlink() {
94            Ok(metadata)
95        } else {
96            Err(io::Error::new(
97                io::ErrorKind::InvalidInput,
98                format!("not a symbolic link: {}", link.display()),
99            ))
100        }
101    }
102}
103
104#[cfg(windows)]
105mod platform {
106    use std::ffi::OsString;
107    use std::fs;
108    use std::io;
109    use std::os::windows::ffi::{OsStrExt, OsStringExt};
110    use std::os::windows::fs::MetadataExt;
111    use std::os::windows::fs::{symlink_dir as create_dir_link, symlink_file as create_file_link};
112    use std::path::{Path, PathBuf};
113
114    // FILE_ATTRIBUTE_DIRECTORY from the Win32 file attribute constants.
115    const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;
116
117    pub(super) fn symlink_file(target: &Path, link: &Path) -> io::Result<()> {
118        create_file_link(target, link)
119    }
120
121    pub(super) fn symlink_dir(target: &Path, link: &Path) -> io::Result<()> {
122        create_dir_link(target, link)
123    }
124
125    pub(super) fn symlink_auto(target: &Path, link: &Path) -> io::Result<()> {
126        let target_is_dir = if target.is_absolute() {
127            fs::metadata(target)?.is_dir()
128        } else {
129            let probe = link.parent().unwrap_or_else(|| Path::new("")).join(target);
130            fs::metadata(probe)?.is_dir()
131        };
132
133        let win_target = win_normalise_auto_target(target, target_is_dir);
134        if target_is_dir {
135            create_dir_link(&win_target, link)
136        } else {
137            create_file_link(&win_target, link)
138        }
139    }
140
141    fn win_normalise_auto_target(target: &Path, is_dir: bool) -> PathBuf {
142        let mut target: Vec<u16> = target
143            .as_os_str()
144            .encode_wide()
145            .map(|c| {
146                if c == u16::from(b'/') {
147                    u16::from(b'\\')
148                } else {
149                    c
150                }
151            })
152            .collect();
153        if is_dir {
154            while target.last() == Some(&u16::from(b'\\')) {
155                target.pop();
156            }
157        }
158        PathBuf::from(OsString::from_wide(&target))
159    }
160
161    pub(super) fn remove_symlink_file(link: &Path) -> io::Result<()> {
162        let metadata = refuse_non_symlink(link)?;
163        if metadata.file_attributes() & FILE_ATTRIBUTE_DIRECTORY != 0 {
164            return Err(io::Error::new(
165                io::ErrorKind::InvalidInput,
166                format!("not a file-kind symbolic link: {}", link.display()),
167            ));
168        }
169        fs::remove_file(link)
170    }
171
172    pub(super) fn remove_symlink_dir(link: &Path) -> io::Result<()> {
173        let metadata = refuse_non_symlink(link)?;
174        if metadata.file_attributes() & FILE_ATTRIBUTE_DIRECTORY == 0 {
175            return Err(io::Error::new(
176                io::ErrorKind::InvalidInput,
177                format!("not a directory-kind symbolic link: {}", link.display()),
178            ));
179        }
180        fs::remove_dir(link)
181    }
182
183    pub(super) fn remove_symlink_auto(link: &Path) -> io::Result<()> {
184        let metadata = refuse_non_symlink(link)?;
185        if metadata.file_attributes() & FILE_ATTRIBUTE_DIRECTORY != 0 {
186            fs::remove_dir(link)
187        } else {
188            fs::remove_file(link)
189        }
190    }
191
192    fn refuse_non_symlink(link: &Path) -> io::Result<fs::Metadata> {
193        let metadata = fs::symlink_metadata(link)?;
194        if metadata.file_type().is_symlink() {
195            Ok(metadata)
196        } else {
197            Err(io::Error::new(
198                io::ErrorKind::InvalidInput,
199                format!("not a symbolic link: {}", link.display()),
200            ))
201        }
202    }
203}
204
205#[cfg(not(any(unix, windows)))]
206mod platform {
207    use std::io;
208    use std::path::Path;
209
210    const MESSAGE: &str = "symbolic links are not supported on this target";
211
212    pub(super) fn symlink_file(_target: &Path, _link: &Path) -> io::Result<()> {
213        unsupported()
214    }
215
216    pub(super) fn symlink_dir(_target: &Path, _link: &Path) -> io::Result<()> {
217        unsupported()
218    }
219
220    pub(super) fn symlink_auto(_target: &Path, _link: &Path) -> io::Result<()> {
221        unsupported()
222    }
223
224    pub(super) fn remove_symlink_file(_link: &Path) -> io::Result<()> {
225        unsupported()
226    }
227
228    pub(super) fn remove_symlink_dir(_link: &Path) -> io::Result<()> {
229        unsupported()
230    }
231
232    pub(super) fn remove_symlink_auto(_link: &Path) -> io::Result<()> {
233        unsupported()
234    }
235
236    fn unsupported() -> io::Result<()> {
237        Err(io::Error::new(io::ErrorKind::Unsupported, MESSAGE))
238    }
239}
240
241#[cfg(test)]
242mod unit_tests;