cargo/ops/cargo_package/
mod.rs

1use std::collections::BTreeMap;
2use std::collections::BTreeSet;
3use std::collections::HashMap;
4use std::fs::{self, File};
5use std::io::SeekFrom;
6use std::io::prelude::*;
7use std::path::{Path, PathBuf};
8use std::task::Poll;
9
10use crate::core::PackageIdSpecQuery;
11use crate::core::Shell;
12use crate::core::Verbosity;
13use crate::core::Workspace;
14use crate::core::dependency::DepKind;
15use crate::core::manifest::Target;
16use crate::core::resolver::CliFeatures;
17use crate::core::resolver::HasDevUnits;
18use crate::core::{Package, PackageId, PackageSet, Resolve, SourceId};
19use crate::ops::lockfile::LOCKFILE_NAME;
20use crate::ops::registry::{RegistryOrIndex, infer_registry};
21use crate::sources::path::PathEntry;
22use crate::sources::{CRATES_IO_REGISTRY, PathSource};
23use crate::util::FileLock;
24use crate::util::Filesystem;
25use crate::util::GlobalContext;
26use crate::util::Graph;
27use crate::util::HumanBytes;
28use crate::util::cache_lock::CacheLockMode;
29use crate::util::context::JobsConfig;
30use crate::util::errors::CargoResult;
31use crate::util::errors::ManifestError;
32use crate::util::restricted_names;
33use crate::util::toml::prepare_for_publish;
34use crate::{drop_println, ops};
35use anyhow::{Context as _, bail};
36use cargo_util::paths;
37use cargo_util_schemas::index::{IndexPackage, RegistryDependency};
38use cargo_util_schemas::messages;
39use flate2::{Compression, GzBuilder};
40use tar::{Builder, EntryType, Header, HeaderMode};
41use tracing::debug;
42use unicase::Ascii as UncasedAscii;
43
44mod vcs;
45mod verify;
46
47/// Message format for `cargo package`.
48///
49/// Currently only affect the output of the `--list` flag.
50#[derive(Debug, Clone)]
51pub enum PackageMessageFormat {
52    Human,
53    Json,
54}
55
56impl PackageMessageFormat {
57    pub const POSSIBLE_VALUES: [&str; 2] = ["human", "json"];
58
59    pub const DEFAULT: &str = "human";
60}
61
62impl std::str::FromStr for PackageMessageFormat {
63    type Err = anyhow::Error;
64
65    fn from_str(s: &str) -> Result<PackageMessageFormat, anyhow::Error> {
66        match s {
67            "human" => Ok(PackageMessageFormat::Human),
68            "json" => Ok(PackageMessageFormat::Json),
69            f => bail!("unknown message format `{f}`"),
70        }
71    }
72}
73
74#[derive(Clone)]
75pub struct PackageOpts<'gctx> {
76    pub gctx: &'gctx GlobalContext,
77    pub list: bool,
78    pub fmt: PackageMessageFormat,
79    pub check_metadata: bool,
80    pub allow_dirty: bool,
81    pub include_lockfile: bool,
82    pub verify: bool,
83    pub jobs: Option<JobsConfig>,
84    pub keep_going: bool,
85    pub to_package: ops::Packages,
86    pub targets: Vec<String>,
87    pub cli_features: CliFeatures,
88    pub reg_or_index: Option<ops::RegistryOrIndex>,
89    /// Whether this packaging job is meant for a publishing dry-run.
90    ///
91    /// Packaging on its own has no side effects, so a dry-run doesn't
92    /// make sense from that point of view. But dry-run publishing needs
93    /// special packaging behavior, which this flag turns on.
94    ///
95    /// Specifically, we want dry-run packaging to work even if versions
96    /// have not yet been bumped. But then if you dry-run packaging in
97    /// a workspace with some declared versions that are already published,
98    /// the package verification step can fail with checksum mismatches.
99    /// So when dry-run is true, the verification step does some extra
100    /// checksum fudging in the lock file.
101    pub dry_run: bool,
102}
103
104const ORIGINAL_MANIFEST_FILE: &str = "Cargo.toml.orig";
105const VCS_INFO_FILE: &str = ".cargo_vcs_info.json";
106
107struct ArchiveFile {
108    /// The relative path in the archive (not including the top-level package
109    /// name directory).
110    rel_path: PathBuf,
111    /// String variant of `rel_path`, for convenience.
112    rel_str: String,
113    /// The contents to add to the archive.
114    contents: FileContents,
115}
116
117enum FileContents {
118    /// Absolute path to the file on disk to add to the archive.
119    OnDisk(PathBuf),
120    /// Generates a file.
121    Generated(GeneratedFile),
122}
123
124enum GeneratedFile {
125    /// Generates `Cargo.toml` by rewriting the original.
126    ///
127    /// Associated path is the original manifest path.
128    Manifest(PathBuf),
129    /// Generates `Cargo.lock`.
130    ///
131    /// Associated path is the path to the original lock file, if existing.
132    Lockfile(Option<PathBuf>),
133    /// Adds a `.cargo_vcs_info.json` file if in a git repo.
134    VcsInfo(vcs::VcsInfo),
135}
136
137// Builds a tarball and places it in the output directory.
138#[tracing::instrument(skip_all)]
139fn create_package(
140    ws: &Workspace<'_>,
141    opts: &PackageOpts<'_>,
142    pkg: &Package,
143    ar_files: Vec<ArchiveFile>,
144    local_reg: Option<&TmpRegistry<'_>>,
145) -> CargoResult<FileLock> {
146    let gctx = ws.gctx();
147    let filecount = ar_files.len();
148
149    // Check that the package dependencies are safe to deploy.
150    for dep in pkg.dependencies() {
151        super::check_dep_has_version(dep, false).map_err(|err| {
152            ManifestError::new(
153                err.context(format!(
154                    "failed to verify manifest at `{}`",
155                    pkg.manifest_path().display()
156                )),
157                pkg.manifest_path().into(),
158            )
159        })?;
160    }
161
162    let filename = pkg.package_id().tarball_name();
163    let dir = ws.target_dir().join("package");
164    let mut dst = {
165        let tmp = format!(".{}", filename);
166        dir.open_rw_exclusive_create(&tmp, gctx, "package scratch space")?
167    };
168
169    // Package up and test a temporary tarball and only move it to the final
170    // location if it actually passes all our tests. Any previously existing
171    // tarball can be assumed as corrupt or invalid, so we just blow it away if
172    // it exists.
173    gctx.shell()
174        .status("Packaging", pkg.package_id().to_string())?;
175    dst.file().set_len(0)?;
176    let uncompressed_size = tar(ws, opts, pkg, local_reg, ar_files, dst.file(), &filename)
177        .context("failed to prepare local package for uploading")?;
178
179    dst.seek(SeekFrom::Start(0))?;
180    let src_path = dst.path();
181    let dst_path = dst.parent().join(&filename);
182    fs::rename(&src_path, &dst_path)
183        .context("failed to move temporary tarball into final location")?;
184
185    let dst_metadata = dst
186        .file()
187        .metadata()
188        .with_context(|| format!("could not learn metadata for: `{}`", dst_path.display()))?;
189    let compressed_size = dst_metadata.len();
190
191    let uncompressed = HumanBytes(uncompressed_size);
192    let compressed = HumanBytes(compressed_size);
193
194    let message = format!("{filecount} files, {uncompressed:.1} ({compressed:.1} compressed)");
195    // It doesn't really matter if this fails.
196    drop(gctx.shell().status("Packaged", message));
197
198    return Ok(dst);
199}
200
201/// Packages an entire workspace.
202///
203/// Returns the generated package files. If `opts.list` is true, skips
204/// generating package files and returns an empty list.
205pub fn package(ws: &Workspace<'_>, opts: &PackageOpts<'_>) -> CargoResult<Vec<FileLock>> {
206    let specs = &opts.to_package.to_package_id_specs(ws)?;
207    // If -p is used, we should check spec is matched with the members (See #13719)
208    if let ops::Packages::Packages(_) = opts.to_package {
209        for spec in specs.iter() {
210            let member_ids = ws.members().map(|p| p.package_id());
211            spec.query(member_ids)?;
212        }
213    }
214    let mut pkgs = ws.members_with_features(specs, &opts.cli_features)?;
215
216    // In `members_with_features_old`, it will add "current" package (determined by the cwd)
217    // So we need filter
218    pkgs.retain(|(pkg, _feats)| specs.iter().any(|spec| spec.matches(pkg.package_id())));
219
220    Ok(do_package(ws, opts, pkgs)?
221        .into_iter()
222        .map(|x| x.2)
223        .collect())
224}
225
226/// Packages an entire workspace.
227///
228/// Returns the generated package files and the dependencies between them. If
229/// `opts.list` is true, skips generating package files and returns an empty
230/// list.
231pub(crate) fn package_with_dep_graph(
232    ws: &Workspace<'_>,
233    opts: &PackageOpts<'_>,
234    pkgs: Vec<(&Package, CliFeatures)>,
235) -> CargoResult<LocalDependencies<(CliFeatures, FileLock)>> {
236    let output = do_package(ws, opts, pkgs)?;
237
238    Ok(local_deps(output.into_iter().map(
239        |(pkg, opts, tarball)| (pkg, (opts.cli_features, tarball)),
240    )))
241}
242
243fn do_package<'a>(
244    ws: &Workspace<'_>,
245    opts: &PackageOpts<'a>,
246    pkgs: Vec<(&Package, CliFeatures)>,
247) -> CargoResult<Vec<(Package, PackageOpts<'a>, FileLock)>> {
248    if ws
249        .lock_root()
250        .as_path_unlocked()
251        .join(LOCKFILE_NAME)
252        .exists()
253        && opts.include_lockfile
254    {
255        // Make sure the Cargo.lock is up-to-date and valid.
256        let dry_run = false;
257        let _ = ops::resolve_ws(ws, dry_run)?;
258        // If Cargo.lock does not exist, it will be generated by `build_lock`
259        // below, and will be validated during the verification step.
260    }
261
262    let deps = local_deps(pkgs.iter().map(|(p, f)| ((*p).clone(), f.clone())));
263    let just_pkgs: Vec<_> = pkgs.iter().map(|p| p.0).collect();
264
265    let mut local_reg = {
266        // The publish registry doesn't matter unless there are local dependencies that will be
267        // resolved,
268        // so only try to get one if we need it. If they explicitly passed a
269        // registry on the CLI, we check it no matter what.
270        let sid = if (deps.has_dependencies() && (opts.include_lockfile || opts.verify))
271            || opts.reg_or_index.is_some()
272        {
273            let sid = get_registry(ws.gctx(), &just_pkgs, opts.reg_or_index.clone())?;
274            debug!("packaging for registry {}", sid);
275            Some(sid)
276        } else {
277            None
278        };
279        let reg_dir = ws.build_dir().join("package").join("tmp-registry");
280        sid.map(|sid| TmpRegistry::new(ws.gctx(), reg_dir, sid))
281            .transpose()?
282    };
283
284    // Packages need to be created in dependency order, because dependencies must
285    // be added to our local overlay before we can create lockfiles that depend on them.
286    let sorted_pkgs = deps.sort();
287    let mut outputs: Vec<(Package, PackageOpts<'_>, FileLock)> = Vec::new();
288    for (pkg, cli_features) in sorted_pkgs {
289        let opts = PackageOpts {
290            cli_features: cli_features.clone(),
291            to_package: ops::Packages::Default,
292            ..opts.clone()
293        };
294        let ar_files = prepare_archive(ws, &pkg, &opts)?;
295
296        if opts.list {
297            match opts.fmt {
298                PackageMessageFormat::Human => {
299                    // While this form is called "human",
300                    // it keeps the old file-per-line format for compatibility.
301                    for ar_file in &ar_files {
302                        drop_println!(ws.gctx(), "{}", ar_file.rel_str);
303                    }
304                }
305                PackageMessageFormat::Json => {
306                    let message = messages::PackageList {
307                        id: pkg.package_id().to_spec(),
308                        files: BTreeMap::from_iter(ar_files.into_iter().map(|f| {
309                            let file = match f.contents {
310                                FileContents::OnDisk(path) => messages::PackageFile::Copy { path },
311                                FileContents::Generated(
312                                    GeneratedFile::Manifest(path)
313                                    | GeneratedFile::Lockfile(Some(path)),
314                                ) => messages::PackageFile::Generate { path: Some(path) },
315                                FileContents::Generated(
316                                    GeneratedFile::VcsInfo(_) | GeneratedFile::Lockfile(None),
317                                ) => messages::PackageFile::Generate { path: None },
318                            };
319                            (f.rel_path, file)
320                        })),
321                    };
322                    let _ = ws.gctx().shell().print_json(&message);
323                }
324            }
325        } else {
326            let tarball = create_package(ws, &opts, &pkg, ar_files, local_reg.as_ref())?;
327            if let Some(local_reg) = local_reg.as_mut() {
328                if pkg.publish() != &Some(Vec::new()) {
329                    local_reg.add_package(ws, &pkg, &tarball)?;
330                }
331            }
332            outputs.push((pkg, opts, tarball));
333        }
334    }
335
336    // Verify all packages in the workspace. This can be done in any order, since the dependencies
337    // are already all in the local registry overlay.
338    if opts.verify {
339        for (pkg, opts, tarball) in &outputs {
340            verify::run_verify(ws, pkg, tarball, local_reg.as_ref(), opts)
341                .context("failed to verify package tarball")?
342        }
343    }
344
345    Ok(outputs)
346}
347
348/// Determine which registry the packages are for.
349///
350/// The registry only affects the built packages if there are dependencies within the
351/// packages that we're packaging: if we're packaging foo-bin and foo-lib, and foo-bin
352/// depends on foo-lib, then the foo-lib entry in foo-bin's lockfile will depend on the
353/// registry that we're building packages for.
354fn get_registry(
355    gctx: &GlobalContext,
356    pkgs: &[&Package],
357    reg_or_index: Option<RegistryOrIndex>,
358) -> CargoResult<SourceId> {
359    let reg_or_index = match reg_or_index.clone() {
360        Some(r) => Some(r),
361        None => infer_registry(pkgs)?,
362    };
363
364    // Validate the registry against the packages' allow-lists.
365    let reg = reg_or_index
366        .clone()
367        .unwrap_or_else(|| RegistryOrIndex::Registry(CRATES_IO_REGISTRY.to_owned()));
368    if let RegistryOrIndex::Registry(reg_name) = reg {
369        for pkg in pkgs {
370            if let Some(allowed) = pkg.publish().as_ref() {
371                // If allowed is empty (i.e. package.publish is false), we let it slide.
372                // This allows packaging unpublishable packages (although packaging might
373                // fail later if the unpublishable package is a dependency of something else).
374                if !allowed.is_empty() && !allowed.iter().any(|a| a == &reg_name) {
375                    bail!(
376                        "`{}` cannot be packaged.\n\
377                         The registry `{}` is not listed in the `package.publish` value in Cargo.toml.",
378                        pkg.name(),
379                        reg_name
380                    );
381                }
382            }
383        }
384    }
385    Ok(ops::registry::get_source_id(gctx, reg_or_index.as_ref())?.replacement)
386}
387
388/// Just the part of the dependency graph that's between the packages we're packaging.
389#[derive(Clone, Debug, Default)]
390pub(crate) struct LocalDependencies<T> {
391    pub packages: HashMap<PackageId, (Package, T)>,
392    pub graph: Graph<PackageId, ()>,
393}
394
395impl<T: Clone> LocalDependencies<T> {
396    pub fn sort(&self) -> Vec<(Package, T)> {
397        self.graph
398            .sort()
399            .into_iter()
400            .map(|name| self.packages[&name].clone())
401            .collect()
402    }
403
404    pub fn has_dependencies(&self) -> bool {
405        self.graph
406            .iter()
407            .any(|node| self.graph.edges(node).next().is_some())
408    }
409}
410
411/// Build just the part of the dependency graph that's between the given packages,
412/// ignoring dev dependencies.
413///
414/// We assume that the packages all belong to this workspace.
415fn local_deps<T>(packages: impl Iterator<Item = (Package, T)>) -> LocalDependencies<T> {
416    let packages: HashMap<PackageId, (Package, T)> = packages
417        .map(|(pkg, payload)| (pkg.package_id(), (pkg, payload)))
418        .collect();
419
420    // Dependencies have source ids but not package ids. We draw an edge
421    // whenever a dependency's source id matches one of our packages. This is
422    // wrong in general because it doesn't require (e.g.) versions to match. But
423    // since we're working only with path dependencies here, it should be fine.
424    let source_to_pkg: HashMap<_, _> = packages
425        .keys()
426        .map(|pkg_id| (pkg_id.source_id(), *pkg_id))
427        .collect();
428
429    let mut graph = Graph::new();
430    for (pkg, _payload) in packages.values() {
431        graph.add(pkg.package_id());
432        for dep in pkg.dependencies() {
433            // We're only interested in local (i.e. living in this workspace) dependencies.
434            if !dep.source_id().is_path() {
435                continue;
436            }
437
438            // If local dev-dependencies don't have a version specified, they get stripped
439            // on publish so we should ignore them.
440            if dep.kind() == DepKind::Development && !dep.specified_req() {
441                continue;
442            };
443
444            // We don't care about cycles
445            if dep.source_id() == pkg.package_id().source_id() {
446                continue;
447            }
448
449            if let Some(dep_pkg) = source_to_pkg.get(&dep.source_id()) {
450                graph.link(pkg.package_id(), *dep_pkg);
451            }
452        }
453    }
454
455    LocalDependencies { packages, graph }
456}
457
458/// Performs pre-archiving checks and builds a list of files to archive.
459#[tracing::instrument(skip_all)]
460fn prepare_archive(
461    ws: &Workspace<'_>,
462    pkg: &Package,
463    opts: &PackageOpts<'_>,
464) -> CargoResult<Vec<ArchiveFile>> {
465    let gctx = ws.gctx();
466    let mut src = PathSource::new(pkg.root(), pkg.package_id().source_id(), gctx);
467    src.load()?;
468
469    if opts.check_metadata {
470        check_metadata(pkg, gctx)?;
471    }
472
473    if !pkg.manifest().exclude().is_empty() && !pkg.manifest().include().is_empty() {
474        gctx.shell().warn(
475            "both package.include and package.exclude are specified; \
476             the exclude list will be ignored",
477        )?;
478    }
479    let src_files = src.list_files(pkg)?;
480
481    // Check (git) repository state, getting the current commit hash.
482    let vcs_info = vcs::check_repo_state(pkg, &src_files, ws, &opts)?;
483    build_ar_list(ws, pkg, src_files, vcs_info, opts.include_lockfile)
484}
485
486/// Builds list of files to archive.
487#[tracing::instrument(skip_all)]
488fn build_ar_list(
489    ws: &Workspace<'_>,
490    pkg: &Package,
491    src_files: Vec<PathEntry>,
492    vcs_info: Option<vcs::VcsInfo>,
493    include_lockfile: bool,
494) -> CargoResult<Vec<ArchiveFile>> {
495    let mut result = HashMap::new();
496    let root = pkg.root();
497    for src_file in &src_files {
498        let rel_path = src_file.strip_prefix(&root)?;
499        check_filename(rel_path, &mut ws.gctx().shell())?;
500        let rel_str = rel_path.to_str().ok_or_else(|| {
501            anyhow::format_err!("non-utf8 path in source directory: {}", rel_path.display())
502        })?;
503        match rel_str {
504            "Cargo.lock" => continue,
505            VCS_INFO_FILE | ORIGINAL_MANIFEST_FILE => anyhow::bail!(
506                "invalid inclusion of reserved file name {} in package source",
507                rel_str
508            ),
509            _ => {
510                result
511                    .entry(UncasedAscii::new(rel_str))
512                    .or_insert_with(Vec::new)
513                    .push(ArchiveFile {
514                        rel_path: rel_path.to_owned(),
515                        rel_str: rel_str.to_owned(),
516                        contents: FileContents::OnDisk(src_file.to_path_buf()),
517                    });
518            }
519        }
520    }
521
522    // Ensure we normalize for case insensitive filesystems (like on Windows) by removing the
523    // existing entry, regardless of case, and adding in with the correct case
524    if result.remove(&UncasedAscii::new("Cargo.toml")).is_some() {
525        result
526            .entry(UncasedAscii::new(ORIGINAL_MANIFEST_FILE))
527            .or_insert_with(Vec::new)
528            .push(ArchiveFile {
529                rel_path: PathBuf::from(ORIGINAL_MANIFEST_FILE),
530                rel_str: ORIGINAL_MANIFEST_FILE.to_string(),
531                contents: FileContents::OnDisk(pkg.manifest_path().to_owned()),
532            });
533        result
534            .entry(UncasedAscii::new("Cargo.toml"))
535            .or_insert_with(Vec::new)
536            .push(ArchiveFile {
537                rel_path: PathBuf::from("Cargo.toml"),
538                rel_str: "Cargo.toml".to_string(),
539                contents: FileContents::Generated(GeneratedFile::Manifest(
540                    pkg.manifest_path().to_owned(),
541                )),
542            });
543    } else {
544        ws.gctx().shell().warn(&format!(
545            "no `Cargo.toml` file found when packaging `{}` (note the case of the file name).",
546            pkg.name()
547        ))?;
548    }
549
550    if include_lockfile {
551        let lockfile_path = ws.lock_root().as_path_unlocked().join(LOCKFILE_NAME);
552        let lockfile_path = lockfile_path.exists().then_some(lockfile_path);
553        let rel_str = "Cargo.lock";
554        result
555            .entry(UncasedAscii::new(rel_str))
556            .or_insert_with(Vec::new)
557            .push(ArchiveFile {
558                rel_path: PathBuf::from(rel_str),
559                rel_str: rel_str.to_string(),
560                contents: FileContents::Generated(GeneratedFile::Lockfile(lockfile_path)),
561            });
562    }
563
564    if let Some(vcs_info) = vcs_info {
565        let rel_str = VCS_INFO_FILE;
566        result
567            .entry(UncasedAscii::new(rel_str))
568            .or_insert_with(Vec::new)
569            .push(ArchiveFile {
570                rel_path: PathBuf::from(rel_str),
571                rel_str: rel_str.to_string(),
572                contents: FileContents::Generated(GeneratedFile::VcsInfo(vcs_info)),
573            });
574    }
575
576    let mut invalid_manifest_field: Vec<String> = vec![];
577
578    let mut result = result.into_values().flatten().collect();
579    if let Some(license_file) = &pkg.manifest().metadata().license_file {
580        let license_path = Path::new(license_file);
581        let abs_file_path = paths::normalize_path(&pkg.root().join(license_path));
582        if abs_file_path.is_file() {
583            check_for_file_and_add(
584                "license-file",
585                license_path,
586                abs_file_path,
587                pkg,
588                &mut result,
589                ws,
590            )?;
591        } else {
592            error_on_nonexistent_file(
593                &pkg,
594                &license_path,
595                "license-file",
596                &mut invalid_manifest_field,
597            );
598        }
599    }
600    if let Some(readme) = &pkg.manifest().metadata().readme {
601        let readme_path = Path::new(readme);
602        let abs_file_path = paths::normalize_path(&pkg.root().join(readme_path));
603        if abs_file_path.is_file() {
604            check_for_file_and_add("readme", readme_path, abs_file_path, pkg, &mut result, ws)?;
605        } else {
606            error_on_nonexistent_file(&pkg, &readme_path, "readme", &mut invalid_manifest_field);
607        }
608    }
609
610    if !invalid_manifest_field.is_empty() {
611        return Err(anyhow::anyhow!(invalid_manifest_field.join("\n")));
612    }
613
614    for t in pkg
615        .manifest()
616        .targets()
617        .iter()
618        .filter(|t| t.is_custom_build())
619    {
620        if let Some(custome_build_path) = t.src_path().path() {
621            let abs_custome_build_path =
622                paths::normalize_path(&pkg.root().join(custome_build_path));
623            if !abs_custome_build_path.is_file() || !abs_custome_build_path.starts_with(pkg.root())
624            {
625                error_custom_build_file_not_in_package(pkg, &abs_custome_build_path, t)?;
626            }
627        }
628    }
629
630    result.sort_unstable_by(|a, b| a.rel_path.cmp(&b.rel_path));
631
632    Ok(result)
633}
634
635fn check_for_file_and_add(
636    label: &str,
637    file_path: &Path,
638    abs_file_path: PathBuf,
639    pkg: &Package,
640    result: &mut Vec<ArchiveFile>,
641    ws: &Workspace<'_>,
642) -> CargoResult<()> {
643    match abs_file_path.strip_prefix(&pkg.root()) {
644        Ok(rel_file_path) => {
645            if !result.iter().any(|ar| ar.rel_path == rel_file_path) {
646                result.push(ArchiveFile {
647                    rel_path: rel_file_path.to_path_buf(),
648                    rel_str: rel_file_path
649                        .to_str()
650                        .expect("everything was utf8")
651                        .to_string(),
652                    contents: FileContents::OnDisk(abs_file_path),
653                })
654            }
655        }
656        Err(_) => {
657            // The file exists somewhere outside of the package.
658            let file_name = file_path.file_name().unwrap();
659            if result.iter().any(|ar| ar.rel_path == file_name) {
660                ws.gctx().shell().warn(&format!(
661                    "{} `{}` appears to be a path outside of the package, \
662                            but there is already a file named `{}` in the root of the package. \
663                            The archived crate will contain the copy in the root of the package. \
664                            Update the {} to point to the path relative \
665                            to the root of the package to remove this warning.",
666                    label,
667                    file_path.display(),
668                    file_name.to_str().unwrap(),
669                    label,
670                ))?;
671            } else {
672                result.push(ArchiveFile {
673                    rel_path: PathBuf::from(file_name),
674                    rel_str: file_name.to_str().unwrap().to_string(),
675                    contents: FileContents::OnDisk(abs_file_path),
676                })
677            }
678        }
679    }
680    Ok(())
681}
682
683fn error_on_nonexistent_file(
684    pkg: &Package,
685    path: &Path,
686    manifest_key_name: &'static str,
687    invalid: &mut Vec<String>,
688) {
689    let rel_msg = if path.is_absolute() {
690        "".to_string()
691    } else {
692        format!(" (relative to `{}`)", pkg.root().display())
693    };
694
695    let msg = format!(
696        "{manifest_key_name} `{}` does not appear to exist{}.\n\
697                Please update the {manifest_key_name} setting in the manifest at `{}`.",
698        path.display(),
699        rel_msg,
700        pkg.manifest_path().display()
701    );
702
703    invalid.push(msg);
704}
705
706fn error_custom_build_file_not_in_package(
707    pkg: &Package,
708    path: &Path,
709    target: &Target,
710) -> CargoResult<Vec<ArchiveFile>> {
711    let tip = {
712        let description_name = target.description_named();
713        if path.is_file() {
714            format!(
715                "the source file of {description_name} doesn't appear to be a path inside of the package.\n\
716            It is at `{}`, whereas the root the package is `{}`.\n",
717                path.display(),
718                pkg.root().display()
719            )
720        } else {
721            format!("the source file of {description_name} doesn't appear to exist.\n",)
722        }
723    };
724    let msg = format!(
725        "{}\
726        This may cause issue during packaging, as modules resolution and resources included via macros are often relative to the path of source files.\n\
727        Please update the `build` setting in the manifest at `{}` and point to a path inside the root of the package.",
728        tip,
729        pkg.manifest_path().display()
730    );
731    anyhow::bail!(msg)
732}
733
734/// Construct `Cargo.lock` for the package to be published.
735fn build_lock(
736    ws: &Workspace<'_>,
737    opts: &PackageOpts<'_>,
738    publish_pkg: &Package,
739    local_reg: Option<&TmpRegistry<'_>>,
740) -> CargoResult<String> {
741    let gctx = ws.gctx();
742    let mut orig_resolve = ops::load_pkg_lockfile(ws)?;
743
744    let mut tmp_ws = Workspace::ephemeral(publish_pkg.clone(), ws.gctx(), None, true)?;
745
746    // The local registry is an overlay used for simulating workspace packages
747    // that are supposed to be in the published registry, but that aren't there
748    // yet.
749    if let Some(local_reg) = local_reg {
750        tmp_ws.add_local_overlay(
751            local_reg.upstream,
752            local_reg.root.as_path_unlocked().to_owned(),
753        );
754        if opts.dry_run {
755            if let Some(orig_resolve) = orig_resolve.as_mut() {
756                let upstream_in_lock = if local_reg.upstream.is_crates_io() {
757                    SourceId::crates_io(gctx)?
758                } else {
759                    local_reg.upstream
760                };
761                for (p, s) in local_reg.checksums() {
762                    orig_resolve.set_checksum(p.with_source_id(upstream_in_lock), s.to_owned());
763                }
764            }
765        }
766    }
767    let mut tmp_reg = tmp_ws.package_registry()?;
768
769    let mut new_resolve = ops::resolve_with_previous(
770        &mut tmp_reg,
771        &tmp_ws,
772        &CliFeatures::new_all(true),
773        HasDevUnits::Yes,
774        orig_resolve.as_ref(),
775        None,
776        &[],
777        true,
778    )?;
779
780    let pkg_set = ops::get_resolved_packages(&new_resolve, tmp_reg)?;
781
782    if let Some(orig_resolve) = orig_resolve {
783        compare_resolve(gctx, tmp_ws.current()?, &orig_resolve, &new_resolve)?;
784    }
785    check_yanked(
786        gctx,
787        &pkg_set,
788        &new_resolve,
789        "consider updating to a version that is not yanked",
790    )?;
791
792    ops::resolve_to_string(&tmp_ws, &mut new_resolve)
793}
794
795// Checks that the package has some piece of metadata that a human can
796// use to tell what the package is about.
797fn check_metadata(pkg: &Package, gctx: &GlobalContext) -> CargoResult<()> {
798    let md = pkg.manifest().metadata();
799
800    let mut missing = vec![];
801
802    macro_rules! lacking {
803        ($( $($field: ident)||* ),*) => {{
804            $(
805                if $(md.$field.as_ref().map_or(true, |s| s.is_empty()))&&* {
806                    $(missing.push(stringify!($field).replace("_", "-"));)*
807                }
808            )*
809        }}
810    }
811    lacking!(
812        description,
813        license || license_file,
814        documentation || homepage || repository
815    );
816
817    if !missing.is_empty() {
818        let mut things = missing[..missing.len() - 1].join(", ");
819        // `things` will be empty if and only if its length is 1 (i.e., the only case
820        // to have no `or`).
821        if !things.is_empty() {
822            things.push_str(" or ");
823        }
824        things.push_str(missing.last().unwrap());
825
826        gctx.shell().warn(&format!(
827            "manifest has no {things}.\n\
828             See https://doc.rust-lang.org/cargo/reference/manifest.html#package-metadata for more info.",
829            things = things
830        ))?
831    }
832
833    Ok(())
834}
835
836/// Compresses and packages a list of [`ArchiveFile`]s and writes into the given file.
837///
838/// Returns the uncompressed size of the contents of the new archive file.
839fn tar(
840    ws: &Workspace<'_>,
841    opts: &PackageOpts<'_>,
842    pkg: &Package,
843    local_reg: Option<&TmpRegistry<'_>>,
844    ar_files: Vec<ArchiveFile>,
845    dst: &File,
846    filename: &str,
847) -> CargoResult<u64> {
848    // Prepare the encoder and its header.
849    let filename = Path::new(filename);
850    let encoder = GzBuilder::new()
851        .filename(paths::path2bytes(filename)?)
852        .write(dst, Compression::best());
853
854    // Put all package files into a compressed archive.
855    let mut ar = Builder::new(encoder);
856    ar.sparse(false);
857    let gctx = ws.gctx();
858
859    let base_name = format!("{}-{}", pkg.name(), pkg.version());
860    let base_path = Path::new(&base_name);
861    let included = ar_files
862        .iter()
863        .map(|ar_file| ar_file.rel_path.clone())
864        .collect::<Vec<_>>();
865    let publish_pkg = prepare_for_publish(pkg, ws, Some(&included))?;
866
867    let mut uncompressed_size = 0;
868    for ar_file in ar_files {
869        let ArchiveFile {
870            rel_path,
871            rel_str,
872            contents,
873        } = ar_file;
874        let ar_path = base_path.join(&rel_path);
875        gctx.shell()
876            .verbose(|shell| shell.status("Archiving", &rel_str))?;
877        let mut header = Header::new_gnu();
878        match contents {
879            FileContents::OnDisk(disk_path) => {
880                let mut file = File::open(&disk_path).with_context(|| {
881                    format!("failed to open for archiving: `{}`", disk_path.display())
882                })?;
883                let metadata = file.metadata().with_context(|| {
884                    format!("could not learn metadata for: `{}`", disk_path.display())
885                })?;
886                header.set_metadata_in_mode(&metadata, HeaderMode::Deterministic);
887                header.set_cksum();
888                ar.append_data(&mut header, &ar_path, &mut file)
889                    .with_context(|| {
890                        format!("could not archive source file `{}`", disk_path.display())
891                    })?;
892                uncompressed_size += metadata.len() as u64;
893            }
894            FileContents::Generated(generated_kind) => {
895                let contents = match generated_kind {
896                    GeneratedFile::Manifest(_) => {
897                        publish_pkg.manifest().to_normalized_contents()?
898                    }
899                    GeneratedFile::Lockfile(_) => build_lock(ws, opts, &publish_pkg, local_reg)?,
900                    GeneratedFile::VcsInfo(ref s) => serde_json::to_string_pretty(s)?,
901                };
902                header.set_entry_type(EntryType::file());
903                header.set_mode(0o644);
904                header.set_size(contents.len() as u64);
905                // use something nonzero to avoid rust-lang/cargo#9512
906                header.set_mtime(1);
907                header.set_cksum();
908                ar.append_data(&mut header, &ar_path, contents.as_bytes())
909                    .with_context(|| format!("could not archive source file `{}`", rel_str))?;
910                uncompressed_size += contents.len() as u64;
911            }
912        }
913    }
914
915    let encoder = ar.into_inner()?;
916    encoder.finish()?;
917    Ok(uncompressed_size)
918}
919
920/// Generate warnings when packaging Cargo.lock, and the resolve have changed.
921fn compare_resolve(
922    gctx: &GlobalContext,
923    current_pkg: &Package,
924    orig_resolve: &Resolve,
925    new_resolve: &Resolve,
926) -> CargoResult<()> {
927    if gctx.shell().verbosity() != Verbosity::Verbose {
928        return Ok(());
929    }
930    let new_set: BTreeSet<PackageId> = new_resolve.iter().collect();
931    let orig_set: BTreeSet<PackageId> = orig_resolve.iter().collect();
932    let added = new_set.difference(&orig_set);
933    // Removed entries are ignored, this is used to quickly find hints for why
934    // an entry changed.
935    let removed: Vec<&PackageId> = orig_set.difference(&new_set).collect();
936    for pkg_id in added {
937        if pkg_id.name() == current_pkg.name() && pkg_id.version() == current_pkg.version() {
938            // Skip the package that is being created, since its SourceId
939            // (directory) changes.
940            continue;
941        }
942        // Check for candidates where the source has changed (such as [patch]
943        // or a dependency with multiple sources like path/version).
944        let removed_candidates: Vec<&PackageId> = removed
945            .iter()
946            .filter(|orig_pkg_id| {
947                orig_pkg_id.name() == pkg_id.name() && orig_pkg_id.version() == pkg_id.version()
948            })
949            .cloned()
950            .collect();
951        let extra = match removed_candidates.len() {
952            0 => {
953                // This can happen if the original was out of date.
954                let previous_versions: Vec<&PackageId> = removed
955                    .iter()
956                    .filter(|orig_pkg_id| orig_pkg_id.name() == pkg_id.name())
957                    .cloned()
958                    .collect();
959                match previous_versions.len() {
960                    0 => String::new(),
961                    1 => format!(
962                        ", previous version was `{}`",
963                        previous_versions[0].version()
964                    ),
965                    _ => format!(
966                        ", previous versions were: {}",
967                        previous_versions
968                            .iter()
969                            .map(|pkg_id| format!("`{}`", pkg_id.version()))
970                            .collect::<Vec<_>>()
971                            .join(", ")
972                    ),
973                }
974            }
975            1 => {
976                // This can happen for multi-sourced dependencies like
977                // `{path="...", version="..."}` or `[patch]` replacement.
978                // `[replace]` is not captured in Cargo.lock.
979                format!(
980                    ", was originally sourced from `{}`",
981                    removed_candidates[0].source_id()
982                )
983            }
984            _ => {
985                // I don't know if there is a way to actually trigger this,
986                // but handle it just in case.
987                let comma_list = removed_candidates
988                    .iter()
989                    .map(|pkg_id| format!("`{}`", pkg_id.source_id()))
990                    .collect::<Vec<_>>()
991                    .join(", ");
992                format!(
993                    ", was originally sourced from one of these sources: {}",
994                    comma_list
995                )
996            }
997        };
998        let msg = format!(
999            "package `{}` added to the packaged Cargo.lock file{}",
1000            pkg_id, extra
1001        );
1002        gctx.shell().note(msg)?;
1003    }
1004    Ok(())
1005}
1006
1007pub fn check_yanked(
1008    gctx: &GlobalContext,
1009    pkg_set: &PackageSet<'_>,
1010    resolve: &Resolve,
1011    hint: &str,
1012) -> CargoResult<()> {
1013    // Checking the yanked status involves taking a look at the registry and
1014    // maybe updating files, so be sure to lock it here.
1015    let _lock = gctx.acquire_package_cache_lock(CacheLockMode::DownloadExclusive)?;
1016
1017    let mut sources = pkg_set.sources_mut();
1018    let mut pending: Vec<PackageId> = resolve.iter().collect();
1019    let mut results = Vec::new();
1020    for (_id, source) in sources.sources_mut() {
1021        source.invalidate_cache();
1022    }
1023    while !pending.is_empty() {
1024        pending.retain(|pkg_id| {
1025            if let Some(source) = sources.get_mut(pkg_id.source_id()) {
1026                match source.is_yanked(*pkg_id) {
1027                    Poll::Ready(result) => results.push((*pkg_id, result)),
1028                    Poll::Pending => return true,
1029                }
1030            }
1031            false
1032        });
1033        for (_id, source) in sources.sources_mut() {
1034            source.block_until_ready()?;
1035        }
1036    }
1037
1038    for (pkg_id, is_yanked) in results {
1039        if is_yanked? {
1040            gctx.shell().warn(format!(
1041                "package `{}` in Cargo.lock is yanked in registry `{}`, {}",
1042                pkg_id,
1043                pkg_id.source_id().display_registry_name(),
1044                hint
1045            ))?;
1046        }
1047    }
1048    Ok(())
1049}
1050
1051// It can often be the case that files of a particular name on one platform
1052// can't actually be created on another platform. For example files with colons
1053// in the name are allowed on Unix but not on Windows.
1054//
1055// To help out in situations like this, issue about weird filenames when
1056// packaging as a "heads up" that something may not work on other platforms.
1057fn check_filename(file: &Path, shell: &mut Shell) -> CargoResult<()> {
1058    let Some(name) = file.file_name() else {
1059        return Ok(());
1060    };
1061    let Some(name) = name.to_str() else {
1062        anyhow::bail!(
1063            "path does not have a unicode filename which may not unpack \
1064             on all platforms: {}",
1065            file.display()
1066        )
1067    };
1068    let bad_chars = ['/', '\\', '<', '>', ':', '"', '|', '?', '*'];
1069    if let Some(c) = bad_chars.iter().find(|c| name.contains(**c)) {
1070        anyhow::bail!(
1071            "cannot package a filename with a special character `{}`: {}",
1072            c,
1073            file.display()
1074        )
1075    }
1076    if restricted_names::is_windows_reserved_path(file) {
1077        shell.warn(format!(
1078            "file {} is a reserved Windows filename, \
1079                it will not work on Windows platforms",
1080            file.display()
1081        ))?;
1082    }
1083    Ok(())
1084}
1085
1086/// Manages a temporary local registry that we use to overlay our new packages on the
1087/// upstream registry. This way we can build lockfiles that depend on the new packages even
1088/// before they're published.
1089struct TmpRegistry<'a> {
1090    gctx: &'a GlobalContext,
1091    upstream: SourceId,
1092    root: Filesystem,
1093    checksums: HashMap<PackageId, String>,
1094    _lock: FileLock,
1095}
1096
1097impl<'a> TmpRegistry<'a> {
1098    fn new(gctx: &'a GlobalContext, root: Filesystem, upstream: SourceId) -> CargoResult<Self> {
1099        root.create_dir()?;
1100        let _lock = root.open_rw_exclusive_create(".cargo-lock", gctx, "temporary registry")?;
1101        let slf = Self {
1102            gctx,
1103            root,
1104            upstream,
1105            checksums: HashMap::new(),
1106            _lock,
1107        };
1108        // If there's an old temporary registry, delete it.
1109        let index_path = slf.index_path().into_path_unlocked();
1110        if index_path.exists() {
1111            paths::remove_dir_all(index_path)?;
1112        }
1113        slf.index_path().create_dir()?;
1114        Ok(slf)
1115    }
1116
1117    fn index_path(&self) -> Filesystem {
1118        self.root.join("index")
1119    }
1120
1121    fn add_package(
1122        &mut self,
1123        ws: &Workspace<'_>,
1124        package: &Package,
1125        tar: &FileLock,
1126    ) -> CargoResult<()> {
1127        debug!(
1128            "adding package {}@{} to local overlay at {}",
1129            package.name(),
1130            package.version(),
1131            self.root.as_path_unlocked().display()
1132        );
1133        {
1134            let mut tar_copy = self.root.open_rw_exclusive_create(
1135                package.package_id().tarball_name(),
1136                self.gctx,
1137                "temporary package registry",
1138            )?;
1139            tar.file().seek(SeekFrom::Start(0))?;
1140            std::io::copy(&mut tar.file(), &mut tar_copy)?;
1141            tar_copy.flush()?;
1142        }
1143
1144        let new_crate = super::registry::prepare_transmit(self.gctx, ws, package, self.upstream)?;
1145
1146        tar.file().seek(SeekFrom::Start(0))?;
1147        let cksum = cargo_util::Sha256::new()
1148            .update_file(tar.file())?
1149            .finish_hex();
1150
1151        self.checksums.insert(package.package_id(), cksum.clone());
1152
1153        let deps: Vec<_> = new_crate
1154            .deps
1155            .into_iter()
1156            .map(|dep| {
1157                let name = dep
1158                    .explicit_name_in_toml
1159                    .clone()
1160                    .unwrap_or_else(|| dep.name.clone())
1161                    .into();
1162                let package = dep
1163                    .explicit_name_in_toml
1164                    .as_ref()
1165                    .map(|_| dep.name.clone().into());
1166                RegistryDependency {
1167                    name: name,
1168                    req: dep.version_req.into(),
1169                    features: dep.features.into_iter().map(|x| x.into()).collect(),
1170                    optional: dep.optional,
1171                    default_features: dep.default_features,
1172                    target: dep.target.map(|x| x.into()),
1173                    kind: Some(dep.kind.into()),
1174                    registry: dep.registry.map(|x| x.into()),
1175                    package: package,
1176                    public: None,
1177                    artifact: dep
1178                        .artifact
1179                        .map(|xs| xs.into_iter().map(|x| x.into()).collect()),
1180                    bindep_target: dep.bindep_target.map(|x| x.into()),
1181                    lib: dep.lib,
1182                }
1183            })
1184            .collect();
1185
1186        let index_line = serde_json::to_string(&IndexPackage {
1187            name: new_crate.name.into(),
1188            vers: package.version().clone(),
1189            deps,
1190            features: new_crate
1191                .features
1192                .into_iter()
1193                .map(|(k, v)| (k.into(), v.into_iter().map(|x| x.into()).collect()))
1194                .collect(),
1195            features2: None,
1196            cksum,
1197            yanked: None,
1198            links: new_crate.links.map(|x| x.into()),
1199            rust_version: None,
1200            v: Some(2),
1201        })?;
1202
1203        let file =
1204            cargo_util::registry::make_dep_path(&package.name().as_str().to_lowercase(), false);
1205        let mut dst = self.index_path().open_rw_exclusive_create(
1206            file,
1207            self.gctx,
1208            "temporary package registry",
1209        )?;
1210        dst.write_all(index_line.as_bytes())?;
1211        Ok(())
1212    }
1213
1214    fn checksums(&self) -> impl Iterator<Item = (PackageId, &str)> {
1215        self.checksums.iter().map(|(p, s)| (*p, s.as_str()))
1216    }
1217}