Skip to main content

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::fs::File;
9use std::io::Seek;
10use std::io::SeekFrom;
11use std::time::Duration;
12
13use anyhow::Context as _;
14use anyhow::bail;
15use cargo_credential::Operation;
16use cargo_credential::Secret;
17use cargo_util::paths;
18use cargo_util_terminal::report::Level;
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::RegistryClient;
40use crate::ops::registry::RegistrySourceIds;
41use crate::sources::CRATES_IO_REGISTRY;
42use crate::sources::RegistrySource;
43use crate::sources::SourceConfigMap;
44use crate::sources::source::QueryKind;
45use crate::sources::source::Source;
46use crate::util::Graph;
47use crate::util::Progress;
48use crate::util::ProgressStyle;
49use crate::util::VersionExt as _;
50use crate::util::auth;
51use crate::util::cache_lock::CacheLockMode;
52use crate::util::context::JobsConfig;
53use crate::util::errors::ManifestError;
54use crate::util::toml::prepare_for_publish;
55
56use super::super::check_dep_has_version;
57
58pub struct PublishOpts<'gctx> {
59    pub gctx: &'gctx GlobalContext,
60    pub token: Option<Secret<String>>,
61    pub reg_or_index: Option<RegistryOrIndex>,
62    pub verify: bool,
63    pub allow_dirty: bool,
64    pub jobs: Option<JobsConfig>,
65    pub keep_going: bool,
66    pub to_publish: ops::Packages,
67    pub targets: Vec<String>,
68    pub dry_run: bool,
69    pub cli_features: CliFeatures,
70}
71
72pub fn publish(ws: &Workspace<'_>, opts: &PublishOpts<'_>) -> CargoResult<()> {
73    let specs = opts.to_publish.to_package_id_specs(ws)?;
74
75    let member_ids: Vec<_> = ws.members().map(|p| p.package_id()).collect();
76    // Check that the specs match members.
77    for spec in &specs {
78        spec.query(member_ids.clone())?;
79    }
80    let mut pkgs = ws.members_with_features(&specs, &opts.cli_features)?;
81    // In `members_with_features_old`, it will add "current" package (determined by the cwd)
82    // So we need filter
83    pkgs.retain(|(m, _)| specs.iter().any(|spec| spec.matches(m.package_id())));
84
85    let (unpublishable, pkgs): (Vec<_>, Vec<_>) = pkgs
86        .into_iter()
87        .partition(|(pkg, _)| pkg.publish() == &Some(vec![]));
88    // If `--workspace` is passed,
89    // the intent is more like "publish all publisable packages in this workspace",
90    // so skip `publish=false` packages.
91    let allow_unpublishable = match &opts.to_publish {
92        Packages::Default => ws.is_virtual(),
93        Packages::All(_) => true,
94        Packages::OptOut(_) => true,
95        Packages::Packages(_) => false,
96    };
97    if !unpublishable.is_empty() && !allow_unpublishable {
98        bail!(
99            "{} cannot be published.\n\
100            `package.publish` must be set to `true` or a non-empty list in Cargo.toml to publish.",
101            unpublishable
102                .iter()
103                .map(|(pkg, _)| format!("`{}`", pkg.name()))
104                .join(", "),
105        );
106    }
107
108    if pkgs.is_empty() {
109        if allow_unpublishable {
110            let n = unpublishable.len();
111            let plural = if n == 1 { "" } else { "s" };
112            ws.gctx().shell().print_report(
113                &[Level::WARNING
114                    .secondary_title(format!(
115                        "nothing to publish, but found {n} unpublishable package{plural}"
116                    ))
117                    .element(Level::HELP.message(
118                        "to publish packages, set `package.publish` to `true` or a non-empty list",
119                    ))],
120                false,
121            )?;
122            return Ok(());
123        } else {
124            unreachable!("must have at least one publishable package");
125        }
126    }
127
128    let just_pkgs: Vec<_> = pkgs.iter().map(|p| p.0).collect();
129    let reg_or_index = resolve_registry_or_index(opts, &just_pkgs)?;
130
131    // This is only used to confirm that we can create a token before we build the package.
132    // This causes the credential provider to be called an extra time, but keeps the same order of errors.
133    let source_ids = super::get_source_id(opts.gctx, reg_or_index.as_ref())?;
134    let (mut registry, mut source) = super::registry(
135        opts.gctx,
136        &source_ids,
137        opts.token.as_ref().map(Secret::as_deref),
138        reg_or_index.as_ref(),
139        true,
140        Some(Operation::Read).filter(|_| !opts.dry_run),
141    )?;
142
143    {
144        let _lock = opts
145            .gctx
146            .acquire_package_cache_lock(CacheLockMode::DownloadExclusive)?;
147
148        for (pkg, _) in &pkgs {
149            verify_unpublished(pkg, &mut source, &source_ids, opts.dry_run, opts.gctx)?;
150            verify_dependencies(pkg, &registry, source_ids.original).map_err(|err| {
151                ManifestError::new(
152                    err.context(format!(
153                        "failed to verify manifest at `{}`",
154                        pkg.manifest_path().display()
155                    )),
156                    pkg.manifest_path().into(),
157                )
158            })?;
159        }
160    }
161
162    let pkg_dep_graph = ops::cargo_package::package_with_dep_graph(
163        ws,
164        &PackageOpts {
165            gctx: opts.gctx,
166            verify: opts.verify,
167            list: false,
168            fmt: ops::PackageMessageFormat::Human,
169            check_metadata: true,
170            allow_dirty: opts.allow_dirty,
171            include_lockfile: true,
172            // `package_with_dep_graph` ignores this field in favor of
173            // the already-resolved list of packages
174            to_package: ops::Packages::Default,
175            targets: opts.targets.clone(),
176            jobs: opts.jobs.clone(),
177            keep_going: opts.keep_going,
178            cli_features: opts.cli_features.clone(),
179            reg_or_index: reg_or_index.clone(),
180            dry_run: opts.dry_run,
181        },
182        pkgs,
183    )?;
184
185    let mut plan = PublishPlan::new(&pkg_dep_graph.graph);
186    // May contains packages from previous rounds as `wait_for_any_publish_confirmation` returns
187    // after it confirms any packages, not all packages, requiring us to handle the rest in the next
188    // iteration.
189    //
190    // As a side effect, any given package's "effective" timeout may be much larger.
191    let mut to_confirm = BTreeSet::new();
192
193    // Check for circular dependencies before publishing.
194    if plan.has_cycles() {
195        bail!(
196            "circular dependency detected while publishing {}\n\
197             help: to break a cycle between dev-dependencies \
198             and other dependencies, remove the version field \
199             on the dev-dependency so it will be implicitly \
200             stripped on publish",
201            package_list(plan.cycle_members(), "and")
202        );
203    }
204
205    while !plan.is_empty() {
206        // There might not be any ready package, if the previous confirmations
207        // didn't unlock a new one. For example, if `c` depends on `a` and
208        // `b`, and we uploaded `a` and `b` but only confirmed `a`, then on
209        // the following pass through the outer loop nothing will be ready for
210        // upload.
211        let mut ready = plan.take_ready();
212
213        if ready.is_empty() && to_confirm.is_empty() {
214            // Cycles are caught above; reaching here means an unexpected stall.
215            return Err(crate::util::internal(format!(
216                "no packages ready to publish but {} packages remain in plan with {} awaiting confirmation: {}",
217                plan.len(),
218                to_confirm.len(),
219                package_list(plan.iter(), "and")
220            )));
221        }
222
223        while let Some(pkg_id) = ready.pop_first() {
224            let (pkg, (_features, tarball)) = &pkg_dep_graph.packages[&pkg_id];
225            opts.gctx.shell().status("Uploading", pkg.package_id())?;
226
227            if !opts.dry_run {
228                let ver = pkg.version().to_string();
229
230                tarball.file().seek(SeekFrom::Start(0))?;
231                let hash = cargo_util::Sha256::new()
232                    .update_file(tarball.file())?
233                    .finish_hex();
234                let operation = Operation::Publish {
235                    name: pkg.name().as_str(),
236                    vers: &ver,
237                    cksum: &hash,
238                };
239                registry.set_token(Some(auth::auth_token(
240                    &opts.gctx,
241                    &source_ids.original,
242                    None,
243                    operation,
244                    vec![],
245                    false,
246                )?));
247            }
248
249            let workspace_context = || {
250                let mut remaining = ready.clone();
251                remaining.extend(plan.iter());
252                if !remaining.is_empty() {
253                    format!(
254                        "\n\nnote: the following crates have not been published yet:\n  {}",
255                        remaining.into_iter().join("\n  ")
256                    )
257                } else {
258                    String::new()
259                }
260            };
261
262            transmit(
263                opts.gctx,
264                ws,
265                pkg,
266                tarball.file(),
267                &mut registry,
268                source_ids.original,
269                opts.dry_run,
270                workspace_context,
271            )?;
272            to_confirm.insert(pkg_id);
273
274            if !opts.dry_run {
275                // Short does not include the registry name.
276                let short_pkg_description = format!("{} v{}", pkg.name(), pkg.version());
277                let source_description = source_ids.original.to_string();
278                ws.gctx().shell().status(
279                    "Uploaded",
280                    format!("{short_pkg_description} to {source_description}"),
281                )?;
282            }
283        }
284
285        let confirmed = if opts.dry_run {
286            to_confirm.clone()
287        } else {
288            const DEFAULT_TIMEOUT: u64 = 60;
289            let timeout = if opts.gctx.cli_unstable().publish_timeout {
290                let timeout: Option<u64> = opts.gctx.get("publish.timeout")?;
291                timeout.unwrap_or(DEFAULT_TIMEOUT)
292            } else {
293                DEFAULT_TIMEOUT
294            };
295            if 0 < timeout {
296                let source_description = source.source_id().to_string();
297                let short_pkg_descriptions = package_list(to_confirm.iter().copied(), "or");
298                if plan.is_empty() {
299                    let report = &[
300                        cargo_util_terminal::report::Group::with_title(
301                        cargo_util_terminal::report::Level::NOTE
302                            .secondary_title(format!(
303                                "waiting for {short_pkg_descriptions} to be available at {source_description}"
304                            ))),
305                            cargo_util_terminal::report::Group::with_title(cargo_util_terminal::report::Level::HELP.secondary_title(format!(
306                                "you may press ctrl-c to skip waiting; the {crate} should be available shortly",
307                                crate = if to_confirm.len() == 1 { "crate" } else {"crates"}
308                            ))),
309                    ];
310                    opts.gctx.shell().print_report(report, false)?;
311                } else {
312                    opts.gctx.shell().note(format!(
313                    "waiting for {short_pkg_descriptions} to be available at {source_description}.\n\
314                    {count} remaining {crate} to be published",
315                    count = plan.len(),
316                    crate = if plan.len() == 1 { "crate" } else {"crates"}
317                ))?;
318                }
319
320                let timeout = Duration::from_secs(timeout);
321                let confirmed = wait_for_any_publish_confirmation(
322                    opts.gctx,
323                    source_ids.original,
324                    &to_confirm,
325                    timeout,
326                )?;
327                if !confirmed.is_empty() {
328                    let short_pkg_description = package_list(confirmed.iter().copied(), "and");
329                    opts.gctx.shell().status(
330                        "Published",
331                        format!("{short_pkg_description} at {source_description}"),
332                    )?;
333                } else {
334                    let short_pkg_descriptions = package_list(to_confirm.iter().copied(), "or");
335                    let krate = if to_confirm.len() == 1 {
336                        "crate"
337                    } else {
338                        "crates"
339                    };
340                    opts.gctx.shell().print_report(
341                        &[Level::WARNING
342                            .secondary_title(format!(
343                                "timed out waiting for {short_pkg_descriptions} \
344                                    to be available in {source_description}",
345                            ))
346                            .element(Level::NOTE.message(format!(
347                                "the registry may have a backlog that is delaying making the \
348                                {krate} available. The {krate} should be available soon.",
349                            )))],
350                        false,
351                    )?;
352                }
353                confirmed
354            } else {
355                BTreeSet::new()
356            }
357        };
358        if confirmed.is_empty() {
359            // If nothing finished, it means we timed out while waiting for confirmation.
360            // We're going to exit, but first we need to check: have we uploaded everything?
361            if plan.is_empty() {
362                // It's ok that we timed out, because nothing was waiting on dependencies to
363                // be confirmed.
364                break;
365            } else {
366                let failed_list = package_list(plan.iter(), "and");
367                bail!(
368                    "unable to publish {failed_list} due to a timeout while waiting for published dependencies to be available."
369                );
370            }
371        }
372        for id in &confirmed {
373            to_confirm.remove(id);
374        }
375        plan.mark_confirmed(confirmed);
376    }
377
378    Ok(())
379}
380
381/// Poll the registry for any packages that are ready for use.
382///
383/// Returns the subset of `pkgs` that are ready for use.
384/// This will be an empty set if we timed out before confirming anything.
385fn wait_for_any_publish_confirmation(
386    gctx: &GlobalContext,
387    registry_src: SourceId,
388    pkgs: &BTreeSet<PackageId>,
389    timeout: Duration,
390) -> CargoResult<BTreeSet<PackageId>> {
391    let mut source = SourceConfigMap::empty(gctx)?.load(registry_src)?;
392    // Disable the source's built-in progress bars. Repeatedly showing a bunch
393    // of independent progress bars can be a little confusing. There is an
394    // overall progress bar managed here.
395    source.set_quiet(true);
396
397    let now = std::time::Instant::now();
398    let sleep_time = Duration::from_secs(1);
399    let max = timeout.as_secs() as usize;
400    let mut progress = Progress::with_style("Waiting", ProgressStyle::Ratio, gctx);
401    progress.tick_now(0, max, "")?;
402    let available = loop {
403        {
404            let _lock = gctx.acquire_package_cache_lock(CacheLockMode::DownloadExclusive)?;
405            // Force re-fetching the source
406            //
407            // As pulling from a git source is expensive, we track when we've done it within the
408            // process to only do it once, but we are one of the rare cases that needs to do it
409            // multiple times
410            gctx.updated_sources().remove(&source.replaced_source_id());
411            source.invalidate_cache();
412            let mut available = BTreeSet::new();
413            for pkg in pkgs {
414                if poll_one_package(registry_src, pkg, &mut *source)? {
415                    available.insert(*pkg);
416                }
417            }
418
419            // As soon as any package is available, break this loop so we can see if another
420            // one can be uploaded.
421            if !available.is_empty() {
422                break available;
423            }
424        }
425
426        let elapsed = now.elapsed();
427        if timeout < elapsed {
428            break BTreeSet::new();
429        }
430
431        progress.tick_now(elapsed.as_secs() as usize, max, "")?;
432        std::thread::sleep(sleep_time);
433    };
434
435    Ok(available)
436}
437
438fn poll_one_package(
439    registry_src: SourceId,
440    pkg_id: &PackageId,
441    source: &dyn Source,
442) -> CargoResult<bool> {
443    let version_req = format!("={}", pkg_id.version());
444    let query = Dependency::parse(pkg_id.name(), Some(&version_req), registry_src)?;
445    // Exact to avoid returning all for path/git
446    let summaries = crate::util::block_on(source.query_vec(&query, QueryKind::Exact))?;
447    Ok(!summaries.is_empty())
448}
449
450fn verify_unpublished(
451    pkg: &Package,
452    source: &mut RegistrySource<'_>,
453    source_ids: &RegistrySourceIds,
454    dry_run: bool,
455    gctx: &GlobalContext,
456) -> CargoResult<()> {
457    let query = Dependency::parse(
458        pkg.name(),
459        Some(&pkg.version().to_exact_req().to_string()),
460        source_ids.replacement,
461    )?;
462    let duplicate_query = crate::util::block_on(source.query_vec(&query, QueryKind::Exact))?;
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<RegistryClient<'_>>,
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<RegistryClient<'_>>,
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 ignored: {}",
680            warnings.invalid_categories.join(", ")
681        );
682        gctx.shell().print_report(
683            &[Level::WARNING
684                .secondary_title(msg)
685                .element(Level::HELP.message(
686                "please see <https://crates.io/category_slugs> for the list of all category slugs",
687            ))],
688            false,
689        )?;
690    }
691
692    if !warnings.invalid_badges.is_empty() {
693        let msg = format!(
694            "the following are not valid badges and were ignored: {}",
695            warnings.invalid_badges.join(", ")
696        );
697        gctx.shell().print_report(
698            &[Level::WARNING.secondary_title(msg).elements([
699                Level::NOTE.message(
700                    "either the badge type specified is unknown or a required \
701                    attribute is missing",
702                ),
703                Level::HELP.message(
704                    "please see \
705                    <https://doc.rust-lang.org/cargo/reference/manifest.html#package-metadata> \
706                    for valid badge types and their required attributes",
707                ),
708            ])],
709            false,
710        )?;
711    }
712
713    if !warnings.other.is_empty() {
714        for msg in warnings.other {
715            gctx.shell().warn(&msg)?;
716        }
717    }
718
719    Ok(())
720}
721
722/// State for tracking dependencies during upload.
723struct PublishPlan {
724    /// Graph of publishable packages where the edges are `(dependency -> dependent)`
725    dependents: Graph<PackageId, ()>,
726    /// The original graph of publishable packages where the edges are `(dependent -> dependency)`
727    graph: Graph<PackageId, ()>,
728    /// The weight of a package is the number of unpublished dependencies it has.
729    dependencies_count: HashMap<PackageId, usize>,
730}
731
732impl PublishPlan {
733    /// Given a package dependency graph, creates a `PublishPlan` for tracking state.
734    fn new(graph: &Graph<PackageId, ()>) -> Self {
735        let dependents = graph.reversed();
736
737        let dependencies_count: HashMap<_, _> = dependents
738            .iter()
739            .map(|id| (*id, graph.edges(id).count()))
740            .collect();
741        Self {
742            dependents,
743            graph: graph.clone(),
744            dependencies_count,
745        }
746    }
747
748    fn iter(&self) -> impl Iterator<Item = PackageId> + '_ {
749        self.dependencies_count.iter().map(|(id, _)| *id)
750    }
751
752    fn is_empty(&self) -> bool {
753        self.dependencies_count.is_empty()
754    }
755
756    fn len(&self) -> usize {
757        self.dependencies_count.len()
758    }
759
760    /// Determines whether the dependency graph contains any circular dependencies.
761    fn has_cycles(&self) -> bool {
762        !self.cycle_members().is_empty()
763    }
764
765    /// Identifies and returns the packages involved in a circular dependency.
766    fn cycle_members(&self) -> Vec<PackageId> {
767        let mut remaining: BTreeSet<_> = self.dependencies_count.keys().copied().collect();
768        loop {
769            let to_remove: Vec<_> = remaining
770                .iter()
771                .filter(|&id| {
772                    self.graph
773                        .edges(id)
774                        .all(|(child, _)| !remaining.contains(child))
775                })
776                .copied()
777                .collect();
778            if to_remove.is_empty() {
779                break;
780            }
781            for id in to_remove {
782                remaining.remove(&id);
783            }
784        }
785        remaining.into_iter().collect()
786    }
787
788    /// Returns the set of packages that are ready for publishing (i.e. have no outstanding dependencies).
789    ///
790    /// These will not be returned in future calls.
791    fn take_ready(&mut self) -> BTreeSet<PackageId> {
792        let ready: BTreeSet<_> = self
793            .dependencies_count
794            .iter()
795            .filter_map(|(id, weight)| (*weight == 0).then_some(*id))
796            .collect();
797        for pkg in &ready {
798            self.dependencies_count.remove(pkg);
799        }
800        ready
801    }
802
803    /// Packages confirmed to be available in the registry, potentially allowing additional
804    /// packages to be "ready".
805    fn mark_confirmed(&mut self, published: impl IntoIterator<Item = PackageId>) {
806        for id in published {
807            for (dependent_id, _) in self.dependents.edges(&id) {
808                if let Some(weight) = self.dependencies_count.get_mut(dependent_id) {
809                    *weight = weight.saturating_sub(1);
810                }
811            }
812        }
813    }
814}
815
816/// Format a collection of packages as a list
817///
818/// e.g. "foo v0.1.0, bar v0.2.0, and baz v0.3.0".
819///
820/// Note: the final separator (e.g. "and" in the previous example) can be chosen.
821fn package_list(pkgs: impl IntoIterator<Item = PackageId>, final_sep: &str) -> String {
822    let mut names: Vec<_> = pkgs
823        .into_iter()
824        .map(|pkg| format!("{} v{}", pkg.name(), pkg.version()))
825        .collect();
826    names.sort();
827
828    match &names[..] {
829        [] => String::new(),
830        [a] => a.clone(),
831        [a, b] => format!("{a} {final_sep} {b}"),
832        [names @ .., last] => {
833            format!("{}, {final_sep} {last}", names.join(", "))
834        }
835    }
836}
837
838fn resolve_registry_or_index(
839    opts: &PublishOpts<'_>,
840    just_pkgs: &[&Package],
841) -> CargoResult<Option<RegistryOrIndex>> {
842    let opt_index_or_registry = opts.reg_or_index.clone();
843
844    let res = match opt_index_or_registry {
845        ref r @ Some(ref registry_or_index) => {
846            validate_registry(just_pkgs, r.as_ref())?;
847
848            let registry_is_specified_by_any_package = just_pkgs
849                .iter()
850                .any(|pkg| pkg.publish().as_ref().map(|v| v.len()).unwrap_or(0) > 0);
851
852            if registry_is_specified_by_any_package && registry_or_index.is_index() {
853                opts.gctx.shell().warn(r#"`--index` will ignore registries set by `package.publish` in Cargo.toml, and may cause unexpected push to prohibited registry
854help: use `--registry` instead or set `publish = true` in Cargo.toml to suppress this warning"#)?;
855            }
856
857            r.clone()
858        }
859        None => {
860            let reg = super::infer_registry(&just_pkgs)?;
861            validate_registry(&just_pkgs, reg.as_ref())?;
862            if let Some(RegistryOrIndex::Registry(registry)) = &reg {
863                if registry != CRATES_IO_REGISTRY {
864                    // Don't warn for crates.io.
865                    opts.gctx.shell().note(&format!(
866                        "found `{}` as only allowed registry. Publishing to it automatically.",
867                        registry
868                    ))?;
869                }
870            }
871            reg
872        }
873    };
874
875    Ok(res)
876}
877
878fn validate_registry(pkgs: &[&Package], reg_or_index: Option<&RegistryOrIndex>) -> CargoResult<()> {
879    let reg_name = match reg_or_index {
880        Some(RegistryOrIndex::Registry(r)) => Some(r.as_str()),
881        None => Some(CRATES_IO_REGISTRY),
882        Some(RegistryOrIndex::Index(_)) => None,
883    };
884    if let Some(reg_name) = reg_name {
885        for pkg in pkgs {
886            if let Some(allowed) = pkg.publish().as_ref() {
887                if !allowed.iter().any(|a| a == reg_name) {
888                    bail!(
889                        "`{}` cannot be published.\n\
890                         The registry `{}` is not listed in the `package.publish` value in Cargo.toml.",
891                        pkg.name(),
892                        reg_name
893                    );
894                }
895            }
896        }
897    }
898
899    Ok(())
900}
901
902#[cfg(test)]
903mod tests {
904    use crate::{
905        core::{PackageId, SourceId},
906        sources::CRATES_IO_INDEX,
907        util::{Graph, IntoUrl},
908    };
909
910    use super::PublishPlan;
911
912    fn pkg_id(name: &str) -> PackageId {
913        let loc = CRATES_IO_INDEX.into_url().unwrap();
914        PackageId::try_new(name, "1.0.0", SourceId::for_registry(&loc).unwrap()).unwrap()
915    }
916
917    #[test]
918    fn parallel_schedule() {
919        let mut graph: Graph<PackageId, ()> = Graph::new();
920        let a = pkg_id("a");
921        let b = pkg_id("b");
922        let c = pkg_id("c");
923        let d = pkg_id("d");
924        let e = pkg_id("e");
925
926        graph.add(a);
927        graph.add(b);
928        graph.add(c);
929        graph.add(d);
930        graph.add(e);
931        graph.link(a, c);
932        graph.link(b, c);
933        graph.link(c, d);
934        graph.link(c, e);
935
936        let mut order = PublishPlan::new(&graph);
937        let ready: Vec<_> = order.take_ready().into_iter().collect();
938        assert_eq!(ready, vec![d, e]);
939
940        order.mark_confirmed(vec![d]);
941        let ready: Vec<_> = order.take_ready().into_iter().collect();
942        assert!(ready.is_empty());
943
944        order.mark_confirmed(vec![e]);
945        let ready: Vec<_> = order.take_ready().into_iter().collect();
946        assert_eq!(ready, vec![c]);
947
948        order.mark_confirmed(vec![c]);
949        let ready: Vec<_> = order.take_ready().into_iter().collect();
950        assert_eq!(ready, vec![a, b]);
951
952        order.mark_confirmed(vec![a, b]);
953        let ready: Vec<_> = order.take_ready().into_iter().collect();
954        assert!(ready.is_empty());
955    }
956}