Skip to main content

cargo/sources/git/
source.rs

1use std::fmt::{self, Debug, Formatter};
2
3use log::trace;
4use url::Url;
5
6use crate::core::source::{MaybePackage, Source, SourceId};
7use crate::core::GitReference;
8use crate::core::{Dependency, Package, PackageId, Summary};
9use crate::sources::git::utils::{GitRemote, GitRevision};
10use crate::sources::PathSource;
11use crate::util::errors::CargoResult;
12use crate::util::hex::short_hash;
13use crate::util::Config;
14
15pub struct GitSource<'cfg> {
16    remote: GitRemote,
17    reference: GitReference,
18    source_id: SourceId,
19    path_source: Option<PathSource<'cfg>>,
20    rev: Option<GitRevision>,
21    ident: String,
22    config: &'cfg Config,
23}
24
25impl<'cfg> GitSource<'cfg> {
26    pub fn new(source_id: SourceId, config: &'cfg Config) -> CargoResult<GitSource<'cfg>> {
27        assert!(source_id.is_git(), "id is not git, id={}", source_id);
28
29        let remote = GitRemote::new(source_id.url());
30        let ident = ident(source_id.url())?;
31
32        let reference = match source_id.precise() {
33            Some(s) => GitReference::Rev(s.to_string()),
34            None => source_id.git_reference().unwrap().clone(),
35        };
36
37        let source = GitSource {
38            remote,
39            reference,
40            source_id,
41            path_source: None,
42            rev: None,
43            ident,
44            config,
45        };
46
47        Ok(source)
48    }
49
50    pub fn url(&self) -> &Url {
51        self.remote.url()
52    }
53
54    pub fn read_packages(&mut self) -> CargoResult<Vec<Package>> {
55        if self.path_source.is_none() {
56            self.update()?;
57        }
58        self.path_source.as_mut().unwrap().read_packages()
59    }
60}
61
62fn ident(url: &Url) -> CargoResult<String> {
63    let url = canonicalize_url(url)?;
64    let ident = url
65        .path_segments()
66        .and_then(|mut s| s.next_back())
67        .unwrap_or("");
68
69    let ident = if ident == "" { "_empty" } else { ident };
70
71    Ok(format!("{}-{}", ident, short_hash(&url)))
72}
73
74// Some hacks and heuristics for making equivalent URLs hash the same
75pub fn canonicalize_url(url: &Url) -> CargoResult<Url> {
76    let mut url = url.clone();
77
78    // cannot-be-a-base-urls are not supported
79    // eg. github.com:rust-lang-nursery/rustfmt.git
80    if url.cannot_be_a_base() {
81        failure::bail!(
82            "invalid url `{}`: cannot-be-a-base-URLs are not supported",
83            url
84        )
85    }
86
87    // Strip a trailing slash
88    if url.path().ends_with('/') {
89        url.path_segments_mut().unwrap().pop_if_empty();
90    }
91
92    // HACKHACK: For GitHub URL's specifically just lowercase
93    // everything.  GitHub treats both the same, but they hash
94    // differently, and we're gonna be hashing them. This wants a more
95    // general solution, and also we're almost certainly not using the
96    // same case conversion rules that GitHub does. (#84)
97    if url.host_str() == Some("github.com") {
98        url.set_scheme("https").unwrap();
99        let path = url.path().to_lowercase();
100        url.set_path(&path);
101    }
102
103    // Repos generally can be accessed with or w/o '.git'
104    let needs_chopping = url.path().ends_with(".git");
105    if needs_chopping {
106        let last = {
107            let last = url.path_segments().unwrap().next_back().unwrap();
108            last[..last.len() - 4].to_owned()
109        };
110        url.path_segments_mut().unwrap().pop().push(&last);
111    }
112
113    Ok(url)
114}
115
116impl<'cfg> Debug for GitSource<'cfg> {
117    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
118        write!(f, "git repo at {}", self.remote.url())?;
119
120        match self.reference.pretty_ref() {
121            Some(s) => write!(f, " ({})", s),
122            None => Ok(()),
123        }
124    }
125}
126
127impl<'cfg> Source for GitSource<'cfg> {
128    fn query(&mut self, dep: &Dependency, f: &mut dyn FnMut(Summary)) -> CargoResult<()> {
129        let src = self
130            .path_source
131            .as_mut()
132            .expect("BUG: update() must be called before query()");
133        src.query(dep, f)
134    }
135
136    fn fuzzy_query(&mut self, dep: &Dependency, f: &mut dyn FnMut(Summary)) -> CargoResult<()> {
137        let src = self
138            .path_source
139            .as_mut()
140            .expect("BUG: update() must be called before query()");
141        src.fuzzy_query(dep, f)
142    }
143
144    fn supports_checksums(&self) -> bool {
145        false
146    }
147
148    fn requires_precise(&self) -> bool {
149        true
150    }
151
152    fn source_id(&self) -> SourceId {
153        self.source_id
154    }
155
156    fn update(&mut self) -> CargoResult<()> {
157        let lock =
158            self.config
159                .git_path()
160                .open_rw(".cargo-lock-git", self.config, "the git checkouts")?;
161
162        let db_path = lock.parent().join("db").join(&self.ident);
163
164        if self.config.cli_unstable().offline && !db_path.exists() {
165            failure::bail!(
166                "can't checkout from '{}': you are in the offline mode (-Z offline)",
167                self.remote.url()
168            );
169        }
170
171        // Resolve our reference to an actual revision, and check if the
172        // database already has that revision. If it does, we just load a
173        // database pinned at that revision, and if we don't we issue an update
174        // to try to find the revision.
175        let actual_rev = self.remote.rev_for(&db_path, &self.reference);
176        let should_update = actual_rev.is_err() || self.source_id.precise().is_none();
177
178        let (db, actual_rev) = if should_update && !self.config.cli_unstable().offline {
179            self.config.shell().status(
180                "Updating",
181                format!("git repository `{}`", self.remote.url()),
182            )?;
183
184            trace!("updating git source `{:?}`", self.remote);
185
186            self.remote
187                .checkout(&db_path, &self.reference, self.config)?
188        } else {
189            (self.remote.db_at(&db_path)?, actual_rev.unwrap())
190        };
191
192        // Don’t use the full hash,
193        // to contribute less to reaching the path length limit on Windows:
194        // https://github.com/servo/servo/pull/14397
195        let short_id = db.to_short_id(&actual_rev).unwrap();
196
197        let checkout_path = lock
198            .parent()
199            .join("checkouts")
200            .join(&self.ident)
201            .join(short_id.as_str());
202
203        // Copy the database to the checkout location. After this we could drop
204        // the lock on the database as we no longer needed it, but we leave it
205        // in scope so the destructors here won't tamper with too much.
206        // Checkout is immutable, so we don't need to protect it with a lock once
207        // it is created.
208        db.copy_to(actual_rev.clone(), &checkout_path, self.config)?;
209
210        let source_id = self.source_id.with_precise(Some(actual_rev.to_string()));
211        let path_source = PathSource::new_recursive(&checkout_path, source_id, self.config);
212
213        self.path_source = Some(path_source);
214        self.rev = Some(actual_rev);
215        self.path_source.as_mut().unwrap().update()
216    }
217
218    fn download(&mut self, id: PackageId) -> CargoResult<MaybePackage> {
219        trace!(
220            "getting packages for package id `{}` from `{:?}`",
221            id,
222            self.remote
223        );
224        self.path_source
225            .as_mut()
226            .expect("BUG: update() must be called before get()")
227            .download(id)
228    }
229
230    fn finish_download(&mut self, _id: PackageId, _data: Vec<u8>) -> CargoResult<Package> {
231        panic!("no download should have started")
232    }
233
234    fn fingerprint(&self, _pkg: &Package) -> CargoResult<String> {
235        Ok(self.rev.as_ref().unwrap().to_string())
236    }
237
238    fn describe(&self) -> String {
239        format!("git repository {}", self.source_id)
240    }
241}
242
243#[cfg(test)]
244mod test {
245    use super::ident;
246    use crate::util::ToUrl;
247    use url::Url;
248
249    #[test]
250    pub fn test_url_to_path_ident_with_path() {
251        let ident = ident(&url("https://github.com/carlhuda/cargo")).unwrap();
252        assert!(ident.starts_with("cargo-"));
253    }
254
255    #[test]
256    pub fn test_url_to_path_ident_without_path() {
257        let ident = ident(&url("https://github.com")).unwrap();
258        assert!(ident.starts_with("_empty-"));
259    }
260
261    #[test]
262    fn test_canonicalize_idents_by_stripping_trailing_url_slash() {
263        let ident1 = ident(&url("https://github.com/PistonDevelopers/piston/")).unwrap();
264        let ident2 = ident(&url("https://github.com/PistonDevelopers/piston")).unwrap();
265        assert_eq!(ident1, ident2);
266    }
267
268    #[test]
269    fn test_canonicalize_idents_by_lowercasing_github_urls() {
270        let ident1 = ident(&url("https://github.com/PistonDevelopers/piston")).unwrap();
271        let ident2 = ident(&url("https://github.com/pistondevelopers/piston")).unwrap();
272        assert_eq!(ident1, ident2);
273    }
274
275    #[test]
276    fn test_canonicalize_idents_by_stripping_dot_git() {
277        let ident1 = ident(&url("https://github.com/PistonDevelopers/piston")).unwrap();
278        let ident2 = ident(&url("https://github.com/PistonDevelopers/piston.git")).unwrap();
279        assert_eq!(ident1, ident2);
280    }
281
282    #[test]
283    fn test_canonicalize_idents_different_protocols() {
284        let ident1 = ident(&url("https://github.com/PistonDevelopers/piston")).unwrap();
285        let ident2 = ident(&url("git://github.com/PistonDevelopers/piston")).unwrap();
286        assert_eq!(ident1, ident2);
287    }
288
289    #[test]
290    fn test_canonicalize_cannot_be_a_base_urls() {
291        assert!(ident(&url("github.com:PistonDevelopers/piston")).is_err());
292        assert!(ident(&url("google.com:PistonDevelopers/piston")).is_err());
293    }
294
295    fn url(s: &str) -> Url {
296        s.to_url().unwrap()
297    }
298}