From d96e3f836ec22848d1f3be1dfc00305bb8498033 Mon Sep 17 00:00:00 2001 From: Chris Morgan Date: Thu, 26 Jan 2017 17:44:14 +0530 Subject: [PATCH] Initial code. --- .gitignore | 2 + .gitlab-ci.yml | 26 +++++++ COPYRIGHT | 3 + Cargo.toml | 11 +++ LICENSE-APACHE | 201 +++++++++++++++++++++++++++++++++++++++++++++++++ LICENSE-MIT | 25 ++++++ README.md | 79 +++++++++++++++++++ src/lib.rs | 182 ++++++++++++++++++++++++++++++++++++++++++++ tests/test.rs | 104 +++++++++++++++++++++++++ 9 files changed, 633 insertions(+) create mode 100644 .gitignore create mode 100644 .gitlab-ci.yml create mode 100644 COPYRIGHT create mode 100644 Cargo.toml create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-MIT create mode 100644 README.md create mode 100644 src/lib.rs create mode 100644 tests/test.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a9d37c5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +target +Cargo.lock diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..df68045 --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,26 @@ +variables: + CARGO_HOME: $CI_PROJECT_DIR/cargo + +before_script: + - rustc --version + - cargo --version + +.job_template: &common + script: + - cargo test --verbose --jobs 1 --release + cache: + paths: + - target/ + - cargo/ + +test:stable: + <<: *common + image: "scorpil/rust:stable" + +test:beta: + <<: *common + image: "scorpil/rust:beta" + +test:nightly: + <<: *common + image: "scorpil/rust:nightly" diff --git a/COPYRIGHT b/COPYRIGHT new file mode 100644 index 0000000..55c8f9f --- /dev/null +++ b/COPYRIGHT @@ -0,0 +1,3 @@ +This project is dual-licensed under the terms of the MIT and Apache (version 2.0) licenses. + +Copyright (c) 2014 Chris Morgan and the Teepee project developers diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..9e53cea --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "symlink" +version = "0.1.0" +authors = ["Chris Morgan "] +description = "Create symlinks in a cross-platform manner" +documentation = "https://docs.rs/symlink" +repository = "https://gitlab.com/chris-morgan/symlink" +readme = "README.md" +keywords = ["file", "fs"] +categories = ["filesystem"] +license = "MIT/Apache-2.0" diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..6866f31 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 Chris Morgan and the Teepee project developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..4e4376b --- /dev/null +++ b/README.md @@ -0,0 +1,79 @@ +# `symlink`: create (and delete) symlinks in a cross-platform manner + +[![Build Status](https://gitlab.com/chris-morgan/symlink/badges/master/build.svg)](https://gitlab.com/chris-morgan/symlink/commits/master) + +Rust’s standard library exposes platform-specific ways to create symlinks: + +- On Windows, `std::os::windows::fs::{symlink_file, symlink_dir}` (because Windows does file and directory symlinks differently); +- On Unixy platforms and Redox, `std::os::unix::fs::symlink` (because they don’t care about whether it’s a file or a directory). + +The situation is similar when removing symlinks: on Unixy platforms all symlinks are files and must be removed with `std::fs::remove_file`, but on Windows directory symlinks must be removed with `std::fs::remove_dir` instead. + +This is all a pain: as soon as you touch symlinks for Unix you need to add in lots of `#[cfg]` branches and other such messy things, or else lose Windows support for no good reason. + +Enter the `symlink` crate. This crate gives you six cross-platform functions instead: + +- `symlink_file`, which creates a file symlink on Windows and a common-or-garden symlink on other platforms; +- `symlink_dir`, which creates a directory symlink on Windows and a perfectly ordinary symlink on other platforms; +- `symlink_auto`, which creates a file or directory symlink on Windows, depending on an examination of the destination, and a perfectly ordinary symlink on other platforms; +- `remove_symlink_file`, which removes a file symlink on Windows and a common-or-garden symlink on other platforms; +- `remove_symlink_dir`, which removes a directory symlink on Windows and a perfectly ordinary symlink on other platforms; +- `remove_symlink_auto`, which removes a file or directory symlink on Windows, depending on an examination of the path, and a perfectly ordinary symlink on other platforms. + +“What about `std::fs::soft_link`?” I hear you say. Yeah, that one got deprecated in Rust 1.1.0 because it didn’t do anything clever on Windows, it just created a file symlink, which is often wrong. `symlink_auto` creates a file *or* directory symlink, depending on what the target is. (Unlike `symlink_file` and `symlink_dir`, it returns an error if the destination doesn’t exist or can’t be statted.) + +And there’s no good way to delete a symlink at all. + +So that’s why this crate exists. + +## Best practices + +You should generally avoid `symlink_auto` and `remove_symlink_auto`, preferring to use the more specific `symlink_file` or `symlink_dir` and `remove_symlink_file` or `remove_symlink_dir`, whichever seems appropriate for what you’re doing. (In real life you almost always know whether you’re making a file or a directory symlink, so say it in the code!) + +**Make sure you use absolute paths for the destination.** I haven’t tested whether relative paths are treated consistently across platforms yet (whether they’re relative to the working directory or the symlink source path). TODO! + +## Caution: this isn’t as useful as it looks + +So now you can create or delete symlinks, right? Not so fast. Although Windows supports symlinks from Windows Vista onwards, it was viewed as a security or compatibility or something risk, and so prior to the Windows 10 Creators Update (due by mid-2017; currently available through the Windows Insider Program) it requires a special privilege, which basically means you’ve got to run a program as admin for it to be allowed to manipulate symlinks. + +Also [Rust PR #38921](https://github.com/rust-lang/rust/pull/38921) needs to land before unprivileged symlink creation will work on the Windows 10 Creators Update. So we’re talking Rust 1.16 as the earliest. + +## My goal: integration with Rust + +I would like to merge this into libstd in some form, because the symlink manipulation support in the standard library at present is hopeless for cross-platformness. I haven’t written an RFC yet; it should definitely start as a separate crate (that’s what this is). Here are some of my thoughts: + +**Concerning `symlink_auto`**: it’s deliberately not named `symlink`; my hope is that people won’t just reach for it blindly but will think about what they are doing. A few things can happen to it (in my order of preference): + +1. It can not exist. It’s really not *necessary*, and letting people be lazy isn’t always good. Encourage cross-platformness! +2. It can exist as `std::fs::symlink_auto`. The distinction is thus clear. +3. `std::fs::soft_link` can be undeprecated, with a change to its Windows semantics from “make a file symlink” to “make a file or directory symlink as appropriate, yielding an error if the destination doesn’t stat”. +4. `std::fs::soft_link` can be undeprecated, with a change to its Windows semantics from “make a file symlink” to “make a file or directory symlink as appropriate, going with a file symlink if the destination doesn’t stat”. +5. It can exist as `std::fs::symlink`. This is the obvious name, but as mentioned earlier encourages inefficient imprecision for Windows. + +**Concerning `symlink_dir` and `symlink_file`**: + +1. `std::fs::{symlink_file, symlink_dir}`, matching `symlink_auto` or nothing. + +2. `std::fs::{soft_link_file, soft_link_dir}`, matching `soft_link` if it is undeprecated. But I don’t like the name “soft link,” anyway: no one calls them that, we all call them symlinks. + +Note that despite the suggestions matching certain approaches for `symlink_auto`, the choices are still independent; there are ten viable combinations presented. + +**Concerning `remove_*`**: I guess what’s done with the other three functions will guide what’s done with these three. + +## Usage + +Cargo all the way: it’s the [`symlink` crate on crates.io](http://crates.io/crates/symlink). + +## Unsafe code in this library + +On Windows only there is some unavoidable unsafe code in `remove_symlink_auto` to determine whether a symlink is a file symlink or a directory symlink, because this detail is not exposed in the standard library. + +## Author + +[Chris Morgan](http://chrismorgan.info/) ([chris-morgan](https://gitlab.com/chris-morgan)) is the primary author and maintainer of this library. + +## License + +This library is distributed under similar terms to Rust: dual licensed under the MIT license and the Apache license (version 2.0). + +See LICENSE-APACHE, LICENSE-MIT, and COPYRIGHT for details. diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..790cb68 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,182 @@ +//! A small, cross-platform crate for creating symlinks. +//! +#![cfg_attr(not(any(target_os = "redox", unix, windows)), doc = "**This platform is not Unix, Windows or Redox; symlinks are not available.**")] +//! +//! For efficiency, you should prefer to use `symlink_file` or `symlink_dir`—whichever is +//! appropriate—rather than `symlink_auto` + +// It’s generally nicer to produce an empty crate on unsupported platforms than to explode. + +use std::fs; +use std::io; +use std::path::Path; + +#[cfg(windows)] +mod internal { + pub use std::os::windows::fs::{symlink_file, symlink_dir}; + pub use std::fs::remove_dir as remove_symlink_dir; + use std::fs; + use std::io; + use std::mem; + use std::path::Path; + + #[inline] + pub fn symlink_auto, Q: AsRef>(src: P, dst: Q) -> io::Result<()> { + if fs::metadata(src.as_ref())?.is_dir() { + symlink_dir(src.as_ref(), dst.as_ref()) + } else { + symlink_file(src.as_ref(), dst.as_ref()) + } + } + + // Copied from the Rust standard library, src/libstd/sys/windows/fs.rs, because it’s an + // implementation detail that isn’t currently exposed in the public interface; I decided to do + // it this way rather than depending on the Debug implementation (which likewise could change). + #[derive(PartialEq)] + enum FileType { + Dir, File, SymlinkFile, SymlinkDir, ReparsePoint, MountPoint, + } + + impl FileType { + pub fn is_symlink_dir(&self) -> bool { + *self == FileType::SymlinkDir || *self == FileType::MountPoint + } + } + + #[inline] + pub fn remove_symlink_auto>(path: P) -> io::Result<()> { + // We need to know whether it’s wrapping a SymlinkFile or SymlinkDir, but in the interests + // of consistency this crucial information is concealed. This is why unsafe transmutation + // is necessary: to determine whether it’s a symlink file or a symlink dir. + let file_type = fs::metadata(path.as_ref())?.file_type(); + let fs_imp_file_type = unsafe { mem::transmute::(file_type) }; + if fs_imp_file_type.is_symlink_dir() { + fs::remove_dir(path) + } else if file_type.is_symlink() { + fs::remove_file(path) + } else { + Err(io::Error::new(io::ErrorKind::InvalidInput, "path is not a symlink")) + } + } +} + +#[cfg(any(target_os = "redox", unix))] +mod internal { + pub use std::fs::remove_file as remove_symlink_dir; + pub use std::fs::remove_file as remove_symlink_auto; + // Note that this symlink function takes src and dst as &Path rather than as impl AsRef. + // I don’t know why that is, but I think we’ll go with impl AsRef in our public + // functions. Because of this disparity of signature, when I say that things are equivalent to + // calling std::os::unix::fs::symlink on Unix, you can see that I’m not being *quite* rigorous. + pub use std::os::unix::fs::{symlink as symlink_auto, + symlink as symlink_file, + symlink as symlink_dir}; +} + +/// Create a symlink (non-preferred way). +/// +/// On Windows, file and directory symlinks are created by distinct methods; to cope with that, +/// this function checks whether the destination is a file or a folder and creates the appropriate +/// type of symlink based on that result. Therefore, if the destination does not exist or if you do +/// not have permission to fetch its metadata, this will return an error on Windows. +/// +/// On Unix platforms there is no distinction, so this isn’t magic: it’s precisely equivalent to +/// calling `std::os::unix::fs::symlink`. +/// +/// # A note on using this function +/// +/// Because this is slightly less efficient and more hazardous on Windows, you should prefer to use +/// [`symlink_file`](fn.symlink_file.html) or [`symlink_dir`](fn.symlink_dir.html) instead. Only +/// use this if you don’t know or care whether the destination is a file or a directory (but even +/// then, you do need to know that it exists). +/// +/// # Errors +/// +/// An error will be returned if the symlink cannot be created, or—on Windows—if the destination +/// does not exist or cannot be read. +#[cfg(any(target_os = "redox", unix, windows))] +#[inline] +pub fn symlink_auto, Q: AsRef>(src: P, dst: Q) -> io::Result<()> { + internal::symlink_auto(src.as_ref(), dst.as_ref()) +} + +/// Create a symlink to a file. +/// +/// On Windows, this is equivalent to `std::os::windows::fs::symlink_file`. If you call it with a +/// directory as the destination, TODO CONSEQUENCES. +/// +/// On Unix, this is equivalent to `std::os::unix::fs::symlink`. If you call it with a directory as +/// the destination, nothing bad will happen, but you’re ruining your cross-platform technique and +/// ruining the point of this crate, so please don’t. +/// +/// # Errors +/// +/// An error will be returned if the symlink cannot be created. +#[cfg(any(target_os = "redox", unix, windows))] +#[inline] +pub fn symlink_file, Q: AsRef>(src: P, dst: Q) -> io::Result<()> { + internal::symlink_file(src.as_ref(), dst.as_ref()) +} + +/// Create a symlink to a directory. +/// +/// On Windows, this is equivalent to `std::os::windows::fs::symlink_dir`. If you call it with a +/// directory as the destination, TODO CONSEQUENCES. +/// +/// On Unix, this is equivalent to `std::os::unix::fs::symlink`. If you call it with a directory as +/// the destination, nothing bad will happen, but you’re ruining your cross-platform technique and +/// ruining the point of this crate, so please don’t. +/// +/// # Errors +/// +/// An error will be returned if the symlink cannot be created. +#[cfg(any(target_os = "redox", unix, windows))] +#[inline] +pub fn symlink_dir, Q: AsRef>(src: P, dst: Q) -> io::Result<()> { + internal::symlink_dir(src.as_ref(), dst.as_ref()) +} + +/// Remove a symlink (non-preferred way). +/// +/// This inspects the path metadata to remove the symlink as a file or directory, whichever is +/// necessary. +/// +/// # A note on using this function +/// +/// Because this is slightly less efficient on Windows, you should prefer to use +/// [`remove_symlink_file`](fn.remove_symlink_file.html) or +/// [`remove_symlink_dir`](fn.remove_symlink_dir.html) instead. Only use this if you don’t know or +/// care whether the destination is a file or a directory (but even then, you do need to know that +/// it exists). +/// +/// # Errors +/// +/// An error will be returned if the symlink cannot be removed. +#[cfg(any(target_os = "redox", unix, windows))] +#[inline] +pub fn remove_symlink_auto>(path: P) -> io::Result<()> { + internal::remove_symlink_auto(path) +} + +/// Remove a directory symlink. +/// +/// On Windows, this corresponds to `std::fs::remove_dir`. +/// +/// On Unix, this corresponds to `std::fs::remove_file`. +#[cfg(any(target_os = "redox", unix, windows))] +#[inline] +pub fn remove_symlink_dir>(path: P) -> io::Result<()> { + internal::remove_symlink_dir(path) +} + +/// Remove a file symlink. +/// +/// This just calls `std::fs::remove_file`, but the function is provided here to correspond to +/// `remove_symlink_dir`. +/// +/// On Unix, this corresponds to `std::fs::remove_file`. +#[cfg(any(target_os = "redox", unix, windows))] +#[inline] +pub fn remove_symlink_file>(path: P) -> io::Result<()> { + fs::remove_file(path) +} diff --git a/tests/test.rs b/tests/test.rs new file mode 100644 index 0000000..441c224 --- /dev/null +++ b/tests/test.rs @@ -0,0 +1,104 @@ +use std::env::temp_dir; +use std::fs::{self, File}; +use std::io; +use std::io::prelude::*; +use std::path::Path; + +extern crate symlink; +use symlink::{symlink_auto, symlink_file, symlink_dir, remove_symlink_file, remove_symlink_dir}; + +const TEST_FILE_CONTENTS: &'static [u8] = + b"This file was created for the purpose of testing the symlink crate."; + +#[test] +fn test_symlink_file() { + let temp = temp_dir(); + let file_path = temp.join("symlink-crate-test-file"); + let symlink_path = temp.join("symlink-crate-test-file-symlink"); + test_file_symlink(&file_path, &symlink_path, |src, dst| symlink_file(src, dst)); +} + +#[test] +fn test_symlink_auto_file() { + let temp = temp_dir(); + let file_path = temp.join("symlink-crate-test-auto-file"); + let symlink_path = temp.join("symlink-crate-test-auto-file-symlink"); + test_file_symlink(&file_path, &symlink_path, |src, dst| symlink_auto(src, dst)); +} + +#[test] +fn test_symlink_dir() { + let temp = temp_dir(); + let dir_path = temp.join("symlink-crate-test-dir"); + let symlink_path = temp.join("symlink-crate-test-dir-symlink"); + test_dir_symlink(&dir_path, &symlink_path, |src, dst| symlink_dir(src, dst)); +} + +#[test] +fn test_symlink_auto_dir() { + let temp = temp_dir(); + let dir_path = temp.join("symlink-crate-test-auto-dir"); + let symlink_path = temp.join("symlink-crate-test-auto-dir-symlink"); + test_dir_symlink(&dir_path, &symlink_path, |src, dst| symlink_auto(src, dst)); +} + +fn test_file_symlink(file_path: &Path, symlink_path: &Path, create_symlink: F) +where F: for<'a> FnOnce(&'a Path, &'a Path) -> io::Result<()> { + let mut file = File::create(file_path).unwrap(); + file.write_all(TEST_FILE_CONTENTS).unwrap(); + // Ensure it’s all written to disk properly. + drop(file); + + // Note: the destination is *deliberately* a relative path. TODO: this would probably be a bad + // idea. On Windows, the paths are relative to the working directory (including treating X:foo + // as foo in the X: working directory); on Linux, I don’t know? If it’s anything like ln, it’s + // a path relative to the symlink. + //create_symlink("symlink-crate-test-file", symlink_path).unwrap(); + create_symlink(file_path, symlink_path).unwrap(); + + assert!(symlink_path.symlink_metadata().unwrap().file_type().is_symlink()); + + file = File::open(symlink_path).unwrap(); + let mut contents = vec![]; + file.read_to_end(&mut contents).unwrap(); + assert_eq!(contents, TEST_FILE_CONTENTS); + drop(file); + + // TODO: use some kind of temp file wrapper which makes sure that the files gets deleted if + // they get created. + remove_symlink_file(symlink_path).unwrap(); + fs::remove_file(file_path).unwrap(); + + assert!(!symlink_path.exists()); + assert!(!file_path.exists()); +} + +fn test_dir_symlink(dir_path: &Path, symlink_path: &Path, create_symlink: F) +where F: for<'a> FnOnce(&'a Path, &'a Path) -> io::Result<()> { + fs::create_dir(dir_path).unwrap(); + + let file_path = dir_path.join("test-file"); + let mut file = File::create(&file_path).unwrap(); + file.write_all(TEST_FILE_CONTENTS).unwrap(); + drop(file); + + create_symlink(dir_path, symlink_path).unwrap(); + + assert!(symlink_path.symlink_metadata().unwrap().file_type().is_symlink()); + + file = File::open(symlink_path.join("test-file")).unwrap(); + let mut contents = vec![]; + file.read_to_end(&mut contents).unwrap(); + assert_eq!(contents, TEST_FILE_CONTENTS); + drop(file); + + // TODO: use some kind of temp file wrapper which makes sure that the files gets deleted if + // they get created. + remove_symlink_dir(symlink_path).unwrap(); + fs::remove_file(&file_path).unwrap(); + fs::remove_dir(dir_path).unwrap(); + + assert!(!symlink_path.exists()); + assert!(!file_path.exists()); + assert!(!dir_path.exists()); +} -- 2.42.0