Unverified Commit b2e835de authored by Benjamin Woodruff ‮'s avatar Benjamin Woodruff Committed by GitHub

Turbopack: Split the read and write codepath data structures for symlinks (#97395)

Another attempt at cleanup, similar to
https://github.com/vercel/next.js/pull/96955.

We need different information to write symlinks or junction points (most
notably, if it's a directory or not) than we get when reading symlinks.

We were trying to use the same data structure for both, but this lead us
to always call `get_type()` as part of reading a link, which was just
silly.

This also meant that `write_link` had to handle `NotFound` and
`Invalid`. `NotFound` is somewhat reasonable (just delete the file), but
`Invalid` is awkward.
parent ee690921
......@@ -10260,6 +10260,7 @@ dependencies = [
"turbo-unix-path",
"url",
"urlencoding",
"windows-sys 0.60.2",
]
[[package]]
......
......@@ -361,6 +361,7 @@ unsize = "1.1.0"
unty = "0.0.4"
url = "2.2.2"
urlencoding = "2.1.2"
windows-sys = "0.60"
uuid = "1.18.1"
vergen = { version = "9.0.6", features = ["cargo"] }
vergen-gitcl = { version = "1.0.8", features = ["cargo"] }
......
......@@ -285,22 +285,14 @@ async fn assets_diff(
),
}
}
(
AssetContent::Redirect {
target: target1,
link_type: link_type1,
},
AssetContent::Redirect {
target: target2,
link_type: link_type2,
},
) => {
if target1 == target2 && link_type1 == link_type2 {
(AssetContent::Redirect(content1), AssetContent::Redirect(content2)) => {
if content1.target == content2.target && content1.target_type == content2.target_type {
None
} else {
Some(format!(
"assets at the same path are both redirects but point to different targets: \
{target1} vs {target2}"
"assets at the same path are both redirects but disagree: {:?} ({:?}) vs {:?} \
({:?})",
content1.target, content1.target_type, content2.target, content2.target_type,
))
}
}
......
......@@ -58,9 +58,11 @@ use turbo_tasks::{
unmark_top_level_task_may_leak_eventually_consistent_state,
};
use turbo_tasks_backend::db_invalidation::invalidation_reasons;
#[cfg(windows)]
use turbo_tasks_fs::windows::to_verbatim_with_case_folded_disk;
use turbo_tasks_fs::{
DiskFileSystem, FileContent, FileSystem, FileSystemPath, canonicalize_to_rcstr, invalidation,
to_verbatim_with_case_folded_disk, util::uri_from_file,
util::uri_from_file,
};
use turbo_unix_path::{get_relative_path_to, unix_to_sys};
use turbopack_core::{
......@@ -2385,9 +2387,12 @@ fn parse_and_canonicalize_source_url(source_url: &str) -> Result<(RcStr, Option<
Err(_) => {
// The file may not exist (e.g. a stale stack frame). Fall back to a purely lexical
// normalization that approximates the canonical format.
if cfg!(windows) {
#[cfg(windows)]
{
to_verbatim_with_case_folded_disk(&path).unwrap_or(path)
} else {
}
#[cfg(not(windows))]
{
path
}
}
......
......@@ -59,6 +59,11 @@ urlencoding = { workspace = true }
[target.'cfg(windows)'.dependencies]
omnipath = "0.1.6"
windows-sys = { workspace = true, features = [
"Win32_Foundation",
"Win32_Storage_FileSystem",
"Win32_System_SystemServices",
] }
[dev-dependencies]
criterion = { workspace = true, features = ["async_tokio"] }
......@@ -68,4 +73,3 @@ sha2 = { workspace = true }
tempfile = { workspace = true }
turbo-tasks-testing = { workspace = true }
turbo-tasks-backend = { workspace = true }
......@@ -10,7 +10,6 @@ use std::{
use anyhow::{Result, bail};
use bincode::{Decode, Encode};
use bitflags::bitflags;
use jsonc_parser::{ParseOptions, parse_to_serde_value};
use mime::Mime;
use serde_json::Value;
......@@ -21,6 +20,7 @@ use turbo_tasks_hash::{
};
use crate::{
FileSystemEntryType, FileSystemPath,
json::UnparsableJson,
retry::retry_blocking,
rope::{Rope, RopeReader},
......@@ -163,47 +163,69 @@ pub(crate) enum FileComparison {
NotEqual,
}
bitflags! {
#[derive(
Default,
TraceRawVcs,
NonLocalValue,
DeterministicHash,
Encode,
Decode,
)]
pub struct LinkType: u8 {
const DIRECTORY = 0b00000001;
const ABSOLUTE = 0b00000010;
}
/// The target of a symbolic link, as read from a filesystem.
///
/// Every variant carries the `resolved` path the link points at, computed once by
/// [`crate::FileSystem::read_link`], which is also what guarantees the target stays inside the
/// filesystem root — a link whose target leaves the root is [`LinkContent::Invalid`] instead.
#[derive(Clone, Debug, Hash, PartialEq, Eq, TraceRawVcs, NonLocalValue, Encode, Decode)]
pub enum LinkTarget {
/// The link is an absolute path on disk.
Absolute { resolved: FileSystemPath },
Relative {
/// The value read from the link. The path is lexically converted to a [unix-style
/// path][turbo_unix_path::sys_to_unix], but it may contain `..` relative to the *directory
/// containing the link*.
raw: RcStr,
/// The link target relative the a `DiskFileSystem` root.
resolved: FileSystemPath,
},
}
/// The contents of a symbolic link. On Windows, this may be a junction point.
impl LinkTarget {
/// The path this link points at.
pub fn file_system_path(&self) -> &FileSystemPath {
match self {
LinkTarget::Absolute { resolved } | LinkTarget::Relative { resolved, .. } => resolved,
}
}
/// The type of the file this link points at.
///
/// This only follows a single link: if the target is itself a symbolic link, this returns
/// [`FileSystemEntryType::Symlink`]. Use [`FileSystemPath::realpath`] to follow a chain of
/// links.
///
/// A dangling link returns [`FileSystemEntryType::NotFound`].
pub async fn target_type(&self) -> Result<FileSystemEntryType> {
Ok(*self.file_system_path().get_type().await?)
}
}
/// The contents of a symbolic link, as read from a filesystem. On Windows, this may be a junction
/// point.
///
/// We treat symbolic links and junction points on Windows as equivalent when reading.
///
/// When reading, we treat symbolic links and junction points on Windows as equivalent. When
/// creating a new link, we always create junction points, because symlink creation may fail if
/// Windows "developer mode" is not enabled and we're running in an unprivileged environment.
/// This describes the link itself and never the type of the file it points at. Use
/// [`LinkTarget::target_type`] if you need the type of the target.
#[turbo_tasks::value(shared)]
#[derive(Debug, DeterministicHash)]
#[derive(Debug)]
pub enum LinkContent {
/// A valid symbolic link pointing to `target`, a unix-style path.
///
/// If [`LinkType::ABSOLUTE`] is set, `target` is normalized and relative to the *filesystem
/// root* (so that absolute system paths never end up in the persistent cache). Otherwise,
/// `target` is the raw value read from the link — unnormalized, may contain `..` — and is
/// relative to the *directory containing the link*.
/// A valid symbolic link pointing to `target`.
Link { target: LinkTarget },
/// The link itself does not exist at the path given to [`FileSystemPath::read_link`].
///
/// A relative `target` must stay raw so that [`FileSystem::write_link`] round-trips it
/// exactly: the value is written verbatim and compared against [`std::fs::read_link`] to
/// skip unchanged links.
Link {
target: RcStr,
link_type: LinkType,
},
// Invalid means the link is invalid it points out of the filesystem root
Invalid,
// The target was not found
/// This says nothing about whether the link's target exists: a dangling link is still
/// returned as [`LinkContent::Link`].
NotFound,
/// The link could not be read.
///
/// This includes all I/O errors other than `NotFound`, denied paths, and targets that leave the
/// filesystem root. A relative target that steps out of the root and back into it is also
/// invalid, since resolving it would need the names of the root's own ancestors, which a
/// root-relative path doesn't carry.
Invalid { reason: RcStr },
}
#[turbo_tasks::value_impl]
......@@ -213,14 +235,70 @@ impl LinkContent {
/// re-create a symlink as a symlink instead of copying the resolved file.
#[turbo_tasks::function]
pub async fn hash(&self, salt: Vc<RcStr>, algorithm: HashAlgorithm) -> Result<Vc<RcStr>> {
#[derive(DeterministicHash)]
enum SimplifiedLinkContent<'a> {
Absolute(&'a RcStr),
Relative(&'a RcStr),
NotFound,
Invalid, // the actual error message doesn't matter for this API
}
let simplified = match self {
LinkContent::Link { target } => match target {
LinkTarget::Absolute { resolved } => {
SimplifiedLinkContent::Absolute(&resolved.path)
}
LinkTarget::Relative { raw, resolved: _ } => SimplifiedLinkContent::Relative(raw),
},
LinkContent::NotFound => SimplifiedLinkContent::NotFound,
LinkContent::Invalid { reason: _ } => SimplifiedLinkContent::Invalid,
};
Ok(Vc::cell(RcStr::from(deterministic_hash(
&salt.await?,
self,
simplified,
algorithm,
))))
}
}
/// The target of a symbolic link to create, used by [`WriteLinkContent`].
///
/// Unlike [`LinkTarget`] this carries only the raw path: the write side never needs the target
/// resolved, and the link being created may not even exist yet.
#[derive(
Clone, Debug, Hash, PartialEq, Eq, TraceRawVcs, NonLocalValue, DeterministicHash, Encode, Decode,
)]
pub enum WriteLinkTarget {
/// Normalized and relative to the *filesystem root*.
Absolute(RcStr),
/// Written verbatim, relative to the *directory containing the link*.
Relative(RcStr),
}
/// The file type of the target of a newly written link. This value is only used on Windows.
#[derive(
Clone, Debug, Hash, PartialEq, Eq, TraceRawVcs, NonLocalValue, DeterministicHash, Encode, Decode,
)]
pub enum WriteLinkTargetType {
/// Represents a link to a file or a symbolic link that is not a junction point. This is likely
/// to fail on Windows, where symbolic links are not enabled by default.
FileNonPortable,
/// Represents a link to a directory. On Windows, this may also be a link to a junction point.
DirectoryOrJunctionPoint,
}
/// The symbolic link to create at a path, passed to [`FileSystemPath::write_link`].
///
/// This is separate from [`LinkContent`] because writing needs to know whether the target is a
/// directory, while reading a link does not: on Windows we always create junction points for
/// directories, because symlink creation may fail if "developer mode" is not enabled and we're
/// running in an unprivileged environment.
#[turbo_tasks::value(shared)]
#[derive(Clone, Debug, DeterministicHash)]
pub struct WriteLinkContent {
pub target: WriteLinkTarget,
pub target_type: WriteLinkTargetType,
}
#[turbo_tasks::value(shared)]
#[derive(Clone, DeterministicHash, PartialOrd, Ord)]
pub struct File {
......
This diff is collapsed.
use anyhow::{Result, bail};
use auto_hash_map::AutoMap;
use include_dir::{Dir, DirEntry};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ValueToString, Vc};
use crate::{
File, FileContent, FileMeta, FileSystem, FileSystemPath, LinkContent, RawDirectoryContent,
RawDirectoryEntry,
RawDirectoryEntry, WriteLinkContent,
};
#[derive(ValueToString)]
......@@ -38,7 +38,15 @@ impl FileSystem for EmbeddedFileSystem {
#[turbo_tasks::function]
fn read_link(&self, _path: FileSystemPath) -> Vc<LinkContent> {
LinkContent::NotFound.cell()
LinkContent::Invalid {
reason: rcstr!("the filesystem does not support symbolic links"),
}
.cell()
}
#[turbo_tasks::function]
fn is_junction_point(&self, _path: FileSystemPath) -> Vc<bool> {
Vc::cell(false)
}
#[turbo_tasks::function]
......@@ -77,7 +85,7 @@ impl FileSystem for EmbeddedFileSystem {
}
#[turbo_tasks::function]
fn write_link(&self, _path: FileSystemPath, _target: Vc<LinkContent>) -> Result<Vc<()>> {
fn write_link(&self, _path: FileSystemPath, _target: Vc<WriteLinkContent>) -> Result<Vc<()>> {
bail!("Writing is not possible to the embedded filesystem")
}
......
......@@ -33,7 +33,8 @@ pub mod source_context;
pub mod util;
pub(crate) mod virtual_fs;
mod watcher;
mod windows;
#[cfg(windows)]
pub mod windows;
use std::{fmt::Debug, fs::FileType, path::PathBuf};
......@@ -53,7 +54,8 @@ pub(crate) use crate::{
pub use crate::{
content::{
File, FileContent, FileJsonContent, FileLine, FileLinesContent, FileMeta, LinkContent,
LinkType, Permissions, PersistedFileContent,
LinkTarget, Permissions, PersistedFileContent, WriteLinkContent, WriteLinkTarget,
WriteLinkTargetType,
},
disk::{DiskFileSystem, canonicalize_to_rcstr, validate_path_length},
null_fs::NullFileSystem,
......@@ -61,7 +63,6 @@ pub use crate::{
read_glob::ReadGlobResult,
virtual_fs::VirtualFileSystem,
watcher::{DiskWatcherConfig, DiskWatcherPathMatcher, DiskWatcherRecursiveMode},
windows::to_verbatim_with_case_folded_disk,
};
#[turbo_tasks::value_trait]
......@@ -73,23 +74,20 @@ pub trait FileSystem: ValueToString {
}
#[turbo_tasks::function]
fn read(self: Vc<Self>, fs_path: FileSystemPath) -> Vc<FileContent>;
/// Reads the target of a symbolic link (or of a junction point on Windows).
///
/// The base of the returned [`LinkContent::Link`] `target` depends on the link's
/// [`LinkType`]: root-relative and normalized for [`LinkType::ABSOLUTE`] links, or the raw
/// link-relative on-disk value otherwise.
///
/// Returns [`LinkContent::Invalid`] if the target points outside of the filesystem root, and
/// [`LinkContent::NotFound`] if `fs_path` doesn't exist or isn't a link.
/// Reads the target of a symbolic link (or junction point on Windows). See [`LinkContent`].
#[turbo_tasks::function]
fn read_link(self: Vc<Self>, fs_path: FileSystemPath) -> Vc<LinkContent>;
/// Returns whether a symbolic link is a junction point on Windows. Always `false` on all other
/// platforms.
#[turbo_tasks::function]
fn is_junction_point(self: Vc<Self>, fs_path: FileSystemPath) -> Vc<bool>;
#[turbo_tasks::function]
fn raw_read_dir(self: Vc<Self>, fs_path: FileSystemPath) -> Vc<RawDirectoryContent>;
#[turbo_tasks::function]
fn write(self: Vc<Self>, fs_path: FileSystemPath, content: Vc<FileContent>) -> Vc<()>;
/// See [`FileSystemPath::write_symbolic_link_dir`].
/// Creates a symbolic link. See [`WriteLinkContent`] and [`FileSystemPath::write_link`].
#[turbo_tasks::function]
fn write_link(self: Vc<Self>, fs_path: FileSystemPath, target: Vc<LinkContent>) -> Vc<()>;
fn write_link(self: Vc<Self>, fs_path: FileSystemPath, target: Vc<WriteLinkContent>) -> Vc<()>;
#[turbo_tasks::function]
fn metadata(self: Vc<Self>, fs_path: FileSystemPath) -> Vc<FileMeta>;
}
......
//! [`NullFileSystem`], a filesystem where every path is empty/not-found.
use turbo_rcstr::rcstr;
use turbo_tasks::{ValueToString, Vc};
use crate::{FileContent, FileMeta, FileSystem, FileSystemPath, LinkContent, RawDirectoryContent};
use crate::{
FileContent, FileMeta, FileSystem, FileSystemPath, LinkContent, RawDirectoryContent,
WriteLinkContent,
};
#[derive(ValueToString)]
#[value_to_string("null")]
......@@ -18,7 +22,15 @@ impl FileSystem for NullFileSystem {
#[turbo_tasks::function]
fn read_link(&self, _fs_path: FileSystemPath) -> Vc<LinkContent> {
LinkContent::NotFound.cell()
LinkContent::Invalid {
reason: rcstr!("the filesystem does not support symbolic links"),
}
.cell()
}
#[turbo_tasks::function]
fn is_junction_point(&self, _fs_path: FileSystemPath) -> Vc<bool> {
Vc::cell(false)
}
#[turbo_tasks::function]
......@@ -30,7 +42,7 @@ impl FileSystem for NullFileSystem {
fn write(&self, _fs_path: FileSystemPath, _content: Vc<FileContent>) {}
#[turbo_tasks::function]
fn write_link(&self, _fs_path: FileSystemPath, _target: Vc<LinkContent>) {}
fn write_link(&self, _fs_path: FileSystemPath, _target: Vc<WriteLinkContent>) {}
#[turbo_tasks::function]
fn metadata(&self, _fs_path: FileSystemPath) -> Vc<FileMeta> {
......
......@@ -6,7 +6,7 @@ use anyhow::{Result, bail};
use auto_hash_map::{AutoMap, AutoSet};
use bincode::{Decode, Encode};
use indexmap::IndexSet;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
Completion, NonLocalValue, ResolvedVc, ValueToString, ValueToStringRef, Vc, trace::TraceRawVcs,
turbobail, turbofmt,
......@@ -16,8 +16,8 @@ use turbo_unix_path::{get_parent_path, get_relative_path_to, join_path, normaliz
use crate::{
DirectoryContent, DirectoryEntry, FileContent, FileJsonContent, FileMeta, FileSystem,
FileSystemEntryType, LinkContent, LinkType, RawDirectoryContent, RawDirectoryEntry,
ReadGlobResult,
FileSystemEntryType, LinkContent, RawDirectoryContent, RawDirectoryEntry, ReadGlobResult,
WriteLinkContent,
glob::Glob,
read_glob::{read_glob, track_glob},
};
......@@ -391,6 +391,10 @@ impl FileSystemPath {
self.fs().read_link(self.clone())
}
pub fn is_junction_point(&self) -> Vc<bool> {
self.fs().is_junction_point(self.clone())
}
pub fn read_json(&self) -> Vc<FileJsonContent> {
self.fs().read(self.clone()).parse_json()
}
......@@ -420,24 +424,20 @@ impl FileSystemPath {
self.fs().write(self.clone(), content)
}
/// Creates a symbolic link to a directory on *nix platforms, or a directory junction point on
/// Windows.
/// Creates a symbolic link on *nix platforms. On Windows, directory links are created as
/// junction points. Links to files on Windows are attempted to be created as symbolic links.
///
/// [Windows supports symbolic links][windows-symlink], but they [can require elevated
/// privileges][windows-privileges] if "developer mode" is not enabled, so we can't safely use
/// them. Using junction points [matches the behavior of pnpm][pnpm-windows].
///
/// This only supports directories because Windows junction points are incompatible with files.
/// To ensure compatibility, this will return an error if the target is a file, even on
/// platforms with full symlink support.
///
/// **We intentionally do not provide an API for symlinking a file**, as we cannot support that
/// on all Windows configurations.
/// It is not recommended to create non-directory links, as this is not portable and will likely
/// fail on Windows.
///
/// [windows-symlink]: https://blogs.windows.com/windowsdeveloper/2016/12/02/symlinks-windows-10/
/// [windows-privileges]: https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-10/security/threat-protection/security-policy-settings/create-symbolic-links
/// [pnpm-windows]: https://pnpm.io/faq#does-it-work-on-windows
pub fn write_symbolic_link_dir(&self, target: Vc<LinkContent>) -> Vc<()> {
pub fn write_link(&self, target: Vc<WriteLinkContent>) -> Vc<()> {
self.fs().write_link(self.clone(), target)
}
......@@ -511,8 +511,12 @@ pub struct RealPathResult {
pub enum RealPathResultError {
TooManySymlinks,
CycleDetected,
Invalid,
/// The first symlink that resolution attempted to read no longer exists.
NotFound,
/// Resolution failed after finding a symlink, or the symlink was invalid to begin with.
Invalid {
reason: RcStr,
},
}
impl RealPathResultError {
......@@ -536,12 +540,14 @@ impl RealPathResultError {
);
turbofmt!("Symlink {orig} is in a symlink loop: {symlinks_dbg}").await?
}
RealPathResultError::Invalid => {
turbofmt!("Symlink {orig} is invalid, it points out of the filesystem root").await?
RealPathResultError::Invalid { reason } => {
turbofmt!("Symlink {orig} could not be resolved: {reason}").await?
}
RealPathResultError::NotFound => {
turbofmt!("Symlink {orig} is invalid, it points at a file that doesn't exist")
.await?
turbofmt!(
"Symlink {orig} could not be read because the symlink itself no longer exists"
)
.await?
}
})
}
......@@ -605,6 +611,9 @@ async fn realpath_with_links(path: FileSystemPath) -> Result<Vc<RealPathResult>>
let mut symlinks: IndexSet<FileSystemPath> = IndexSet::new();
let mut visited: AutoSet<RcStr> = AutoSet::new();
let mut error = RealPathResultError::TooManySymlinks;
// Whether a previous iteration resolved a symbolic link, so `current_path` is now a link
// target rather than the path we were asked about.
let mut followed_link = false;
// Pick some arbitrary symlink depth limit... similar to the ELOOP logic for realpath(3).
// SYMLOOP_MAX is 40 for Linux: https://unix.stackexchange.com/q/721724
for _i in 0..40 {
......@@ -630,25 +639,44 @@ async fn realpath_with_links(path: FileSystemPath) -> Result<Vc<RealPathResult>>
.rsplit_once('/')
.map_or(current_path.path.as_str(), |(_, name)| name);
symlinks.extend(parent_result.symlinks);
let parent_path = match parent_result.path_result {
match parent_result.path_result {
Ok(path) => {
if path != parent {
current_path = path.join(basename)?;
}
path
}
Err(parent_error) => {
error = parent_error;
error = match parent_error {
RealPathResultError::NotFound if !symlinks.is_empty() => {
RealPathResultError::Invalid {
reason: rcstr!(
"a symlink encountered while resolving the path no longer exists"
),
}
}
error => error,
};
break;
}
};
}
// use `get_type` before trying `read_link`, as there's a good chance of a cache hit on
// `get_type`, and `read_link` isn't the common codepath.
if !matches!(
*current_path.get_type().await?,
FileSystemEntryType::Symlink
) {
let entry_type = *current_path.get_type().await?;
if !matches!(entry_type, FileSystemEntryType::Symlink) {
// A link we followed points at something that doesn't exist. `read_link` can't detect
// this, as it never looks at the target, so a dangling link reads back as valid.
//
// Only report this for a link we actually followed: resolving a path that simply
// doesn't exist is not an error, it just resolves to itself.
if (followed_link || !symlinks.is_empty())
&& matches!(entry_type, FileSystemEntryType::NotFound)
{
error = RealPathResultError::Invalid {
reason: rcstr!("a symlink target does not exist"),
};
break;
}
return Ok(RealPathResult {
path_result: Ok(current_path),
symlinks: symlinks.into_iter().collect(), // convert set to vec
......@@ -656,22 +684,30 @@ async fn realpath_with_links(path: FileSystemPath) -> Result<Vc<RealPathResult>>
.cell());
}
match &*current_path.read_link().await? {
LinkContent::Link { target, link_type } => {
symlinks.insert(current_path.clone());
current_path = if link_type.contains(LinkType::ABSOLUTE) {
current_path.root().owned().await?
} else {
parent_path
}
.join(target)?;
let link_content = current_path.read_link().await?;
match &*link_content {
LinkContent::Link { target } => {
let target_path = target.file_system_path().clone();
symlinks.insert(current_path);
current_path = target_path;
followed_link = true;
}
LinkContent::NotFound => {
error = RealPathResultError::NotFound;
error = if symlinks.is_empty() {
RealPathResultError::NotFound
} else {
RealPathResultError::Invalid {
reason: rcstr!(
"a symlink encountered while resolving the path no longer exists"
),
}
};
break;
}
LinkContent::Invalid => {
error = RealPathResultError::Invalid;
LinkContent::Invalid { reason } => {
error = RealPathResultError::Invalid {
reason: reason.clone(),
};
break;
}
}
......
......@@ -5,7 +5,8 @@ use turbo_rcstr::RcStr;
use turbo_tasks::{Completion, ResolvedVc, TryJoinIterExt, Vc, turbobail};
use crate::{
DirectoryContent, DirectoryEntry, FileSystem, FileSystemPath, LinkContent, LinkType, glob::Glob,
DirectoryContent, DirectoryEntry, FileSystem, FileSystemEntryType, FileSystemPath, LinkContent,
glob::Glob,
};
#[turbo_tasks::value]
......@@ -85,8 +86,11 @@ async fn read_glob_internal(
handle_dir(&mut result, entry_path, segment, path).await?;
}
DirectoryEntry::Symlink(path) => {
if let LinkContent::Link { link_type, .. } = &*path.read_link().await? {
if link_type.contains(LinkType::DIRECTORY) {
// Skip links that leave the filesystem root.
let link_content = path.read_link().await?;
if let LinkContent::Link { target } = &*link_content {
if matches!(target.target_type().await?, FileSystemEntryType::Directory)
{
// Ensure that there are no infinite link loops, but don't resolve
resolve_symlink_safely(entry.clone()).await?;
......
......@@ -2,7 +2,10 @@ use anyhow::{Result, bail};
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ValueToString, Vc};
use crate::{FileContent, FileMeta, FileSystem, FileSystemPath, LinkContent, RawDirectoryContent};
use crate::{
FileContent, FileMeta, FileSystem, FileSystemPath, LinkContent, RawDirectoryContent,
WriteLinkContent,
};
#[derive(ValueToString)]
#[value_to_string(self.name)]
......@@ -51,6 +54,11 @@ impl FileSystem for VirtualFileSystem {
bail!("Reading is not possible on the virtual file system")
}
#[turbo_tasks::function]
fn is_junction_point(&self, _fs_path: FileSystemPath) -> Result<Vc<bool>> {
bail!("Reading is not possible on the virtual file system")
}
#[turbo_tasks::function]
fn raw_read_dir(&self, _fs_path: FileSystemPath) -> Result<Vc<RawDirectoryContent>> {
bail!("Reading is not possible on the virtual file system")
......@@ -62,7 +70,11 @@ impl FileSystem for VirtualFileSystem {
}
#[turbo_tasks::function]
fn write_link(&self, _fs_path: FileSystemPath, _target: Vc<LinkContent>) -> Result<Vc<()>> {
fn write_link(
&self,
_fs_path: FileSystemPath,
_target: Vc<WriteLinkContent>,
) -> Result<Vc<()>> {
bail!("Writing is not possible on the virtual file system")
}
......
use std::path::{Path, PathBuf};
use std::{
ffi::OsString,
io, mem,
os::windows::ffi::{OsStrExt, OsStringExt},
path::{Component, Path, PathBuf, Prefix},
ptr::{null, null_mut},
};
use omnipath::WinPathExt;
use windows_sys::Win32::{
Foundation::{CloseHandle, INVALID_HANDLE_VALUE},
Storage::FileSystem::{
CreateFileW, FILE_ATTRIBUTE_TAG_INFO, FILE_FLAG_BACKUP_SEMANTICS,
FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
FileAttributeTagInfo, GetFileInformationByHandleEx, OPEN_EXISTING,
},
System::SystemServices::IO_REPARSE_TAG_MOUNT_POINT,
};
pub(crate) fn is_link_junction_point(path: &Path) -> io::Result<bool> {
let path: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
let handle = unsafe {
CreateFileW(
path.as_ptr(),
0,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
null(),
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
null_mut(),
)
};
if handle == INVALID_HANDLE_VALUE {
return Err(io::Error::last_os_error());
}
let mut tag_info = FILE_ATTRIBUTE_TAG_INFO {
FileAttributes: 0,
ReparseTag: 0,
};
let result = unsafe {
GetFileInformationByHandleEx(
handle,
FileAttributeTagInfo,
(&mut tag_info as *mut FILE_ATTRIBUTE_TAG_INFO).cast(),
mem::size_of::<FILE_ATTRIBUTE_TAG_INFO>() as u32,
)
};
let error = if result == 0 {
Some(io::Error::last_os_error())
} else {
None
};
unsafe {
CloseHandle(handle);
}
error.map_or(Ok(tag_info.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT), Err)
}
/// Converts `path` into the verbatim, drive-letter-case-folded representation used internally by
/// [`crate::DiskFileSystem`] on Windows.
......@@ -8,57 +65,41 @@ use std::path::{Path, PathBuf};
/// `canonicalize`, does not touch the disk — it resolves neither symlinks nor 8.3 short names. The
/// drive letter is then upper-cased to match the form `GetFinalPathNameByHandle` (and thus
/// `canonicalize`) produces.
///
/// No-op on non-Windows platforms (returns `path` unchanged).
pub fn to_verbatim_with_case_folded_disk(path: &Path) -> std::io::Result<PathBuf> {
#[cfg(windows)]
{
use std::{
ffi::OsString,
os::windows::ffi::{OsStrExt, OsStringExt},
path::{Component, Prefix},
};
use omnipath::WinPathExt;
pub fn to_verbatim_with_case_folded_disk(path: &Path) -> io::Result<PathBuf> {
// `to_verbatim` guarantees an absolute, verbatim path from here on, so there's no
// non-verbatim case to guard against below.
let path = path.to_verbatim()?;
// `to_verbatim` guarantees an absolute, verbatim path from here on, so there's no
// non-verbatim case to guard against below.
let path = path.to_verbatim()?;
// Only `\\?\C:\...` (`VerbatimDisk`) paths carry a drive letter; verbatim UNC
// (`\\?\UNC\...`) and other verbatim device paths (`\\?\prefix`) don't, so there's nothing
// to case-fold for those.
//
// We can't read the letter from `VerbatimDisk(disk)` because that value is already
// normalized to uppercase, so it wouldn't tell us whether the underlying path needs
// rewriting.
let is_verbatim_disk = matches!(
path.components().next(),
Some(Component::Prefix(prefix)) if matches!(prefix.kind(), Prefix::VerbatimDisk(_))
);
if !is_verbatim_disk {
return Ok(path);
}
// The layout is `\\?\C:\...`, so the drive letter is the 5th UTF-16 code unit (index 4)
// and is guaranteed to be a-z or A-Z.
if let Some(disk) = path.as_os_str().encode_wide().nth(4).map(|disk| disk as u8)
&& disk.is_ascii_lowercase()
{
// we must encode/decode because OsString's internal encoding is opaque/unstable
let mut wide: Vec<u16> = path.as_os_str().encode_wide().collect();
wide[4] = u16::from(disk.to_ascii_uppercase());
return Ok(PathBuf::from(OsString::from_wide(&wide)));
}
// Only `\\?\C:\...` (`VerbatimDisk`) paths carry a drive letter; verbatim UNC
// (`\\?\UNC\...`) and other verbatim device paths (`\\?\prefix`) don't, so there's nothing
// to case-fold for those.
//
// We can't read the letter from `VerbatimDisk(disk)` because that value is already
// normalized to uppercase, so it wouldn't tell us whether the underlying path needs
// rewriting.
let is_verbatim_disk = matches!(
path.components().next(),
Some(Component::Prefix(prefix)) if matches!(prefix.kind(), Prefix::VerbatimDisk(_))
);
if !is_verbatim_disk {
return Ok(path);
}
Ok(path)
// The layout is `\\?\C:\...`, so the drive letter is the 5th UTF-16 code unit (index 4)
// and is guaranteed to be a-z or A-Z.
if let Some(disk) = path.as_os_str().encode_wide().nth(4).map(|disk| disk as u8)
&& disk.is_ascii_lowercase()
{
// we must encode/decode because OsString's internal encoding is opaque/unstable
let mut wide: Vec<u16> = path.as_os_str().encode_wide().collect();
wide[4] = u16::from(disk.to_ascii_uppercase());
return Ok(PathBuf::from(OsString::from_wide(&wide)));
}
#[cfg(not(windows))]
Ok(path.to_path_buf())
Ok(path)
}
#[cfg(all(test, windows))]
#[cfg(test)]
mod tests {
use std::path::Path;
......@@ -87,4 +128,18 @@ mod tests {
r"\\?\UNC\server\share\foo"
);
}
#[test]
fn identifies_junction_points() {
let scratch = tempfile::tempdir().unwrap();
let target = scratch.path().join("target");
let link = scratch.path().join("link");
let file = scratch.path().join("file");
std::fs::create_dir(&target).unwrap();
std::fs::File::create(&file).unwrap();
std::os::windows::fs::junction_point(&target, &link).unwrap();
assert!(is_link_junction_point(&link).unwrap());
assert!(!is_link_junction_point(&file).unwrap());
}
}
......@@ -20,7 +20,8 @@ use turbo_tasks::{
};
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbo_tasks_fs::{
DiskFileSystem, File, FileContent, FileSystem, FileSystemPath, LinkContent, LinkType,
DiskFileSystem, File, FileContent, FileSystem, FileSystemPath, WriteLinkContent,
WriteLinkTarget, WriteLinkTargetType,
};
// `read_or_write_all_paths_operation` always writes the sentinel values to files/symlinks. We can
......@@ -76,12 +77,12 @@ enum SymlinkMode {
}
impl SymlinkMode {
fn to_link_type(self) -> LinkType {
fn is_directory(self) -> bool {
match self {
SymlinkMode::File => LinkType::empty(),
SymlinkMode::Directory => LinkType::DIRECTORY,
SymlinkMode::File => false,
SymlinkMode::Directory => true,
#[cfg(windows)]
SymlinkMode::Junction => LinkType::DIRECTORY,
SymlinkMode::Junction => true,
}
}
}
......@@ -139,8 +140,7 @@ pub async fn run(args: FsWatcher) -> anyhow::Result<()> {
};
let track_writes = args.track_writes;
let symlink_mode = args.symlinks;
let symlink_is_directory =
symlink_mode.map(|m| m.to_link_type().contains(LinkType::DIRECTORY));
let symlink_is_directory = symlink_mode.map(SymlinkMode::is_directory);
let effects_op = extract_effects_operation(read_or_write_all_paths_operation(
invalidations.clone(),
......@@ -348,12 +348,14 @@ async fn write_link(
) -> anyhow::Result<()> {
let path_str = path.path.clone();
invalidations.0.lock().unwrap().insert(path_str);
let link_type = if is_directory {
LinkType::DIRECTORY
} else {
LinkType::empty()
let link_content = WriteLinkContent {
target: WriteLinkTarget::Relative(target),
target_type: if is_directory {
WriteLinkTargetType::DirectoryOrJunctionPoint
} else {
WriteLinkTargetType::FileNonPortable
},
};
let link_content = LinkContent::Link { target, link_type };
let _ = path
.fs()
.write_link(path.clone(), link_content.cell())
......
......@@ -13,7 +13,10 @@ use turbo_tasks::{
read_strongly_consistent_and_apply_effects, take_effects,
};
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbo_tasks_fs::{DiskFileSystem, FileSystem, FileSystemPath, LinkContent, LinkType};
use turbo_tasks_fs::{
DiskFileSystem, FileSystem, FileSystemPath, WriteLinkContent, WriteLinkTarget,
WriteLinkTargetType,
};
#[derive(Args)]
pub struct SymlinkStress {
......@@ -40,6 +43,15 @@ async fn extract_effects_operation(op: OperationVc<()>) -> anyhow::Result<Vc<Eff
}
pub async fn run(args: SymlinkStress) -> anyhow::Result<()> {
// Each batch writes `parallelism` distinct symlinks, so there must be enough to go around.
if args.parallelism > args.symlink_count {
anyhow::bail!(
"--parallelism ({}) must not exceed --symlink-count ({}), since a batch cannot write \
the same symlink twice",
args.parallelism,
args.symlink_count,
);
}
std::fs::create_dir(&args.fs_root)?;
let fs_root = args.fs_root.canonicalize()?;
let _guard = FsCleanup {
......@@ -58,7 +70,12 @@ pub async fn run(args: SymlinkStress) -> anyhow::Result<()> {
std::fs::create_dir(&symlinks_dir)?;
let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
BackendOptions::default(),
BackendOptions {
// `noop_backing_storage` is read-only, so asking to persist on shutdown (the default)
// just fails with "Cannot perform write operations on a read-only database".
storage_mode: None,
..Default::default()
},
noop_backing_storage(),
));
......@@ -102,6 +119,8 @@ pub async fn run(args: SymlinkStress) -> anyhow::Result<()> {
);
let mut rng = rand::rngs::SmallRng::from_rng(&mut rand::rng());
// Reused across batches; each batch partially shuffles it to sample distinct symlinks.
let mut symlink_indices: Vec<usize> = (0..symlink_count).collect();
let mut total_writes: u64 = 0;
let mut last_progress_writes: u64 = 0;
let start_time = Instant::now();
......@@ -113,13 +132,18 @@ pub async fn run(args: SymlinkStress) -> anyhow::Result<()> {
break;
}
// Generate random symlink updates for this batch
let updates: Vec<(usize, usize)> = (0..parallelism)
.map(|_| {
let symlink_idx = rng.random_range(0..symlink_count);
let target_idx = rng.random_range(0..target_count);
(symlink_idx, target_idx)
})
// Pick `parallelism` *distinct* symlinks for this batch, via a partial Fisher-Yates
// shuffle. They must be distinct because writing two different targets to one path
// within a single operation is a conflicting effect: a usage error, not something to
// stress test. Sampling without replacement (rather than deduplicating) keeps the
// batch size exactly `parallelism`, so the reported concurrency is honest.
for i in 0..parallelism {
let j = rng.random_range(i..symlink_count);
symlink_indices.swap(i, j);
}
let updates: Vec<(usize, usize)> = symlink_indices[..parallelism]
.iter()
.map(|&symlink_idx| (symlink_idx, rng.random_range(0..target_count)))
.collect();
// Execute writes in parallel via turbo-tasks
......@@ -169,17 +193,17 @@ pub async fn run(args: SymlinkStress) -> anyhow::Result<()> {
Ok(())
}
#[turbo_tasks::function(operation)]
#[turbo_tasks::function(operation, root)]
fn disk_file_system_operation(fs_root: RcStr) -> Vc<DiskFileSystem> {
DiskFileSystem::new(rcstr!("project"), Vc::cell(fs_root))
}
#[turbo_tasks::function(operation)]
#[turbo_tasks::function(operation, root)]
fn disk_file_system_root_operation(fs: ResolvedVc<DiskFileSystem>) -> Vc<FileSystemPath> {
fs.root()
}
#[turbo_tasks::function(operation)]
#[turbo_tasks::function(operation, root)]
async fn create_initial_symlinks_operation(
symlinks_dir: FileSystemPath,
count: usize,
......@@ -192,7 +216,7 @@ async fn create_initial_symlinks_operation(
Ok(())
}
#[turbo_tasks::function(operation)]
#[turbo_tasks::function(operation, root)]
async fn write_symlinks_batch_operation(
symlinks_dir: FileSystemPath,
updates: Vec<(usize, usize)>,
......@@ -215,9 +239,9 @@ async fn write_symlink(
target: RcStr,
) -> anyhow::Result<()> {
let symlink_path = symlinks_dir.join(&symlink_idx.to_string())?;
let link_content = LinkContent::Link {
target,
link_type: LinkType::DIRECTORY,
let link_content = WriteLinkContent {
target: WriteLinkTarget::Relative(target),
target_type: WriteLinkTargetType::DirectoryOrJunctionPoint,
};
symlink_path
.fs()
......
......@@ -10,28 +10,27 @@ use crate::expand::{generate_exhaustive_destructuring, match_expansion};
///
/// This requires that every contained value also implement `DeterministicHash`.
pub fn derive_deterministic_hash(input: TokenStream) -> TokenStream {
let derive_input = parse_macro_input!(input as DeriveInput);
let ident = &derive_input.ident;
let match_hash = match_expansion(
let DeriveInput {
ident,
&derive_input.data,
&hash_named,
&hash_unnamed,
&hash_unit,
);
let discriminant = match derive_input.data {
generics,
data,
..
} = parse_macro_input!(input as DeriveInput);
let match_hash = match_expansion(&ident, &data, &hash_named, &hash_unnamed, &hash_unit);
let discriminant = match data {
Data::Enum(_) => {
quote! {
turbo_tasks_hash::DeterministicHash::deterministic_hash(&std::mem::discriminant(self), __state__);
::turbo_tasks_hash::DeterministicHash::deterministic_hash(&std::mem::discriminant(self), __state__);
}
}
_ => quote! {},
};
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
quote! {
#[automatically_derived]
impl turbo_tasks_hash::DeterministicHash for #ident {
impl #impl_generics ::turbo_tasks_hash::DeterministicHash for #ident #ty_generics #where_clause {
fn deterministic_hash<H: turbo_tasks_hash::DeterministicHasher>(&self, __state__: &mut H) {
#discriminant
#match_hash
......
......@@ -6,11 +6,11 @@ use std::borrow::Cow;
/// directory separators with forward slashes on Windows.
#[inline]
pub fn sys_to_unix(path: &str) -> Cow<'_, str> {
#[cfg(not(target_family = "windows"))]
#[cfg(not(windows))]
{
Cow::from(path)
}
#[cfg(target_family = "windows")]
#[cfg(windows)]
{
Cow::Owned(path.replace(std::path::MAIN_SEPARATOR_STR, "/"))
}
......@@ -20,11 +20,11 @@ pub fn sys_to_unix(path: &str) -> Cow<'_, str> {
/// slash directory separators with backslashes on Windows.
#[inline]
pub fn unix_to_sys(path: &str) -> Cow<'_, str> {
#[cfg(not(target_family = "windows"))]
#[cfg(not(windows))]
{
Cow::from(path)
}
#[cfg(target_family = "windows")]
#[cfg(windows)]
{
Cow::Owned(path.replace('/', std::path::MAIN_SEPARATOR_STR))
}
......@@ -36,10 +36,8 @@ pub fn unix_to_sys(path: &str) -> Cow<'_, str> {
/// see also [normalize_path] for normalization.
/// Returns `None` if the joined path would leave the filesystem root.
pub fn join_path(fs_path: &str, join: &str) -> Option<String> {
// Paths that we join are written as source code (eg, `join_path(fs_path, "foo/bar.js")`) and
// it's expected that they will never contain a backslash.
debug_assert!(
!join.contains('\\'),
!cfg!(windows) || !join.contains('\\'),
"joined path {join} must not contain a Windows directory '\\', it must be normalized to \
Unix '/'"
);
......
......@@ -2,7 +2,7 @@ use anyhow::Result;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::{
FileContent, FileJsonContent, FileLinesContent, FileSystemPath, LinkContent, LinkType,
FileContent, FileJsonContent, FileLinesContent, FileSystemPath, WriteLinkContent,
};
use turbo_tasks_hash::{HashAlgorithm, deterministic_hash};
......@@ -52,10 +52,8 @@ pub trait Asset {
#[derive(Clone)]
pub enum AssetContent {
File(ResolvedVc<FileContent>),
// for the relative link, the target is raw value read from the link
// for the absolute link, the target is stripped of the root path while reading
// See [LinkContent::Link] for more details.
Redirect { target: RcStr, link_type: LinkType },
/// A symbolic link. See [`WriteLinkContent`] for how it is written.
Redirect(WriteLinkContent),
}
#[turbo_tasks::value_impl]
......@@ -69,7 +67,7 @@ impl AssetContent {
pub fn parse_json(&self) -> Vc<FileJsonContent> {
match self {
AssetContent::File(content) => content.parse_json(),
AssetContent::Redirect { .. } => {
AssetContent::Redirect(..) => {
FileJsonContent::unparsable(rcstr!("a redirect can't be parsed as json")).cell()
}
}
......@@ -79,7 +77,7 @@ impl AssetContent {
pub fn file_content(&self) -> Vc<FileContent> {
match self {
AssetContent::File(content) => **content,
AssetContent::Redirect { .. } => FileContent::NotFound.cell(),
AssetContent::Redirect(..) => FileContent::NotFound.cell(),
}
}
......@@ -87,7 +85,7 @@ impl AssetContent {
pub fn lines(&self) -> Vc<FileLinesContent> {
match self {
AssetContent::File(content) => content.lines(),
AssetContent::Redirect { .. } => FileLinesContent::Unparsable.cell(),
AssetContent::Redirect(..) => FileLinesContent::Unparsable.cell(),
}
}
......@@ -95,7 +93,7 @@ impl AssetContent {
pub fn len(&self) -> Vc<Option<u64>> {
match self {
AssetContent::File(content) => content.len(),
AssetContent::Redirect { .. } => Vc::cell(None),
AssetContent::Redirect(..) => Vc::cell(None),
}
}
......@@ -103,7 +101,7 @@ impl AssetContent {
pub fn parse_json_with_comments(&self) -> Vc<FileJsonContent> {
match self {
AssetContent::File(content) => content.parse_json_with_comments(),
AssetContent::Redirect { .. } => {
AssetContent::Redirect(..) => {
FileJsonContent::unparsable(rcstr!("a redirect can't be parsed as json")).cell()
}
}
......@@ -115,16 +113,10 @@ impl AssetContent {
AssetContent::File(file) => {
path.write(**file).as_side_effect().await?;
}
AssetContent::Redirect { target, link_type } => {
path.write_symbolic_link_dir(
LinkContent::Link {
target: target.clone(),
link_type: *link_type,
}
.cell(),
)
.as_side_effect()
.await?;
AssetContent::Redirect(content) => {
path.write_link(content.clone().cell())
.as_side_effect()
.await?;
}
}
Ok(())
......@@ -134,9 +126,9 @@ impl AssetContent {
pub async fn hash(&self, salt: Vc<RcStr>, algorithm: HashAlgorithm) -> Result<Vc<RcStr>> {
Ok(match self {
AssetContent::File(content) => content.hash(salt, algorithm),
AssetContent::Redirect { target, link_type } => Vc::cell(RcStr::from(
AssetContent::Redirect(content) => Vc::cell(RcStr::from(
// no_hash_salt
deterministic_hash(&salt.await?, (target, link_type), algorithm),
deterministic_hash(&salt.await?, content, algorithm),
)),
})
}
......@@ -154,7 +146,7 @@ impl AssetContent {
) -> Result<Vc<Option<RcStr>>> {
match self {
AssetContent::File(content) => Ok(content.content_hash(salt, algorithm)),
AssetContent::Redirect { .. } => Ok(Vc::cell(None)),
AssetContent::Redirect(..) => Ok(Vc::cell(None)),
}
}
}
use anyhow::{Result, bail};
use turbo_rcstr::RcStr;
use turbo_tasks::Vc;
use turbo_tasks_fs::{FileContent, FileSystemEntryType, FileSystemPath, LinkContent};
use turbo_tasks_fs::{
FileContent, FileSystemEntryType, FileSystemPath, LinkContent, LinkTarget, WriteLinkContent,
WriteLinkTarget, WriteLinkTargetType,
};
use crate::{
asset::{Asset, AssetContent},
......@@ -66,11 +69,31 @@ impl Asset for FileSource {
let file_type = &*self.path.get_type().await?;
match file_type {
FileSystemEntryType::Symlink => match &*self.path.read_link().await? {
LinkContent::Link { target, link_type } => Ok(AssetContent::Redirect {
target: target.clone(),
link_type: *link_type,
LinkContent::Link { target } => {
let write_target = match target {
LinkTarget::Absolute { resolved } => {
WriteLinkTarget::Absolute(resolved.path.clone())
}
LinkTarget::Relative { raw, .. } => WriteLinkTarget::Relative(raw.clone()),
};
let target_fs_path = target.file_system_path();
let write_target_type = match *target_fs_path.get_type().await? {
FileSystemEntryType::Directory => {
WriteLinkTargetType::DirectoryOrJunctionPoint
}
FileSystemEntryType::Symlink
if *target_fs_path.is_junction_point().await? =>
{
WriteLinkTargetType::DirectoryOrJunctionPoint
}
_ => WriteLinkTargetType::FileNonPortable,
};
Ok(AssetContent::Redirect(WriteLinkContent {
target: write_target,
target_type: write_target_type,
})
.cell())
}
.cell()),
_ => bail!("Invalid symlink"),
},
FileSystemEntryType::File => {
......
......@@ -54,9 +54,7 @@ pub async fn content_to_details(content: Vc<AssetContent>) -> Result<Vc<RcStr>>
}
FileContent::NotFound => Vc::cell(rcstr!("not found")),
},
AssetContent::Redirect { target, link_type } => {
Vc::cell(format!("redirect to {target} with type {link_type:?}").into())
}
AssetContent::Redirect(content) => Vc::cell(format!("redirect to {content:?}").into()),
})
}
......
......@@ -14,7 +14,7 @@ use turbo_tasks::{
NonLocalValue, TaskInput, ValueToString, Vc, debug::ValueDebugFormat, trace::TraceRawVcs,
};
use turbo_tasks_fs::{
FileSystemPath, LinkContent, LinkType, RawDirectoryContent, RawDirectoryEntry,
FileSystemEntryType, FileSystemPath, LinkContent, RawDirectoryContent, RawDirectoryEntry,
};
use turbo_unix_path::normalize_path;
......@@ -1606,12 +1606,12 @@ pub async fn read_matches(
)),
RawDirectoryEntry::Symlink => {
let fs_path = parent_fs_path.join(last_segment)?;
let LinkContent::Link { link_type, .. } = &*fs_path.read_link().await?
else {
let LinkContent::Link { target } = &*fs_path.read_link().await? else {
continue;
};
let path = concat(&prefix, str).into();
if link_type.contains(LinkType::DIRECTORY) {
if matches!(target.target_type().await?, FileSystemEntryType::Directory)
{
results.push((index, PatternMatch::Directory(path, fs_path)));
} else {
results.push((index, PatternMatch::File(path, fs_path)))
......@@ -1795,10 +1795,13 @@ pub async fn read_matches(
}
if let Some(pos) = pat.match_position(&prefix) {
let fs_path = lookup_dir.join(key)?;
if let LinkContent::Link { link_type, .. } =
if let LinkContent::Link { target } =
&*fs_path.read_link().await?
{
if link_type.contains(LinkType::DIRECTORY) {
if matches!(
target.target_type().await?,
FileSystemEntryType::Directory
) {
results.push((
pos,
PatternMatch::Directory(
......@@ -1817,9 +1820,12 @@ pub async fn read_matches(
prefix.push('/');
if let Some(pos) = pat.match_position(&prefix) {
let fs_path = lookup_dir.join(key)?;
if let LinkContent::Link { link_type, .. } =
if let LinkContent::Link { target } =
&*fs_path.read_link().await?
&& link_type.contains(LinkType::DIRECTORY)
&& matches!(
target.target_type().await?,
FileSystemEntryType::Directory
)
{
results.push((
pos,
......@@ -1829,9 +1835,12 @@ pub async fn read_matches(
}
if let Some(pos) = pat.could_match_position(&prefix) {
let fs_path = lookup_dir.join(key)?;
if let LinkContent::Link { link_type, .. } =
if let LinkContent::Link { target } =
&*fs_path.read_link().await?
&& link_type.contains(LinkType::DIRECTORY)
&& matches!(
target.target_type().await?,
FileSystemEntryType::Directory
)
{
results.push((
pos,
......
......@@ -2,6 +2,7 @@ use anyhow::{Result, bail};
use turbo_tasks::{ValueToString, Vc};
use turbo_tasks_fs::{
FileContent, FileMeta, FileSystem, FileSystemPath, LinkContent, RawDirectoryContent,
WriteLinkContent,
};
#[turbo_tasks::value]
......@@ -29,6 +30,11 @@ impl FileSystem for ServerFileSystem {
bail!("Reading is not possible from the marker filesystem for the server")
}
#[turbo_tasks::function]
fn is_junction_point(&self, _fs_path: FileSystemPath) -> Result<Vc<bool>> {
bail!("Reading is not possible from the marker filesystem for the server")
}
#[turbo_tasks::function]
fn raw_read_dir(&self, _fs_path: FileSystemPath) -> Result<Vc<RawDirectoryContent>> {
bail!("Reading is not possible from the marker filesystem for the server")
......@@ -40,7 +46,11 @@ impl FileSystem for ServerFileSystem {
}
#[turbo_tasks::function]
fn write_link(&self, _fs_path: FileSystemPath, _target: Vc<LinkContent>) -> Result<Vc<()>> {
fn write_link(
&self,
_fs_path: FileSystemPath,
_target: Vc<WriteLinkContent>,
) -> Result<Vc<()>> {
bail!("Writing is not possible to the marker filesystem for the server")
}
......
......@@ -234,7 +234,7 @@ impl FileHashVersion {
.context("file not found")?;
Ok(Self::cell(FileHashVersion { hash }))
}
AssetContent::Redirect { .. } => bail!("not a file"),
AssetContent::Redirect(..) => bail!("not a file"),
}
}
}
......
......@@ -378,7 +378,7 @@ pub async fn parse_css(
let content = source.content();
let ident_str = &*source.ident().to_string().await?;
Ok(match &*content.await? {
AssetContent::Redirect { .. } => ParseCssResult::Unparsable.cell(),
AssetContent::Redirect(..) => ParseCssResult::Unparsable.cell(),
AssetContent::File(file_content) => match &*file_content.await? {
FileContent::NotFound => ParseCssResult::NotFound.cell(),
FileContent::Content(file) => match file.content().to_str() {
......
......@@ -372,7 +372,7 @@ async fn parse_internal(
}
}
},
AssetContent::Redirect { .. } => ParseResult::Unparsable { messages: None }.cell(),
AssetContent::Redirect(..) => ParseResult::Unparsable { messages: None }.cell(),
})
}
......
......@@ -4,7 +4,10 @@ use anyhow::{Context, Result};
use bincode::{Decode, Encode};
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TryJoinIterExt, ValueToStringRef, Vc, trace::TraceRawVcs};
use turbo_tasks_fs::{FileSystem, FileSystemPath, LinkType, VirtualFileSystem, rope::RopeBuilder};
use turbo_tasks_fs::{
FileSystem, FileSystemPath, VirtualFileSystem, WriteLinkContent, WriteLinkTarget,
WriteLinkTargetType, rope::RopeBuilder,
};
use turbo_tasks_hash::{encode_hex, hash_xxh3_hash64};
use turbopack_core::{
asset::{Asset, AssetContent},
......@@ -508,10 +511,10 @@ impl Asset for ExternalsSymlinkAsset {
)
.into();
Ok(AssetContent::Redirect {
target,
link_type: LinkType::DIRECTORY,
}
Ok(AssetContent::Redirect(WriteLinkContent {
target: WriteLinkTarget::Relative(target),
target_type: WriteLinkTargetType::DirectoryOrJunctionPoint,
})
.cell())
}
}
......@@ -169,9 +169,7 @@ async fn get_contents(file: Vc<AssetContent>) -> Result<Option<String>> {
}
}
},
AssetContent::Redirect { target, link_type } => Some(format!(
"Redirect {{ target: {target}, link_type: {link_type:?} }}"
)),
AssetContent::Redirect(content) => Some(format!("Redirect {content:?}")),
})
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment