add vendor dir name param

This commit is contained in:
stelzo 2025-01-22 01:19:19 +01:00
parent 9256871d62
commit 476b79ddfc
No known key found for this signature in database
GPG Key ID: FC4EF89052319374
6 changed files with 56 additions and 31 deletions

View File

@ -361,6 +361,14 @@ pub struct PackageArgs {
value_name = "DIR" value_name = "DIR"
)] )]
pub package_cache_path: Option<PathBuf>, pub package_cache_path: Option<PathBuf>,
/// Custom vendor directory name.
#[clap(
long = "package-vendor-path",
env = "TYPST_PACKAGE_VENDOR_PATH",
value_name = "DIR"
)]
pub vendor_path: Option<PathBuf>,
} }
/// Common arguments to customize available fonts. /// Common arguments to customize available fonts.

View File

@ -15,7 +15,7 @@ use crate::package;
/// Execute an initialization command. /// Execute an initialization command.
pub fn init(command: &InitCommand) -> StrResult<()> { pub fn init(command: &InitCommand) -> StrResult<()> {
let package_storage = package::storage(&command.package); let package_storage = package::storage(&command.package, None);
// Parse the package specification. If the user didn't specify the version, // Parse the package specification. If the user didn't specify the version,
// we try to figure it out automatically by downloading the package index // we try to figure it out automatically by downloading the package index
@ -28,9 +28,9 @@ pub fn init(command: &InitCommand) -> StrResult<()> {
StrResult::Ok(spec.at(version)) StrResult::Ok(spec.at(version))
})?; })?;
// Find or download the package. Vendoring does not make sense for initialization, so project_root is not needed. // Find or download the package. Vendoring does not make sense for initialization, so vendor_dir is not needed.
let package_path = let package_path =
package_storage.prepare_package(&spec, &mut PrintDownload(&spec), None)?; package_storage.prepare_package(&spec, &mut PrintDownload(&spec))?;
// Parse the manifest. // Parse the manifest.
let manifest = parse_manifest(&package_path)?; let manifest = parse_manifest(&package_path)?;

View File

@ -1,13 +1,17 @@
use std::path::PathBuf;
use typst_kit::package::PackageStorage; use typst_kit::package::PackageStorage;
use crate::args::PackageArgs; use crate::args::PackageArgs;
use crate::download; use crate::download;
/// Returns a new package storage for the given args. /// Returns a new package storage for the given args.
pub fn storage(args: &PackageArgs) -> PackageStorage { pub fn storage(args: &PackageArgs, workdir: Option<PathBuf>) -> PackageStorage {
PackageStorage::new( PackageStorage::new(
args.vendor_path.clone(),
args.package_cache_path.clone(), args.package_cache_path.clone(),
args.package_path.clone(), args.package_path.clone(),
download::downloader(), download::downloader(),
workdir,
) )
} }

View File

@ -1,4 +1,7 @@
use std::fs::{create_dir, create_dir_all}; use std::{
fs::{create_dir, create_dir_all},
path::PathBuf,
};
use ecow::eco_format; use ecow::eco_format;
use typst::{ use typst::{
@ -24,7 +27,7 @@ pub fn vendor(command: &VendorCommand) -> HintedStrResult<()> {
match output { match output {
Ok(_) => { Ok(_) => {
copy_deps(&mut world)?; copy_deps(&mut world, &command.world.package.vendor_path)?;
print_diagnostics(&world, &[], &warnings, command.process.diagnostic_format) print_diagnostics(&world, &[], &warnings, command.process.diagnostic_format)
.map_err(|err| eco_format!("failed to print diagnostics ({err})"))?; .map_err(|err| eco_format!("failed to print diagnostics ({err})"))?;
} }
@ -45,20 +48,26 @@ pub fn vendor(command: &VendorCommand) -> HintedStrResult<()> {
Ok(()) Ok(())
} }
fn copy_deps(world: &mut SystemWorld) -> HintedStrResult<()> { fn copy_deps(
let vendor_dir = world.workdir().join(DEFAULT_VENDOR_SUBDIR); world: &mut SystemWorld,
vendor_path: &Option<PathBuf>,
match vendor_dir.try_exists() { ) -> HintedStrResult<()> {
Ok(false) => { let vendor_dir = match vendor_path {
if let Err(err) = create_dir(vendor_dir.clone()) { Some(path) => match path.canonicalize() {
bail!("failed to create vendor directory: {:?}", err); Ok(path) => path,
Err(err) => {
if err.kind() == std::io::ErrorKind::NotFound {
if let Err(err) = create_dir(path) {
bail!("failed to create vendor directory: {:?}", err);
}
path.clone()
} else {
bail!("failed to canonicalize vendor directory path: {:?}", err);
}
} }
} },
Err(err) => { None => world.workdir().join(DEFAULT_VENDOR_SUBDIR),
bail!("failed to check existence of vendor directory: {:?}", err); };
}
_ => {}
}
// Must iterate two times in total. As soon as the parent directory is created, // Must iterate two times in total. As soon as the parent directory is created,
// world tries to read the subsequent files from the same package // world tries to read the subsequent files from the same package

View File

@ -29,7 +29,7 @@ static STDIN_ID: LazyLock<FileId> =
/// A world that provides access to the operating system. /// A world that provides access to the operating system.
pub struct SystemWorld { pub struct SystemWorld {
/// The working directory. /// The working directory.
workdir: Option<PathBuf>, workdir: PathBuf,
/// The root relative to which absolute paths are resolved. /// The root relative to which absolute paths are resolved.
root: PathBuf, root: PathBuf,
/// The input path. /// The input path.
@ -132,15 +132,18 @@ impl SystemWorld {
None => Now::System(OnceLock::new()), None => Now::System(OnceLock::new()),
}; };
let env_workdir = std::env::current_dir().ok();
let workdir = env_workdir.unwrap_or(PathBuf::from("."));
Ok(Self { Ok(Self {
workdir: std::env::current_dir().ok(), workdir: workdir.clone(),
root, root,
main, main,
library: LazyHash::new(library), library: LazyHash::new(library),
book: LazyHash::new(fonts.book), book: LazyHash::new(fonts.book),
fonts: fonts.fonts, fonts: fonts.fonts,
slots: Mutex::new(HashMap::new()), slots: Mutex::new(HashMap::new()),
package_storage: package::storage(&world_args.package), package_storage: package::storage(&world_args.package, Some(workdir)),
now, now,
}) })
} }
@ -157,7 +160,7 @@ impl SystemWorld {
/// The current working directory. /// The current working directory.
pub fn workdir(&self) -> &Path { pub fn workdir(&self) -> &Path {
self.workdir.as_deref().unwrap_or(Path::new(".")) self.workdir.as_path()
} }
/// Return all paths the last compilation depended on. /// Return all paths the last compilation depended on.
@ -380,12 +383,9 @@ fn system_path(
// will be resolved. // will be resolved.
let buf; let buf;
let mut root = project_root; let mut root = project_root;
if let Some(spec) = id.package() { if let Some(spec) = id.package() {
buf = package_storage.prepare_package( buf = package_storage.prepare_package(spec, &mut PrintDownload(&spec))?;
spec,
&mut PrintDownload(&spec),
Some(root),
)?;
root = &buf; root = &buf;
} }

View File

@ -28,6 +28,8 @@ pub const DEFAULT_VENDOR_SUBDIR: &str = "vendor";
/// on demand, if possible. /// on demand, if possible.
#[derive(Debug)] #[derive(Debug)]
pub struct PackageStorage { pub struct PackageStorage {
/// The path at which packages are stored by the vendor command.
package_vendor_path: Option<PathBuf>,
/// The path at which non-local packages should be stored when downloaded. /// The path at which non-local packages should be stored when downloaded.
package_cache_path: Option<PathBuf>, package_cache_path: Option<PathBuf>,
/// The path at which local packages are stored. /// The path at which local packages are stored.
@ -42,11 +44,15 @@ impl PackageStorage {
/// Creates a new package storage for the given package paths. Falls back to /// Creates a new package storage for the given package paths. Falls back to
/// the recommended XDG directories if they are `None`. /// the recommended XDG directories if they are `None`.
pub fn new( pub fn new(
package_vendor_path: Option<PathBuf>,
package_cache_path: Option<PathBuf>, package_cache_path: Option<PathBuf>,
package_path: Option<PathBuf>, package_path: Option<PathBuf>,
downloader: Downloader, downloader: Downloader,
workdir: Option<PathBuf>,
) -> Self { ) -> Self {
Self { Self {
package_vendor_path: package_vendor_path
.or_else(|| workdir.map(|workdir| workdir.join(DEFAULT_VENDOR_SUBDIR))),
package_cache_path: package_cache_path.or_else(|| { package_cache_path: package_cache_path.or_else(|| {
dirs::cache_dir().map(|cache_dir| cache_dir.join(DEFAULT_PACKAGES_SUBDIR)) dirs::cache_dir().map(|cache_dir| cache_dir.join(DEFAULT_PACKAGES_SUBDIR))
}), }),
@ -74,7 +80,6 @@ impl PackageStorage {
&self, &self,
spec: &PackageSpec, spec: &PackageSpec,
progress: &mut dyn Progress, progress: &mut dyn Progress,
project_root: Option<&Path>,
) -> PackageResult<PathBuf> { ) -> PackageResult<PathBuf> {
let subdir = format!("{}/{}/{}", spec.namespace, spec.name, spec.version); let subdir = format!("{}/{}/{}", spec.namespace, spec.name, spec.version);
@ -86,8 +91,7 @@ impl PackageStorage {
} }
// Read from vendor dir if it exists. // Read from vendor dir if it exists.
if let Some(project_root) = project_root { if let Some(vendor_dir) = &self.package_vendor_path {
let vendor_dir = project_root.join(DEFAULT_VENDOR_SUBDIR);
if let Ok(true) = vendor_dir.try_exists() { if let Ok(true) = vendor_dir.try_exists() {
let dir = vendor_dir.join(&subdir); let dir = vendor_dir.join(&subdir);
if dir.exists() { if dir.exists() {