use std::collections::VecDeque;
use std::ffi::OsString;
use std::fs;
use std::io::{self, Read, Write};
use std::path::{Component, Path, PathBuf};
use cap_std::fs::{Dir, File, OpenOptions};
use super::consume::{is_consume_leftover, CONSUME_CLAIM};
use super::say_out;
use super::CliError;
pub(super) fn repo_path_display(path: &Path) -> String {
path.display()
.to_string()
.replace(std::path::MAIN_SEPARATOR, "/")
}
pub(super) const STAGING_MARK: &str = ".oakum-write.";
pub(super) const CONSUME_MARK: &str = ".oakum-consume.";
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum StagingKind {
Write,
Consume,
}
#[derive(Debug)]
pub(super) struct StagingName<'a> {
pub(super) target: &'a str,
pub(super) kind: StagingKind,
pub(super) tail: &'a str,
}
impl StagingName<'_> {
fn pid(&self) -> Option<u32> {
self.tail.split('.').next()?.parse().ok()
}
}
pub(super) fn parse_staging_name(name: &str) -> Option<StagingName<'_>> {
if !name.starts_with('.') {
return None;
}
let write = name
.rfind(STAGING_MARK)
.map(|at| (at, STAGING_MARK, StagingKind::Write));
let consume = name
.rfind(CONSUME_MARK)
.map(|at| (at, CONSUME_MARK, StagingKind::Consume));
let (at, mark, kind) = write
.into_iter()
.chain(consume)
.max_by_key(|(at, ..)| *at)?;
Some(StagingName {
target: name.get(1..at).unwrap_or_default(),
kind,
tail: &name[at + mark.len()..],
})
}
pub(super) fn is_staging_name(name: &str) -> bool {
parse_staging_name(name).is_some()
}
pub(super) fn is_consume_staging_name(name: &str) -> bool {
parse_staging_name(name).is_some_and(|staging| staging.kind == StagingKind::Consume)
}
pub(super) fn stray_staging_files(
dir: &Dir,
sub: &str,
) -> Result<Vec<String>, Box<dyn std::error::Error>> {
let entries = match dir.read_dir(sub) {
Ok(entries) => entries,
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(err) => {
return Err(Box::new(CliError::new(format!(
"failed to read `{sub}`: {err}"
))));
}
};
let mut strays = Vec::new();
for entry in entries {
let entry = entry.map_err(|err| CliError::new(format!("failed to read `{sub}`: {err}")))?;
let is_file = entry.metadata().is_ok_and(|meta| meta.is_file());
if let Some(name) = entry.file_name().to_str() {
if is_file && is_staging_name(name) {
strays.push(if sub == "." {
name.to_owned()
} else {
format!("{sub}/{name}")
});
}
}
}
strays.sort();
Ok(strays)
}
pub(super) fn own_staging_files(
dir: &Dir,
sub: &str,
) -> Result<Vec<String>, Box<dyn std::error::Error>> {
let pid = std::process::id();
Ok(stray_staging_files(dir, sub)?
.into_iter()
.filter(|path| {
parse_staging_name(path.rsplit('/').next().unwrap_or(path))
.and_then(|staging| staging.pid())
== Some(pid)
})
.collect())
}
pub(super) fn stray_staging_message(path: &str) -> String {
let name = path.rsplit('/').next().unwrap_or(path);
if is_consume_leftover(name) {
format!("`{path}` is {CONSUME_CLAIM}")
} else {
format!("`{path}` is {STAGING_CLAIM}")
}
}
pub(super) const STAGING_CLAIM: &str =
"an oakum staging file; if no oakum run is in progress, remove it";
pub(super) fn report_stray_staging(dir: &Dir) -> Result<(), Box<dyn std::error::Error>> {
for path in stray_staging_files(dir, ".changeset")? {
say_out(&stray_staging_message(&path));
}
Ok(())
}
pub(super) fn write_file_via_rename(
dir: &Dir,
target: &Path,
body: &str,
) -> Result<(), Box<dyn std::error::Error>> {
stage_and_replace(dir, target, body).map_err(|failure| failure.into_error(target).into())
}
pub(super) fn write_landing(
dir: &Dir,
target: &Path,
body: &str,
shared: bool,
) -> Result<Landing, Box<dyn std::error::Error>> {
let unfollowed = match link_target(dir, target) {
Ok(None) => None,
Ok(Some(resolved)) if shared => Some(Unfollowed {
names: Some(resolved),
why: String::from("another file this run writes names the same file"),
}),
Ok(Some(resolved)) => match stage_and_replace(dir, &resolved, body) {
Ok(()) => return Ok(Landing::plain(resolved)),
Err(failure) => Some(Unfollowed {
why: failure.into_error(&resolved).to_string(),
names: Some(resolved),
}),
},
Err(unfollowed) => Some(unfollowed),
};
let replaced_link = unfollowed.as_ref().map(|_| ReplacedLink {
target: dir.read_link_contents(target).ok(),
});
if let Err(failure) = stage_and_replace(dir, target, body) {
let err = failure.into_error(target);
return Err(Box::new(match unfollowed {
Some(unfollowed) => CliError::new(format!(
"{err}, after not following it as a link: {}",
unfollowed.why
)),
None => err,
}));
}
if let Some(Unfollowed { names, why }) = unfollowed {
let shown = repo_path_display(target);
super::say_err(&match names {
Some(names) => {
let names = repo_path_display(&names);
format!(
"note: `{shown}` is a link to `{names}` that oakum did not follow ({why}), \
so `{shown}` was replaced by a regular file holding the new text and \
`{names}` did not get it"
)
}
None => format!(
"note: `{shown}` is a link oakum did not follow ({why}), so it was replaced by \
a regular file holding the new text"
),
});
}
Ok(Landing {
at: target.to_path_buf(),
replaced_link,
})
}
pub(super) struct Landing {
pub(super) at: PathBuf,
pub(super) replaced_link: Option<ReplacedLink>,
}
impl Landing {
pub(super) const fn plain(at: PathBuf) -> Self {
Self {
at,
replaced_link: None,
}
}
}
pub(super) struct ReplacedLink {
pub(super) target: Option<PathBuf>,
}
pub(super) struct Unfollowed {
names: Option<PathBuf>,
why: String,
}
pub(super) fn link_target(dir: &Dir, target: &Path) -> Result<Option<PathBuf>, Unfollowed> {
match dir.symlink_metadata(target) {
Ok(meta) if meta.file_type().is_symlink() => {}
_ => return Ok(None),
}
let resolved = dir.canonicalize(target).map_err(|err| Unfollowed {
names: None,
why: format!("it could not be followed: {err}"),
})?;
if resolved.components().any(
|component| matches!(component, Component::Normal(name) if name.eq_ignore_ascii_case(".git")),
) {
return Err(Unfollowed {
names: Some(resolved),
why: String::from("it names a file inside `.git`"),
});
}
Ok(Some(resolved))
}
pub(super) fn link_staging_dir(dir: &Dir, path: &Path) -> Option<String> {
let resolved = link_target(dir, path).ok()??;
Some(match resolved.parent() {
Some(parent) if !parent.as_os_str().is_empty() => repo_path_display(parent),
_ => String::from("."),
})
}
enum Failure {
Stage(io::Error),
Write(io::Error),
Replace(io::Error),
}
impl Failure {
fn into_error(self, target: &Path) -> CliError {
let (step, err) = match self {
Self::Stage(err) | Self::Write(err) => ("stage", err),
Self::Replace(err) => ("replace", err),
};
CliError::new(format!(
"failed to {step} `{}`: {err}",
repo_path_display(target)
))
}
}
fn stage_and_replace(dir: &Dir, target: &Path, body: &str) -> Result<(), Failure> {
let permissions = dir.metadata(target).ok().map(|meta| meta.permissions());
let (parent, file_name) =
staging_parts(target).map_err(|err| Failure::Stage(io::Error::other(err.to_string())))?;
let mut attempt: u32 = 0;
let (tmp, mut staged) = loop {
let candidate = staging_candidate(&parent, file_name, STAGING_MARK, attempt);
match dir.open_with(&candidate, OpenOptions::new().create_new(true).write(true)) {
Ok(file) => break (candidate, file),
Err(err) if err.kind() == io::ErrorKind::AlreadyExists && attempt < 16 => {
attempt += 1;
}
Err(err) => return Err(Failure::Stage(err)),
}
};
staged.write_all(body.as_bytes()).map_err(|err| {
let _ = dir.remove_file(&tmp);
Failure::Write(err)
})?;
if let Some(Err(err)) = permissions.map(|permissions| staged.set_permissions(permissions)) {
super::say_err(&format!(
"warning: `{}` was written with default permissions, since its old ones could not be kept: {err}",
repo_path_display(target)
));
}
drop(staged);
dir.rename(&tmp, dir, target).map_err(|err| {
let _ = dir.remove_file(&tmp);
Failure::Replace(err)
})
}
pub(super) fn stage_aside(dir: &Dir, target: &Path) -> Result<PathBuf, CliError> {
let (parent, file_name) = staging_parts(target)?;
for attempt in 0..16 {
let candidate = staging_candidate(&parent, file_name, CONSUME_MARK, attempt);
match dir.hard_link(target, dir, &candidate) {
Ok(()) => {
return match dir.remove_file(target) {
Ok(()) => Ok(candidate),
Err(err) => {
let _ = dir.remove_file(&candidate);
Err(stage_aside_failed(target, &err))
}
};
}
Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {}
Err(_) => return stage_aside_by_rename(dir, target, &parent, file_name, attempt),
}
}
Err(stage_names_taken(target))
}
fn stage_aside_by_rename(
dir: &Dir,
target: &Path,
parent: &Path,
file_name: &str,
first: u32,
) -> Result<PathBuf, CliError> {
for attempt in first..16 {
let candidate = staging_candidate(parent, file_name, CONSUME_MARK, attempt);
match dir.symlink_metadata(&candidate) {
Ok(_) => continue,
Err(err) if err.kind() == io::ErrorKind::NotFound => {}
Err(err) => {
return Err(CliError::new(format!(
"failed to check staging name `{}` for `{}`: {err}",
repo_path_display(&candidate),
repo_path_display(target)
)));
}
}
return dir
.rename(target, dir, &candidate)
.map(|()| candidate)
.map_err(|err| stage_aside_failed(target, &err));
}
Err(stage_names_taken(target))
}
fn stage_names_taken(target: &Path) -> CliError {
CliError::new(format!(
"failed to move `{}` aside: every staging name was taken",
repo_path_display(target)
))
}
fn stage_aside_failed(target: &Path, err: &io::Error) -> CliError {
CliError::new(format!(
"failed to move `{}` aside: {err}",
repo_path_display(target)
))
}
fn staging_parts(target: &Path) -> Result<(PathBuf, &str), CliError> {
let file_name = target
.file_name()
.and_then(|name| name.to_str())
.ok_or_else(|| CliError::new("write target has no file name"))?;
let parent = target.parent().map(Path::to_path_buf).unwrap_or_default();
Ok((parent, file_name))
}
const STAGING_NAME_KEEP: usize = 200;
pub(super) fn staging_candidate(
parent: &Path,
file_name: &str,
mark: &str,
attempt: u32,
) -> PathBuf {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.subsec_nanos());
let mut keep = file_name.len().min(STAGING_NAME_KEEP);
while !file_name.is_char_boundary(keep) {
keep -= 1;
}
parent.join(format!(
".{}{mark}{}.{nanos}.{attempt}",
&file_name[..keep],
std::process::id()
))
}
pub(super) fn write_file_exclusive(dir: &Dir, target: &Path, body: &str) -> io::Result<()> {
let mut file = dir
.open_with(target, OpenOptions::new().create_new(true).write(true))
.map_err(|err| {
let shown = repo_path_display(target);
let dangling = err.kind() == io::ErrorKind::AlreadyExists
&& dir
.symlink_metadata(target)
.is_ok_and(|meta| meta.file_type().is_symlink())
&& dir
.metadata(target)
.is_err_and(|err| err.kind() == io::ErrorKind::NotFound);
let message = if dangling {
format!("`{shown}` is a symlink whose target does not exist")
} else {
format!("failed to create `{shown}`: {err}")
};
io::Error::new(err.kind(), message)
})?;
file.write_all(body.as_bytes()).map_err(|err| {
let _ = dir.remove_file(target);
io::Error::new(
err.kind(),
format!("failed to write `{}`: {err}", repo_path_display(target)),
)
})?;
Ok(())
}
pub(super) fn open_read_only(dir: &Dir, path: &Path) -> io::Result<File> {
let mut options = OpenOptions::new();
options.read(true);
#[cfg(unix)]
{
use cap_std::fs::OpenOptionsExt;
options.custom_flags(libc::O_NONBLOCK);
}
dir.open_with(path, &options)
}
pub(super) enum ReadFailure {
Open(io::Error),
Inspect(io::Error),
NotRegular,
Read(io::Error),
}
pub(super) fn read_regular(dir: &Dir, path: &Path) -> Result<Option<String>, ReadFailure> {
let mut file = match open_read_only(dir, path) {
Ok(file) => file,
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(err) => return Err(ReadFailure::Open(err)),
};
if !file.metadata().map_err(ReadFailure::Inspect)?.is_file() {
return Err(ReadFailure::NotRegular);
}
let mut text = String::new();
file.read_to_string(&mut text).map_err(ReadFailure::Read)?;
Ok(Some(text))
}
pub(super) fn read_text(
dir: &Dir,
path: &str,
) -> Result<Option<String>, Box<dyn std::error::Error>> {
let failed =
|message: String| -> Box<dyn std::error::Error> { Box::new(CliError::new(message)) };
match read_regular(dir, Path::new(path)) {
Ok(None) if dir.symlink_metadata(path).is_ok() => Err(failed(format!(
"`{path}` is a symlink whose target does not exist"
))),
Ok(text) => Ok(text),
Err(ReadFailure::Open(err)) => Err(failed(format!("failed to open `{path}`: {err}"))),
Err(ReadFailure::Inspect(err)) => Err(failed(format!("failed to inspect `{path}`: {err}"))),
Err(ReadFailure::NotRegular) => Err(failed(format!("`{path}` is not a regular file"))),
Err(ReadFailure::Read(err)) => Err(failed(format!("failed to read `{path}`: {err}"))),
}
}
pub(super) fn read_resolved_text(dir: &Dir, path: &Path) -> Result<Option<String>, CliError> {
let unreadable = |err: io::Error| {
CliError::unverified(format!(
"unverified: failed to read `{}`: {err}",
repo_path_display(path)
))
};
let not_regular = || {
CliError::unverified(format!(
"unverified: `{}` is not a regular file",
repo_path_display(path)
))
};
read_regular(dir, path).map_err(|failure| match failure {
ReadFailure::Open(err) => match dir.metadata(path) {
Ok(meta) if !meta.is_file() => not_regular(),
_ => unreadable(err),
},
ReadFailure::Inspect(err) | ReadFailure::Read(err) => unreadable(err),
ReadFailure::NotRegular => not_regular(),
})
}
pub(super) fn resolve_capability_path(
dir: &Dir,
repo_path: &Path,
path: &Path,
) -> Result<PathBuf, Box<dyn std::error::Error>> {
let mut pending = relative_components(path)?;
let mut resolved = PathBuf::new();
let mut followed = 0;
while let Some(component) = pending.pop_front() {
match component {
PendingComponent::Parent => {
if !resolved.pop() {
return Err(outside_repository(path));
}
}
PendingComponent::Normal(component) => {
let candidate = resolved.join(&component);
let metadata = dir.symlink_metadata(&candidate).map_err(|err| {
path_error(format!(
"failed to resolve `{}` within the repository: {err}",
repo_path_display(path)
))
})?;
if !metadata.file_type().is_symlink() {
resolved.push(component);
continue;
}
followed += 1;
if followed > 40 {
return Err(path_error(format!(
"`{}` contains too many symbolic links",
repo_path_display(path)
)));
}
let target = match dir.read_link_contents(&candidate) {
Ok(target) => target,
Err(err) => {
#[cfg(not(windows))]
{
return Err(path_error(format!(
"failed to resolve `{}` within the repository: {err}",
repo_path_display(path)
)));
}
#[cfg(windows)]
{
let _ = err;
match read_symlink_via_ambient(repo_path, &candidate) {
Ok(target) => target,
Err(_) => return Err(outside_repository(path)),
}
}
}
};
#[cfg(windows)]
let target = win32_from_nt_symlink_target(&target);
let target = if target.is_absolute() {
resolved.clear();
contained_absolute_target(repo_path, &target)
.ok_or_else(|| outside_repository(path))?
} else {
target
};
let mut target_components = relative_components(&target)?;
while let Some(target_component) = target_components.pop_back() {
pending.push_front(target_component);
}
}
}
}
if resolved.as_os_str().is_empty() {
Ok(PathBuf::from("."))
} else {
Ok(resolved)
}
}
enum PendingComponent {
Parent,
Normal(OsString),
}
fn relative_components(
path: &Path,
) -> Result<VecDeque<PendingComponent>, Box<dyn std::error::Error>> {
let mut components = VecDeque::new();
for component in path.components() {
match component {
Component::Normal(component) => {
components.push_back(PendingComponent::Normal(component.to_owned()));
}
Component::CurDir => {}
Component::ParentDir => components.push_back(PendingComponent::Parent),
Component::RootDir | Component::Prefix(_) => return Err(outside_repository(path)),
}
}
Ok(components)
}
#[cfg(any(windows, test))]
fn win32_from_nt_symlink_target(target: &Path) -> PathBuf {
let text = target.to_string_lossy().replace('/', "\\");
let win32 = if let Some(rest) = text.strip_prefix(r"\??\UNC\") {
format!(r"\\{rest}")
} else if let Some(rest) = text.strip_prefix(r"\??\") {
rest.to_owned()
} else if let Some(rest) = text.strip_prefix(r"UNC\") {
format!(r"\\{rest}")
} else {
text
};
PathBuf::from(win32)
}
#[cfg(windows)]
fn read_symlink_via_ambient(repo_path: &Path, candidate: &Path) -> io::Result<PathBuf> {
std::fs::read_link(repo_path.join(candidate)).or_else(|_| {
std::fs::read_link(PathBuf::from(normalized_windows_path(repo_path)).join(candidate))
})
}
#[cfg(not(windows))]
fn contained_absolute_target(repo_path: &Path, target: &Path) -> Option<PathBuf> {
fs::canonicalize(target)
.ok()?
.strip_prefix(repo_path)
.ok()
.map(Path::to_path_buf)
}
#[cfg(windows)]
fn contained_absolute_target(repo_path: &Path, target: &Path) -> Option<PathBuf> {
let repo = normalized_windows_path(repo_path);
let target = normalized_windows_path(&fs::canonicalize(target).ok()?);
contained_windows_path(&repo, &target)
}
#[cfg(any(windows, test))]
fn contained_windows_path(repo: &str, target: &str) -> Option<PathBuf> {
let prefix = target.get(..repo.len())?;
if !prefix.eq_ignore_ascii_case(repo) {
return None;
}
let remainder = target.get(repo.len()..)?;
let repo_ends_with_separator = repo.ends_with('\\') || repo.ends_with('/');
if !remainder.is_empty()
&& !repo_ends_with_separator
&& !remainder.starts_with('\\')
&& !remainder.starts_with('/')
{
return None;
}
Some(PathBuf::from(remainder.trim_start_matches(|character| {
character == '\\' || character == '/'
})))
}
#[cfg(any(windows, test))]
pub(super) fn normalized_windows_path(path: &Path) -> String {
let path = path.to_string_lossy().replace('/', "\\");
let path = if let Some(rest) = path.strip_prefix(r"\\?\UNC\") {
format!(r"\\{rest}")
} else if let Some(rest) = path.strip_prefix(r"\\?\") {
rest.to_owned()
} else {
path
};
loopback_admin_share(&path).unwrap_or(path)
}
#[cfg(any(windows, test))]
fn loopback_admin_share(path: &str) -> Option<String> {
let rest = path.strip_prefix(r"\\")?;
let mut parts = rest.splitn(3, '\\');
let host = parts.next()?;
let share = parts.next()?;
let tail = parts.next();
if !(host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1") {
return None;
}
let bytes = share.as_bytes();
if share.len() != 2 || bytes.get(1) != Some(&b'$') || !bytes[0].is_ascii_alphabetic() {
return None;
}
let drive = bytes[0].to_ascii_uppercase() as char;
Some(match tail {
Some(tail) if !tail.is_empty() => format!(r"{drive}:\{tail}"),
_ => format!(r"{drive}:\"),
})
}
pub(super) fn outside_repository_message(
dir: &Dir,
path: &Path,
err: &io::Error,
) -> Option<String> {
if err.kind() != io::ErrorKind::PermissionDenied
|| err.to_string() != "a path led outside of the filesystem"
{
return None;
}
let shown = repo_path_display(path);
let absolute = dir
.read_link_contents(path)
.is_ok_and(|target| target.is_absolute());
Some(if absolute {
format!("`{shown}` is a symlink with an absolute target, which oakum does not follow")
} else {
format!(
"`{shown}` is reached through a path that leaves the repository, or through a symlink with an absolute target, which oakum does not follow"
)
})
}
fn outside_repository(path: &Path) -> Box<dyn std::error::Error> {
path_error(format!(
"`{}` resolves outside the repository",
repo_path_display(path)
))
}
fn path_error(message: impl Into<String>) -> Box<dyn std::error::Error> {
Box::new(CliError::new(message))
}
#[cfg(test)]
mod tests {
use std::path::{Path, PathBuf};
use super::{
contained_windows_path, normalized_windows_path, repo_path_display,
win32_from_nt_symlink_target,
};
fn open(root: &Path) -> cap_std::fs::Dir {
cap_std::fs::Dir::open_ambient_dir(root, cap_std::ambient_authority()).unwrap()
}
#[cfg(unix)]
#[test]
fn an_exclusive_create_names_only_a_dangling_link() {
let root = crate::test_fixture::Fixture::new("fs", "exclusive-link");
std::fs::write(root.join("real.md"), "x").unwrap();
std::os::unix::fs::symlink("real.md", root.join("live.md")).unwrap();
std::os::unix::fs::symlink("gone.md", root.join("dangling.md")).unwrap();
let dir = open(&root);
let live = super::write_file_exclusive(&dir, Path::new("live.md"), "y")
.unwrap_err()
.to_string();
assert!(live.starts_with("failed to create `live.md`"), "{live}");
let dangling = super::write_file_exclusive(&dir, Path::new("dangling.md"), "y")
.unwrap_err()
.to_string();
assert_eq!(
dangling,
"`dangling.md` is a symlink whose target does not exist"
);
}
#[test]
fn only_an_escape_is_worded_as_one() {
let root = crate::test_fixture::Fixture::new("fs", "escape-wording");
std::fs::write(root.join("plain.md"), "x").unwrap();
let dir = open(&root);
let escape = std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"a path led outside of the filesystem",
);
let denied = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");
assert_eq!(
super::outside_repository_message(&dir, Path::new("plain.md"), &denied),
None
);
assert_eq!(
super::outside_repository_message(&dir, Path::new("plain.md"), &escape).as_deref(),
Some("`plain.md` is reached through a path that leaves the repository, or through a symlink with an absolute target, which oakum does not follow")
);
}
#[cfg(unix)]
#[test]
fn write_file_via_rename_replaces_a_link_without_following_it() {
let root = crate::test_fixture::Fixture::new("fs", "replace-link");
std::fs::write(root.join("source.md"), "old").unwrap();
std::os::unix::fs::symlink("source.md", root.join("dest.md")).unwrap();
let dir = cap_std::fs::Dir::open_ambient_dir(&root, cap_std::ambient_authority()).unwrap();
super::write_file_via_rename(&dir, Path::new("dest.md"), "new").unwrap();
assert!(!std::fs::symlink_metadata(root.join("dest.md"))
.unwrap()
.file_type()
.is_symlink());
assert_eq!(
std::fs::read_to_string(root.join("dest.md")).unwrap(),
"new"
);
assert_eq!(
std::fs::read_to_string(root.join("source.md")).unwrap(),
"old"
);
}
#[cfg(unix)]
#[test]
fn a_socket_is_not_a_regular_file() {
struct Removed(PathBuf);
impl Drop for Removed {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
let root =
Removed(std::env::temp_dir().join(format!("oakum-socket-{}", std::process::id())));
std::fs::create_dir_all(&root.0).expect("socket dir");
let _listener =
std::os::unix::net::UnixListener::bind(root.0.join("pin.toml")).expect("bind a socket");
let dir =
cap_std::fs::Dir::open_ambient_dir(&root.0, cap_std::ambient_authority()).expect("dir");
let err = super::read_resolved_text(&dir, Path::new("pin.toml")).expect_err("refused");
assert!(err.to_string().contains("is not a regular file"), "{err}");
}
#[test]
fn repo_path_display_uses_forward_slashes() {
assert_eq!(
repo_path_display(&Path::new(".github/workflows").join("ci.yml")),
".github/workflows/ci.yml"
);
}
#[cfg(windows)]
#[test]
fn repo_path_display_rewrites_a_backslash_separator() {
assert_eq!(
repo_path_display(Path::new(r".github\workflows\ci.yml")),
".github/workflows/ci.yml"
);
}
#[test]
fn windows_drive_root_contains_files() {
assert_eq!(
contained_windows_path(r"C:\", r"c:\config.toml"),
Some(PathBuf::from("config.toml"))
);
assert_eq!(
contained_windows_path(r"C:\repo", r"c:\repository\config.toml"),
None
);
}
#[test]
fn path_component_case_is_ignored_for_windows_containment() {
assert_eq!(
contained_windows_path(r"C:\Users\repo", r"c:\users\REPO\.changeset\_config.toml"),
Some(PathBuf::from(r".changeset\_config.toml"))
);
assert_eq!(
contained_windows_path(r"C:\Users\repo", r"c:\users\repository\config.toml"),
None
);
}
#[test]
fn verbatim_and_unc_prefixes_strip_to_the_drive_path() {
assert_eq!(
normalized_windows_path(Path::new(r"\\?\C:\repo\_config.toml")),
r"C:\repo\_config.toml"
);
assert_eq!(
normalized_windows_path(Path::new(r"\\?\UNC\localhost\C$\repo")),
r"C:\repo"
);
assert_eq!(
normalized_windows_path(Path::new(r"\\localhost\C$\repo\a")),
r"C:\repo\a"
);
assert_eq!(
normalized_windows_path(Path::new(r"\\127.0.0.1\c$\repo")),
r"C:\repo"
);
assert_eq!(
normalized_windows_path(Path::new(r"\\fileserver\C$\repo")),
r"\\fileserver\C$\repo"
);
assert_eq!(
normalized_windows_path(Path::new("C:/repo/a")),
r"C:\repo\a"
);
assert_eq!(
normalized_windows_path(Path::new("//localhost/C$/repo")),
r"C:\repo"
);
assert_eq!(
normalized_windows_path(Path::new("//?/C:/repo/a")),
r"C:\repo\a"
);
assert_eq!(
normalized_windows_path(Path::new(r"\\localhost\C$")),
r"C:\"
);
assert_eq!(
normalized_windows_path(Path::new(r"\\localhost\C$\")),
r"C:\"
);
}
#[test]
fn nt_symlink_unc_becomes_win32_unc() {
assert_eq!(
win32_from_nt_symlink_target(Path::new(r"UNC\localhost\C$\repo")),
PathBuf::from(r"\\localhost\C$\repo")
);
assert_eq!(
win32_from_nt_symlink_target(Path::new(r"\??\UNC\localhost\C$\repo")),
PathBuf::from(r"\\localhost\C$\repo")
);
assert_eq!(
win32_from_nt_symlink_target(Path::new(r"\??\C:\repo")),
PathBuf::from(r"C:\repo")
);
assert_eq!(
win32_from_nt_symlink_target(Path::new(r"..\outside")),
PathBuf::from(r"..\outside")
);
}
#[test]
fn a_loopback_unc_repo_contains_a_canonical_drive_target() {
let repo = normalized_windows_path(Path::new(r"\\localhost\C$\repo"));
assert_eq!(repo, r"C:\repo");
assert_eq!(
contained_windows_path(&repo, r"c:\repo\.changeset\_config.toml"),
Some(PathBuf::from(r".changeset\_config.toml"))
);
assert_eq!(
contained_windows_path(
&repo,
&normalized_windows_path(Path::new(r"\\?\C:\repo\.changeset\_config.toml"))
),
Some(PathBuf::from(r".changeset\_config.toml"))
);
assert_eq!(
contained_windows_path(&repo, r"D:\repo\.changeset\_config.toml"),
None
);
assert_eq!(
contained_windows_path(
&normalized_windows_path(Path::new(r"\\fileserver\C$\repo")),
r"C:\repo\.changeset\_config.toml"
),
None
);
}
#[test]
fn staging_names_are_the_dot_prefixed_marked_ones() {
use super::is_staging_name;
assert!(is_staging_name(".one.md.oakum-write.123.456.0"));
assert!(is_staging_name("._config.toml.oakum-write.1.2.3"));
assert!(!is_staging_name("one.md"));
assert!(!is_staging_name("oakum-write.md"));
assert!(!is_staging_name("one.md.oakum-write.1.2.3"));
assert!(!is_staging_name(".gitkeep"));
assert!(is_staging_name(".one.md.oakum-consume.123.456.0"));
assert!(is_staging_name(".oakum-write.1.2.3"));
}
#[test]
fn consume_names_are_told_apart_from_write_names() {
use super::{is_consume_staging_name, parse_staging_name, StagingKind};
assert!(is_consume_staging_name(".one.md.oakum-consume.1.2.0"));
assert!(!is_consume_staging_name("._config.toml.oakum-write.1.2.0"));
let consume = parse_staging_name(".a.oakum-write.9.md.oakum-consume.42.1.0").unwrap();
assert_eq!(
(consume.target, consume.kind, consume.pid()),
("a.oakum-write.9.md", StagingKind::Consume, Some(42))
);
let write = parse_staging_name(".a.oakum-consume.9.md.oakum-write.43.1.0").unwrap();
assert_eq!(
(write.target, write.kind, write.pid()),
("a.oakum-consume.9.md", StagingKind::Write, Some(43))
);
}
#[test]
fn a_consume_leftover_is_not_advised_for_removal() {
use super::{stray_staging_message, CONSUME_CLAIM, STAGING_CLAIM};
let consume = stray_staging_message(".changeset/.a.md.oakum-consume.1.2.0");
assert!(consume.ends_with(CONSUME_CLAIM), "{consume}");
let write = stray_staging_message(".changeset/._config.toml.oakum-write.1.2.0");
assert!(write.ends_with(STAGING_CLAIM), "{write}");
let rewrite =
stray_staging_message(".changeset/..version.oakum-consume.1.2.0.oakum-write.9.8.0");
assert!(rewrite.ends_with(CONSUME_CLAIM), "{rewrite}");
}
#[test]
fn the_last_mark_decides_a_staging_names_kind() {
use super::is_consume_staging_name;
assert!(is_consume_staging_name(".a.md.oakum-consume.1.2.0"));
assert!(!is_consume_staging_name(
"..version.oakum-consume.1.2.0.oakum-write.9.8.0"
));
assert!(is_consume_staging_name(
".a.oakum-write.md.oakum-consume.1.2.0"
));
}
}