Skip to main content

cargo/ops/
cargo_generate_lockfile.rs

1use std::collections::{BTreeMap, HashSet};
2
3use log::debug;
4use termcolor::Color::{self, Cyan, Green, Red};
5
6use crate::core::registry::PackageRegistry;
7use crate::core::resolver::Method;
8use crate::core::PackageId;
9use crate::core::{Resolve, SourceId, Workspace};
10use crate::ops;
11use crate::util::config::Config;
12use crate::util::CargoResult;
13
14pub struct UpdateOptions<'a> {
15    pub config: &'a Config,
16    pub to_update: Vec<String>,
17    pub precise: Option<&'a str>,
18    pub aggressive: bool,
19    pub dry_run: bool,
20}
21
22pub fn generate_lockfile(ws: &Workspace<'_>) -> CargoResult<()> {
23    let mut registry = PackageRegistry::new(ws.config())?;
24    let resolve = ops::resolve_with_previous(
25        &mut registry,
26        ws,
27        Method::Everything,
28        None,
29        None,
30        &[],
31        true,
32        true,
33    )?;
34    ops::write_pkg_lockfile(ws, &resolve)?;
35    Ok(())
36}
37
38pub fn update_lockfile(ws: &Workspace<'_>, opts: &UpdateOptions<'_>) -> CargoResult<()> {
39    if opts.aggressive && opts.precise.is_some() {
40        failure::bail!("cannot specify both aggressive and precise simultaneously")
41    }
42
43    if ws.members().count() == 0 {
44        failure::bail!("you can't generate a lockfile for an empty workspace.")
45    }
46
47    if opts.config.cli_unstable().offline {
48        failure::bail!("you can't update in the offline mode");
49    }
50
51    let previous_resolve = match ops::load_pkg_lockfile(ws)? {
52        Some(resolve) => resolve,
53        None => return generate_lockfile(ws),
54    };
55    let mut registry = PackageRegistry::new(opts.config)?;
56    let mut to_avoid = HashSet::new();
57
58    if opts.to_update.is_empty() {
59        to_avoid.extend(previous_resolve.iter());
60    } else {
61        let mut sources = Vec::new();
62        for name in opts.to_update.iter() {
63            let dep = previous_resolve.query(name)?;
64            if opts.aggressive {
65                fill_with_deps(&previous_resolve, dep, &mut to_avoid, &mut HashSet::new());
66            } else {
67                to_avoid.insert(dep);
68                sources.push(match opts.precise {
69                    Some(precise) => {
70                        // TODO: see comment in `resolve.rs` as well, but this
71                        //       seems like a pretty hokey reason to single out
72                        //       the registry as well.
73                        let precise = if dep.source_id().is_registry() {
74                            format!("{}={}->{}", dep.name(), dep.version(), precise)
75                        } else {
76                            precise.to_string()
77                        };
78                        dep.source_id().with_precise(Some(precise))
79                    }
80                    None => dep.source_id().with_precise(None),
81                });
82            }
83        }
84        registry.add_sources(sources)?;
85    }
86
87    let resolve = ops::resolve_with_previous(
88        &mut registry,
89        ws,
90        Method::Everything,
91        Some(&previous_resolve),
92        Some(&to_avoid),
93        &[],
94        true,
95        true,
96    )?;
97
98    // Summarize what is changing for the user.
99    let print_change = |status: &str, msg: String, color: Color| {
100        opts.config.shell().status_with_color(status, msg, color)
101    };
102    for (removed, added) in compare_dependency_graphs(&previous_resolve, &resolve) {
103        if removed.len() == 1 && added.len() == 1 {
104            let msg = if removed[0].source_id().is_git() {
105                format!(
106                    "{} -> #{}",
107                    removed[0],
108                    &added[0].source_id().precise().unwrap()[..8]
109                )
110            } else {
111                format!("{} -> v{}", removed[0], added[0].version())
112            };
113            print_change("Updating", msg, Green)?;
114        } else {
115            for package in removed.iter() {
116                print_change("Removing", format!("{}", package), Red)?;
117            }
118            for package in added.iter() {
119                print_change("Adding", format!("{}", package), Cyan)?;
120            }
121        }
122    }
123    if opts.dry_run {
124        opts.config
125            .shell()
126            .warn("not updating lockfile due to dry run")?;
127    } else {
128        ops::write_pkg_lockfile(ws, &resolve)?;
129    }
130    return Ok(());
131
132    fn fill_with_deps<'a>(
133        resolve: &'a Resolve,
134        dep: PackageId,
135        set: &mut HashSet<PackageId>,
136        visited: &mut HashSet<PackageId>,
137    ) {
138        if !visited.insert(dep) {
139            return;
140        }
141        set.insert(dep);
142        for dep in resolve.deps_not_replaced(dep) {
143            fill_with_deps(resolve, dep, set, visited);
144        }
145    }
146
147    fn compare_dependency_graphs(
148        previous_resolve: &Resolve,
149        resolve: &Resolve,
150    ) -> Vec<(Vec<PackageId>, Vec<PackageId>)> {
151        fn key(dep: PackageId) -> (&'static str, SourceId) {
152            (dep.name().as_str(), dep.source_id())
153        }
154
155        // Removes all package ids in `b` from `a`. Note that this is somewhat
156        // more complicated because the equality for source ids does not take
157        // precise versions into account (e.g. git shas), but we want to take
158        // that into account here.
159        fn vec_subtract(a: &[PackageId], b: &[PackageId]) -> Vec<PackageId> {
160            a.iter()
161                .filter(|a| {
162                    // If this package id is not found in `b`, then it's definitely
163                    // in the subtracted set
164                    let i = match b.binary_search(a) {
165                        Ok(i) => i,
166                        Err(..) => return true,
167                    };
168
169                    // If we've found `a` in `b`, then we iterate over all instances
170                    // (we know `b` is sorted) and see if they all have different
171                    // precise versions. If so, then `a` isn't actually in `b` so
172                    // we'll let it through.
173                    //
174                    // Note that we only check this for non-registry sources,
175                    // however, as registries contain enough version information in
176                    // the package id to disambiguate
177                    if a.source_id().is_registry() {
178                        return false;
179                    }
180                    b[i..]
181                        .iter()
182                        .take_while(|b| a == b)
183                        .all(|b| a.source_id().precise() != b.source_id().precise())
184                })
185                .cloned()
186                .collect()
187        }
188
189        // Map (package name, package source) to (removed versions, added versions).
190        let mut changes = BTreeMap::new();
191        let empty = (Vec::new(), Vec::new());
192        for dep in previous_resolve.iter() {
193            changes
194                .entry(key(dep))
195                .or_insert_with(|| empty.clone())
196                .0
197                .push(dep);
198        }
199        for dep in resolve.iter() {
200            changes
201                .entry(key(dep))
202                .or_insert_with(|| empty.clone())
203                .1
204                .push(dep);
205        }
206
207        for v in changes.values_mut() {
208            let (ref mut old, ref mut new) = *v;
209            old.sort();
210            new.sort();
211            let removed = vec_subtract(old, new);
212            let added = vec_subtract(new, old);
213            *old = removed;
214            *new = added;
215        }
216        debug!("{:#?}", changes);
217
218        changes.into_iter().map(|(_, v)| v).collect()
219    }
220}