cargo/ops/registry/
publish.rs

1//! Interacts with the registry [publish API][1].
2//!
3//! [1]: https://doc.rust-lang.org/nightly/cargo/reference/registry-web-api.html#publish
4
5use std::collections::BTreeMap;
6use std::collections::BTreeSet;
7use std::collections::HashMap;
8use std::collections::HashSet;
9use std::fs::File;
10use std::io::Seek;
11use std::io::SeekFrom;
12use std::time::Duration;
13
14use anyhow::Context as _;
15use anyhow::bail;
16use cargo_credential::Operation;
17use cargo_credential::Secret;
18use cargo_util::paths;
19use crates_io::NewCrate;
20use crates_io::NewCrateDependency;
21use crates_io::Registry;
22use itertools::Itertools;
23
24use crate::CargoResult;
25use crate::GlobalContext;
26use crate::core::Dependency;
27use crate::core::Package;
28use crate::core::PackageId;
29use crate::core::PackageIdSpecQuery;
30use crate::core::SourceId;
31use crate::core::Workspace;
32use crate::core::dependency::DepKind;
33use crate::core::manifest::ManifestMetadata;
34use crate::core::resolver::CliFeatures;
35use crate::ops;
36use crate::ops::PackageOpts;
37use crate::ops::Packages;
38use crate::ops::RegistryOrIndex;
39use crate::ops::registry::RegistrySourceIds;
40use crate::sources::CRATES_IO_REGISTRY;
41use crate::sources::RegistrySource;
42use crate::sources::SourceConfigMap;
43use crate::sources::source::QueryKind;
44use crate::sources::source::Source;
45use crate::util::Graph;
46use crate::util::Progress;
47use crate::util::ProgressStyle;
48use crate::util::VersionExt as _;
49use crate::util::auth;
50use crate::util::cache_lock::CacheLockMode;
51use crate::util::context::JobsConfig;
52use crate::util::errors::ManifestError;
53use crate::util::toml::prepare_for_publish;
54
55use super::super::check_dep_has_version;
56
57pub struct PublishOpts<'gctx> {
58    pub gctx: &'gctx GlobalContext,
59    pub token: Option<Secret<String>>,
60    pub reg_or_index: Option<RegistryOrIndex>,
61    pub verify: bool,
62    pub allow_dirty: bool,
63    pub jobs: Option<JobsConfig>,
64    pub keep_going: bool,
65    pub to_publish: ops::Packages,
66    pub targets: Vec<String>,
67    pub dry_run: bool,
68    pub cli_features: CliFeatures,
69}
70
71pub fn publish(ws: &Workspace<'_>, opts: &PublishOpts<'_>) -> CargoResult<()> {
72    let specs = opts.to_publish.to_package_id_specs(ws)?;
73
74    let member_ids: Vec<_> = ws.members().map(|p| p.package_id()).collect();
75    // Check that the specs match members.
76    for spec in &specs {
77        spec.query(member_ids.clone())?;
78    }
79    let mut pkgs = ws.members_with_features(&specs, &opts.cli_features)?;
80    // In `members_with_features_old`, it will add "current" package (determined by the cwd)
81    // So we need filter
82    pkgs.retain(|(m, _)| specs.iter().any(|spec| spec.matches(m.package_id())));
83
84    let (unpublishable, pkgs): (Vec<_>, Vec<_>) = pkgs
85        .into_iter()
86        .partition(|(pkg, _)| pkg.publish() == &Some(vec![]));
87    // If `--workspace` is passed,
88    // the intent is more like "publish all publisable packages in this workspace",
89    // so skip `publish=false` packages.
90    let allow_unpublishable = match &opts.to_publish {
91        Packages::Default => ws.is_virtual(),
92        Packages::All(_) => true,
93        Packages::OptOut(_) => true,
94        Packages::Packages(_) => false,
95    };
96    if !unpublishable.is_empty() && !allow_unpublishable {
97        bail!(
98            "{} cannot be published.\n\
99            `package.publish` must be set to `true` or a non-empty list in Cargo.toml to publish.",
100            unpublishable
101                .iter()
102                .map(|(pkg, _)| format!("`{}`", pkg.name()))
103                .join(", "),
104        );
105    }
106
107    if pkgs.is_empty() {
108        if allow_unpublishable {
109            let n = unpublishable.len();
110            let plural = if n == 1 { "" } else { "s" };
111            ws.gctx().shell().warn(format_args!(
112                "nothing to publish, but found {n} unpublishable package{plural}"
113            ))?;
114            ws.gctx().shell().note(format_args!(
115                "to publish packages, set `package.publish` to `true` or a non-empty list"
116            ))?;
117            return Ok(());
118        } else {
119            unreachable!("must have at least one publishable package");
120        }
121    }
122
123    let just_pkgs: Vec<_> = pkgs.iter().map(|p| p.0).collect();
124    let reg_or_index = match opts.reg_or_index.clone() {
125        Some(r) => {
126            validate_registry(&just_pkgs, Some(&r))?;
127            Some(r)
128        }
129        None => {
130            let reg = super::infer_registry(&just_pkgs)?;
131            validate_registry(&just_pkgs, reg.as_ref())?;
132            if let Some(RegistryOrIndex::Registry(registry)) = &reg {
133                if registry != CRATES_IO_REGISTRY {
134                    // Don't warn for crates.io.
135                    opts.gctx.shell().note(&format!(
136                        "found `{}` as only allowed registry. Publishing to it automatically.",
137                        registry
138                    ))?;
139                }
140            }
141            reg
142        }
143    };
144
145    // This is only used to confirm that we can create a token before we build the package.
146    // This causes the credential provider to be called an extra time, but keeps the same order of errors.
147    let source_ids = super::get_source_id(opts.gctx, reg_or_index.as_ref())?;
148    let (mut registry, mut source) = super::registry(
149        opts.gctx,
150        &source_ids,
151        opts.token.as_ref().map(Secret::as_deref),
152        reg_or_index.as_ref(),
153        true,
154        Some(Operation::Read).filter(|_| !opts.dry_run),
155    )?;
156
157    {
158        let _lock = opts
159            .gctx
160            .acquire_package_cache_lock(CacheLockMode::DownloadExclusive)?;
161
162        for (pkg, _) in &pkgs {
163            verify_unpublished(pkg, &mut source, &source_ids, opts.dry_run, opts.gctx)?;
164            verify_dependencies(pkg, &registry, source_ids.original).map_err(|err| {
165                ManifestError::new(
166                    err.context(format!(
167                        "failed to verify manifest at `{}`",
168                        pkg.manifest_path().display()
169                    )),
170                    pkg.manifest_path().into(),
171                )
172            })?;
173        }
174    }
175
176    let pkg_dep_graph = ops::cargo_package::package_with_dep_graph(
177        ws,
178        &PackageOpts {
179            gctx: opts.gctx,
180            verify: opts.verify,
181            list: false,
182            fmt: ops::PackageMessageFormat::Human,
183            check_metadata: true,
184            allow_dirty: opts.allow_dirty,
185            include_lockfile: true,
186            // `package_with_dep_graph` ignores this field in favor of
187            // the already-resolved list of packages
188            to_package: ops::Packages::Default,
189            targets: opts.targets.clone(),
190            jobs: opts.jobs.clone(),
191            keep_going: opts.keep_going,
192            cli_features: opts.cli_features.clone(),
193            reg_or_index: reg_or_index.clone(),
194            dry_run: opts.dry_run,
195        },
196        pkgs,
197    )?;
198
199    let mut plan = PublishPlan::new(&pkg_dep_graph.graph);
200    // May contains packages from previous rounds as `wait_for_any_publish_confirmation` returns
201    // after it confirms any packages, not all packages, requiring us to handle the rest in the next
202    // iteration.
203    //
204    // As a side effect, any given package's "effective" timeout may be much larger.
205    let mut to_confirm = BTreeSet::new();
206
207    while !plan.is_empty() {
208        // There might not be any ready package, if the previous confirmations
209        // didn't unlock a new one. For example, if `c` depends on `a` and
210        // `b`, and we uploaded `a` and `b` but only confirmed `a`, then on
211        // the following pass through the outer loop nothing will be ready for
212        // upload.
213        let mut ready = plan.take_ready();
214        while let Some(pkg_id) = ready.pop_first() {
215            let (pkg, (_features, tarball)) = &pkg_dep_graph.packages[&pkg_id];
216            opts.gctx.shell().status("Uploading", pkg.package_id())?;
217
218            if !opts.dry_run {
219                let ver = pkg.version().to_string();
220
221                tarball.file().seek(SeekFrom::Start(0))?;
222                let hash = cargo_util::Sha256::new()
223                    .update_file(tarball.file())?
224                    .finish_hex();
225                let operation = Operation::Publish {
226                    name: pkg.name().as_str(),
227                    vers: &ver,
228                    cksum: &hash,
229                };
230                registry.set_token(Some(auth::auth_token(
231                    &opts.gctx,
232                    &source_ids.original,
233                    None,
234                    operation,
235                    vec![],
236                    false,
237                )?));
238            }
239
240            let workspace_context = || {
241                let mut remaining = ready.clone();
242                remaining.extend(plan.iter());
243                if !remaining.is_empty() {
244                    format!(
245                        "\n\nnote: the following crates have not been published yet:\n  {}",
246                        remaining.into_iter().join("\n  ")
247                    )
248                } else {
249                    String::new()
250                }
251            };
252
253            transmit(
254                opts.gctx,
255                ws,
256                pkg,
257                tarball.file(),
258                &mut registry,
259                source_ids.original,
260                opts.dry_run,
261                workspace_context,
262            )?;
263            to_confirm.insert(pkg_id);
264
265            if !opts.dry_run {
266                // Short does not include the registry name.
267                let short_pkg_description = format!("{} v{}", pkg.name(), pkg.version());
268                let source_description = source_ids.original.to_string();
269                ws.gctx().shell().status(
270                    "Uploaded",
271                    format!("{short_pkg_description} to {source_description}"),
272                )?;
273            }
274        }
275
276        let confirmed = if opts.dry_run {
277            to_confirm.clone()
278        } else {
279            const DEFAULT_TIMEOUT: u64 = 60;
280            let timeout = if opts.gctx.cli_unstable().publish_timeout {
281                let timeout: Option<u64> = opts.gctx.get("publish.timeout")?;
282                timeout.unwrap_or(DEFAULT_TIMEOUT)
283            } else {
284                DEFAULT_TIMEOUT
285            };
286            if 0 < timeout {
287                let source_description = source.source_id().to_string();
288                let short_pkg_descriptions = package_list(to_confirm.iter().copied(), "or");
289                if plan.is_empty() {
290                    let report = &[
291                        annotate_snippets::Group::with_title(
292                        annotate_snippets::Level::NOTE
293                            .secondary_title(format!(
294                                "waiting for {short_pkg_descriptions} to be available at {source_description}"
295                            ))),
296                            annotate_snippets::Group::with_title(annotate_snippets::Level::HELP.secondary_title(format!(
297                                "you may press ctrl-c to skip waiting; the {crate} should be available shortly",
298                                crate = if to_confirm.len() == 1 { "crate" } else {"crates"}
299                            ))),
300                    ];
301                    opts.gctx.shell().print_report(report, false)?;
302                } else {
303                    opts.gctx.shell().note(format!(
304                    "waiting for {short_pkg_descriptions} to be available at {source_description}.\n\
305                    {count} remaining {crate} to be published",
306                    count = plan.len(),
307                    crate = if plan.len() == 1 { "crate" } else {"crates"}
308                ))?;
309                }
310
311                let timeout = Duration::from_secs(timeout);
312                let confirmed = wait_for_any_publish_confirmation(
313                    opts.gctx,
314                    source_ids.original,
315                    &to_confirm,
316                    timeout,
317                )?;
318                if !confirmed.is_empty() {
319                    let short_pkg_description = package_list(confirmed.iter().copied(), "and");
320                    opts.gctx.shell().status(
321                        "Published",
322                        format!("{short_pkg_description} at {source_description}"),
323                    )?;
324                } else {
325                    let short_pkg_descriptions = package_list(to_confirm.iter().copied(), "or");
326                    opts.gctx.shell().warn(format!(
327                        "timed out waiting for {short_pkg_descriptions} to be available in {source_description}",
328                    ))?;
329                    opts.gctx.shell().note(format!(
330                        "the registry may have a backlog that is delaying making the \
331                        {crate} available. The {crate} should be available soon.",
332                        crate = if to_confirm.len() == 1 {
333                            "crate"
334                        } else {
335                            "crates"
336                        }
337                    ))?;
338                }
339                confirmed
340            } else {
341                BTreeSet::new()
342            }
343        };
344        if confirmed.is_empty() {
345            // If nothing finished, it means we timed out while waiting for confirmation.
346            // We're going to exit, but first we need to check: have we uploaded everything?
347            if plan.is_empty() {
348                // It's ok that we timed out, because nothing was waiting on dependencies to
349                // be confirmed.
350                break;
351            } else {
352                let failed_list = package_list(plan.iter(), "and");
353                bail!(
354                    "unable to publish {failed_list} due to a timeout while waiting for published dependencies to be available."
355                );
356            }
357        }
358        for id in &confirmed {
359            to_confirm.remove(id);
360        }
361        plan.mark_confirmed(confirmed);
362    }
363
364    Ok(())
365}
366
367/// Poll the registry for any packages that are ready for use.
368///
369/// Returns the subset of `pkgs` that are ready for use.
370/// This will be an empty set if we timed out before confirming anything.
371fn wait_for_any_publish_confirmation(
372    gctx: &GlobalContext,
373    registry_src: SourceId,
374    pkgs: &BTreeSet<PackageId>,
375    timeout: Duration,
376) -> CargoResult<BTreeSet<PackageId>> {
377    let mut source = SourceConfigMap::empty(gctx)?.load(registry_src, &HashSet::new())?;
378    // Disable the source's built-in progress bars. Repeatedly showing a bunch
379    // of independent progress bars can be a little confusing. There is an
380    // overall progress bar managed here.
381    source.set_quiet(true);
382
383    let now = std::time::Instant::now();
384    let sleep_time = Duration::from_secs(1);
385    let max = timeout.as_secs() as usize;
386    let mut progress = Progress::with_style("Waiting", ProgressStyle::Ratio, gctx);
387    progress.tick_now(0, max, "")?;
388    let available = loop {
389        {
390            let _lock = gctx.acquire_package_cache_lock(CacheLockMode::DownloadExclusive)?;
391            // Force re-fetching the source
392            //
393            // As pulling from a git source is expensive, we track when we've done it within the
394            // process to only do it once, but we are one of the rare cases that needs to do it
395            // multiple times
396            gctx.updated_sources().remove(&source.replaced_source_id());
397            source.invalidate_cache();
398            let mut available = BTreeSet::new();
399            for pkg in pkgs {
400                if poll_one_package(registry_src, pkg, &mut source)? {
401                    available.insert(*pkg);
402                }
403            }
404
405            // As soon as any package is available, break this loop so we can see if another
406            // one can be uploaded.
407            if !available.is_empty() {
408                break available;
409            }
410        }
411
412        let elapsed = now.elapsed();
413        if timeout < elapsed {
414            break BTreeSet::new();
415        }
416
417        progress.tick_now(elapsed.as_secs() as usize, max, "")?;
418        std::thread::sleep(sleep_time);
419    };
420
421    Ok(available)
422}
423
424fn poll_one_package(
425    registry_src: SourceId,
426    pkg_id: &PackageId,
427    source: &mut dyn Source,
428) -> CargoResult<bool> {
429    let version_req = format!("={}", pkg_id.version());
430    let query = Dependency::parse(pkg_id.name(), Some(&version_req), registry_src)?;
431    let summaries = loop {
432        // Exact to avoid returning all for path/git
433        match source.query_vec(&query, QueryKind::Exact) {
434            std::task::Poll::Ready(res) => {
435                break res?;
436            }
437            std::task::Poll::Pending => source.block_until_ready()?,
438        }
439    };
440    Ok(!summaries.is_empty())
441}
442
443fn verify_unpublished(
444    pkg: &Package,
445    source: &mut RegistrySource<'_>,
446    source_ids: &RegistrySourceIds,
447    dry_run: bool,
448    gctx: &GlobalContext,
449) -> CargoResult<()> {
450    let query = Dependency::parse(
451        pkg.name(),
452        Some(&pkg.version().to_exact_req().to_string()),
453        source_ids.replacement,
454    )?;
455    let duplicate_query = loop {
456        match source.query_vec(&query, QueryKind::Exact) {
457            std::task::Poll::Ready(res) => {
458                break res?;
459            }
460            std::task::Poll::Pending => source.block_until_ready()?,
461        }
462    };
463    if !duplicate_query.is_empty() {
464        // Move the registry error earlier in the publish process.
465        // Since dry-run wouldn't talk to the registry to get the error, we downgrade it to a
466        // warning.
467        if dry_run {
468            gctx.shell().warn(format!(
469                "crate {}@{} already exists on {}",
470                pkg.name(),
471                pkg.version(),
472                source.describe()
473            ))?;
474        } else {
475            bail!(
476                "crate {}@{} already exists on {}",
477                pkg.name(),
478                pkg.version(),
479                source.describe()
480            );
481        }
482    }
483
484    Ok(())
485}
486
487fn verify_dependencies(
488    pkg: &Package,
489    registry: &Registry,
490    registry_src: SourceId,
491) -> CargoResult<()> {
492    for dep in pkg.dependencies().iter() {
493        if check_dep_has_version(dep, true)? {
494            continue;
495        }
496        // TomlManifest::prepare_for_publish will rewrite the dependency
497        // to be just the `version` field.
498        if dep.source_id() != registry_src {
499            if !dep.source_id().is_registry() {
500                // Consider making SourceId::kind a public type that we can
501                // exhaustively match on. Using match can help ensure that
502                // every kind is properly handled.
503                panic!("unexpected source kind for dependency {:?}", dep);
504            }
505            // Block requests to send to crates.io with alt-registry deps.
506            // This extra hostname check is mostly to assist with testing,
507            // but also prevents someone using `--index` to specify
508            // something that points to crates.io.
509            if registry_src.is_crates_io() || registry.host_is_crates_io() {
510                bail!(
511                    "crates cannot be published to crates.io with dependencies sourced from other\n\
512                       registries. `{}` needs to be published to crates.io before publishing this crate.\n\
513                       (crate `{}` is pulled from {})",
514                    dep.package_name(),
515                    dep.package_name(),
516                    dep.source_id()
517                );
518            }
519        }
520    }
521    Ok(())
522}
523
524pub(crate) fn prepare_transmit(
525    gctx: &GlobalContext,
526    ws: &Workspace<'_>,
527    local_pkg: &Package,
528    registry_id: SourceId,
529) -> CargoResult<NewCrate> {
530    let included = None; // don't filter build-targets
531    let publish_pkg = prepare_for_publish(local_pkg, ws, included)?;
532
533    let deps = publish_pkg
534        .dependencies()
535        .iter()
536        .map(|dep| {
537            // If the dependency is from a different registry, then include the
538            // registry in the dependency.
539            let dep_registry_id = match dep.registry_id() {
540                Some(id) => id,
541                None => SourceId::crates_io(gctx)?,
542            };
543            // In the index and Web API, None means "from the same registry"
544            // whereas in Cargo.toml, it means "from crates.io".
545            let dep_registry = if dep_registry_id != registry_id {
546                Some(dep_registry_id.url().to_string())
547            } else {
548                None
549            };
550
551            Ok(NewCrateDependency {
552                optional: dep.is_optional(),
553                default_features: dep.uses_default_features(),
554                name: dep.package_name().to_string(),
555                features: dep.features().iter().map(|s| s.to_string()).collect(),
556                version_req: dep.version_req().to_string(),
557                target: dep.platform().map(|s| s.to_string()),
558                kind: match dep.kind() {
559                    DepKind::Normal => "normal",
560                    DepKind::Build => "build",
561                    DepKind::Development => "dev",
562                }
563                .to_string(),
564                registry: dep_registry,
565                explicit_name_in_toml: dep.explicit_name_in_toml().map(|s| s.to_string()),
566                artifact: dep.artifact().map(|artifact| {
567                    artifact
568                        .kinds()
569                        .iter()
570                        .map(|x| x.as_str().into_owned())
571                        .collect()
572                }),
573                bindep_target: dep.artifact().and_then(|artifact| {
574                    artifact.target().map(|target| target.as_str().to_owned())
575                }),
576                lib: dep.artifact().map_or(false, |artifact| artifact.is_lib()),
577            })
578        })
579        .collect::<CargoResult<Vec<NewCrateDependency>>>()?;
580    let manifest = publish_pkg.manifest();
581    let ManifestMetadata {
582        ref authors,
583        ref description,
584        ref homepage,
585        ref documentation,
586        ref keywords,
587        ref readme,
588        ref repository,
589        ref license,
590        ref license_file,
591        ref categories,
592        ref badges,
593        ref links,
594        ref rust_version,
595    } = *manifest.metadata();
596    let rust_version = rust_version.as_ref().map(ToString::to_string);
597    let readme_content = local_pkg
598        .manifest()
599        .metadata()
600        .readme
601        .as_ref()
602        .map(|readme| {
603            paths::read(&local_pkg.root().join(readme)).with_context(|| {
604                format!("failed to read `readme` file for package `{}`", local_pkg)
605            })
606        })
607        .transpose()?;
608    if let Some(ref file) = local_pkg.manifest().metadata().license_file {
609        if !local_pkg.root().join(file).exists() {
610            bail!("the license file `{}` does not exist", file)
611        }
612    }
613
614    let string_features = match manifest.normalized_toml().features() {
615        Some(features) => features
616            .iter()
617            .map(|(feat, values)| {
618                (
619                    feat.to_string(),
620                    values.iter().map(|fv| fv.to_string()).collect(),
621                )
622            })
623            .collect::<BTreeMap<String, Vec<String>>>(),
624        None => BTreeMap::new(),
625    };
626
627    Ok(NewCrate {
628        name: publish_pkg.name().to_string(),
629        vers: publish_pkg.version().to_string(),
630        deps,
631        features: string_features,
632        authors: authors.clone(),
633        description: description.clone(),
634        homepage: homepage.clone(),
635        documentation: documentation.clone(),
636        keywords: keywords.clone(),
637        categories: categories.clone(),
638        readme: readme_content,
639        readme_file: readme.clone(),
640        repository: repository.clone(),
641        license: license.clone(),
642        license_file: license_file.clone(),
643        badges: badges.clone(),
644        links: links.clone(),
645        rust_version,
646    })
647}
648
649fn transmit(
650    gctx: &GlobalContext,
651    ws: &Workspace<'_>,
652    pkg: &Package,
653    tarball: &File,
654    registry: &mut Registry,
655    registry_id: SourceId,
656    dry_run: bool,
657    workspace_context: impl Fn() -> String,
658) -> CargoResult<()> {
659    let new_crate = prepare_transmit(gctx, ws, pkg, registry_id)?;
660
661    // Do not upload if performing a dry run
662    if dry_run {
663        gctx.shell().warn("aborting upload due to dry run")?;
664        return Ok(());
665    }
666
667    let warnings = registry.publish(&new_crate, tarball).with_context(|| {
668        format!(
669            "failed to publish {} v{} to registry at {}{}",
670            pkg.name(),
671            pkg.version(),
672            registry.host(),
673            workspace_context()
674        )
675    })?;
676
677    if !warnings.invalid_categories.is_empty() {
678        let msg = format!(
679            "the following are not valid category slugs and were \
680             ignored: {}. Please see https://crates.io/category_slugs \
681             for the list of all category slugs. \
682             ",
683            warnings.invalid_categories.join(", ")
684        );
685        gctx.shell().warn(&msg)?;
686    }
687
688    if !warnings.invalid_badges.is_empty() {
689        let msg = format!(
690            "the following are not valid badges and were ignored: {}. \
691             Either the badge type specified is unknown or a required \
692             attribute is missing. Please see \
693             https://doc.rust-lang.org/cargo/reference/manifest.html#package-metadata \
694             for valid badge types and their required attributes.",
695            warnings.invalid_badges.join(", ")
696        );
697        gctx.shell().warn(&msg)?;
698    }
699
700    if !warnings.other.is_empty() {
701        for msg in warnings.other {
702            gctx.shell().warn(&msg)?;
703        }
704    }
705
706    Ok(())
707}
708
709/// State for tracking dependencies during upload.
710struct PublishPlan {
711    /// Graph of publishable packages where the edges are `(dependency -> dependent)`
712    dependents: Graph<PackageId, ()>,
713    /// The weight of a package is the number of unpublished dependencies it has.
714    dependencies_count: HashMap<PackageId, usize>,
715}
716
717impl PublishPlan {
718    /// Given a package dependency graph, creates a `PublishPlan` for tracking state.
719    fn new(graph: &Graph<PackageId, ()>) -> Self {
720        let dependents = graph.reversed();
721
722        let dependencies_count: HashMap<_, _> = dependents
723            .iter()
724            .map(|id| (*id, graph.edges(id).count()))
725            .collect();
726        Self {
727            dependents,
728            dependencies_count,
729        }
730    }
731
732    fn iter(&self) -> impl Iterator<Item = PackageId> + '_ {
733        self.dependencies_count.iter().map(|(id, _)| *id)
734    }
735
736    fn is_empty(&self) -> bool {
737        self.dependencies_count.is_empty()
738    }
739
740    fn len(&self) -> usize {
741        self.dependencies_count.len()
742    }
743
744    /// Returns the set of packages that are ready for publishing (i.e. have no outstanding dependencies).
745    ///
746    /// These will not be returned in future calls.
747    fn take_ready(&mut self) -> BTreeSet<PackageId> {
748        let ready: BTreeSet<_> = self
749            .dependencies_count
750            .iter()
751            .filter_map(|(id, weight)| (*weight == 0).then_some(*id))
752            .collect();
753        for pkg in &ready {
754            self.dependencies_count.remove(pkg);
755        }
756        ready
757    }
758
759    /// Packages confirmed to be available in the registry, potentially allowing additional
760    /// packages to be "ready".
761    fn mark_confirmed(&mut self, published: impl IntoIterator<Item = PackageId>) {
762        for id in published {
763            for (dependent_id, _) in self.dependents.edges(&id) {
764                if let Some(weight) = self.dependencies_count.get_mut(dependent_id) {
765                    *weight = weight.saturating_sub(1);
766                }
767            }
768        }
769    }
770}
771
772/// Format a collection of packages as a list
773///
774/// e.g. "foo v0.1.0, bar v0.2.0, and baz v0.3.0".
775///
776/// Note: the final separator (e.g. "and" in the previous example) can be chosen.
777fn package_list(pkgs: impl IntoIterator<Item = PackageId>, final_sep: &str) -> String {
778    let mut names: Vec<_> = pkgs
779        .into_iter()
780        .map(|pkg| format!("{} v{}", pkg.name(), pkg.version()))
781        .collect();
782    names.sort();
783
784    match &names[..] {
785        [] => String::new(),
786        [a] => a.clone(),
787        [a, b] => format!("{a} {final_sep} {b}"),
788        [names @ .., last] => {
789            format!("{}, {final_sep} {last}", names.join(", "))
790        }
791    }
792}
793
794fn validate_registry(pkgs: &[&Package], reg_or_index: Option<&RegistryOrIndex>) -> CargoResult<()> {
795    let reg_name = match reg_or_index {
796        Some(RegistryOrIndex::Registry(r)) => Some(r.as_str()),
797        None => Some(CRATES_IO_REGISTRY),
798        Some(RegistryOrIndex::Index(_)) => None,
799    };
800    if let Some(reg_name) = reg_name {
801        for pkg in pkgs {
802            if let Some(allowed) = pkg.publish().as_ref() {
803                if !allowed.iter().any(|a| a == reg_name) {
804                    bail!(
805                        "`{}` cannot be published.\n\
806                         The registry `{}` is not listed in the `package.publish` value in Cargo.toml.",
807                        pkg.name(),
808                        reg_name
809                    );
810                }
811            }
812        }
813    }
814
815    Ok(())
816}
817
818#[cfg(test)]
819mod tests {
820    use crate::{
821        core::{PackageId, SourceId},
822        sources::CRATES_IO_INDEX,
823        util::{Graph, IntoUrl},
824    };
825
826    use super::PublishPlan;
827
828    fn pkg_id(name: &str) -> PackageId {
829        let loc = CRATES_IO_INDEX.into_url().unwrap();
830        PackageId::try_new(name, "1.0.0", SourceId::for_registry(&loc).unwrap()).unwrap()
831    }
832
833    #[test]
834    fn parallel_schedule() {
835        let mut graph: Graph<PackageId, ()> = Graph::new();
836        let a = pkg_id("a");
837        let b = pkg_id("b");
838        let c = pkg_id("c");
839        let d = pkg_id("d");
840        let e = pkg_id("e");
841
842        graph.add(a);
843        graph.add(b);
844        graph.add(c);
845        graph.add(d);
846        graph.add(e);
847        graph.link(a, c);
848        graph.link(b, c);
849        graph.link(c, d);
850        graph.link(c, e);
851
852        let mut order = PublishPlan::new(&graph);
853        let ready: Vec<_> = order.take_ready().into_iter().collect();
854        assert_eq!(ready, vec![d, e]);
855
856        order.mark_confirmed(vec![d]);
857        let ready: Vec<_> = order.take_ready().into_iter().collect();
858        assert!(ready.is_empty());
859
860        order.mark_confirmed(vec![e]);
861        let ready: Vec<_> = order.take_ready().into_iter().collect();
862        assert_eq!(ready, vec![c]);
863
864        order.mark_confirmed(vec![c]);
865        let ready: Vec<_> = order.take_ready().into_iter().collect();
866        assert_eq!(ready, vec![a, b]);
867
868        order.mark_confirmed(vec![a, b]);
869        let ready: Vec<_> = order.take_ready().into_iter().collect();
870        assert!(ready.is_empty());
871    }
872}