1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
#![warn(missing_docs)]
use anyhow::{anyhow, bail, Context, Error};
use flate2::read::GzDecoder;
use regex::Regex;
use reqwest::StatusCode;
use semver;
use serde_json::Value;
use std::env;
use std::path::PathBuf;
use std::process::Command;
use tar::Archive;
#[macro_use]
extern crate log;
static APP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));
pub const DEFAULT_BITBUCKET_URL: &'static str = "https://api.bitbucket.org/2.0/repositories";
pub const DEFAULT_GITHUB_URL: &'static str = "https://github.com";
pub const DEFAULT_GITLAB_URL: &'static str = "https://gitlab.com";
pub const DEFAULT_REGISTRY_URL: &'static str = "https://crates.io";
#[derive(Debug, Clone)]
pub enum CloneMethodKind {
Crate,
Git,
Mercurial,
Pijul,
Fossil,
Auto,
}
impl CloneMethodKind {
pub fn command(&self) -> &str {
match *self {
CloneMethodKind::Crate => "crate",
CloneMethodKind::Git => "git",
CloneMethodKind::Mercurial => "hg",
CloneMethodKind::Pijul => "pijul",
CloneMethodKind::Fossil => "fossil",
CloneMethodKind::Auto => "auto",
}
}
pub fn from(method_name: &str) -> Option<CloneMethodKind> {
match method_name {
"crate" => Some(CloneMethodKind::Crate),
"git" => Some(CloneMethodKind::Git),
"hg" => Some(CloneMethodKind::Mercurial),
"mercurial" => Some(CloneMethodKind::Mercurial),
"pijul" => Some(CloneMethodKind::Pijul),
"fossil" => Some(CloneMethodKind::Fossil),
"auto" => Some(CloneMethodKind::Auto),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub struct Cloner {
registry_url: String,
github_url: String,
gitlab_url: String,
bitbutcket_url: String,
out_dir: Option<PathBuf>,
}
fn check_semver_req(version: &str) -> Result<String, Error> {
let first = version
.chars()
.nth(0)
.ok_or_else(|| anyhow!("version is empty"))?;
let is_req = "<>=^~".contains(first) || version.contains('*');
if is_req {
Ok(version.parse::<semver::VersionReq>()?.to_string())
} else {
match semver::Version::parse(version) {
Ok(v) => Ok(format!("={}", v)),
Err(e) => Err(e).context(anyhow!(
"`{}` is not a valid semver version.\n\
Use an exact version like 1.2.3 or a version requirement expression.",
version
))?,
}
}
}
fn get_repo(pkg_info: &Value) -> Result<Option<String>, Error> {
let krate = pkg_info
.get("crate")
.ok_or_else(|| anyhow!("`crate` expected in pkg info"))?;
let repo = &krate["repository"];
if repo.is_string() {
return Ok(Some(repo.as_str().unwrap().to_string()));
}
let home = &krate["homepage"];
if home.is_string() {
return Ok(Some(home.as_str().unwrap().to_string()));
}
Ok(None)
}
fn reqwest_get(url: &str) -> reqwest::Result<reqwest::blocking::Response> {
let client = reqwest::blocking::Client::builder()
.user_agent(APP_USER_AGENT)
.build()?;
client.get(url).send()
}
impl Cloner {
pub fn new() -> Cloner {
Cloner {
registry_url: DEFAULT_REGISTRY_URL.to_string(),
github_url: DEFAULT_GITHUB_URL.to_string(),
gitlab_url: DEFAULT_GITLAB_URL.to_string(),
bitbutcket_url: DEFAULT_BITBUCKET_URL.to_string(),
out_dir: None,
}
}
pub fn set_registry_url(&mut self, value: impl Into<String>) -> &mut Self {
self.registry_url = value.into();
self
}
pub fn set_github_url(&mut self, value: impl Into<String>) -> &mut Self {
self.github_url = value.into();
self
}
pub fn set_gitlab_url(&mut self, value: impl Into<String>) -> &mut Self {
self.gitlab_url = value.into();
self
}
pub fn set_bitbucket_url(&mut self, value: impl Into<String>) -> &mut Self {
self.bitbutcket_url = value.into();
self
}
pub fn set_out_dir(&mut self, value: impl Into<PathBuf>) -> &mut Self {
self.out_dir = Some(value.into());
self
}
fn out_dir(&self) -> Result<PathBuf, Error> {
Ok(self
.out_dir
.as_ref()
.map_or_else(|| env::current_dir(), |v| Ok(v.to_path_buf()))?)
}
pub fn clone(
&self,
method_kind: CloneMethodKind,
spec: &str,
version: Option<&str>,
extra: &[&str],
) -> Result<(), Error> {
let mut parts = spec.splitn(2, &[':', '@']);
let name = parts.next().unwrap();
let spec_version_req = parts.next();
if spec_version_req.is_some() && version.is_some() {
bail!("Cannot specify both a :version and --version.");
}
let version_req = version
.or(spec_version_req)
.map(check_semver_req)
.transpose()?;
let pkg_info = self.get_pkg_info(name)?;
let repo = get_repo(&pkg_info)?;
let (method, repo) = match method_kind {
CloneMethodKind::Auto => {
if version_req.is_some() {
(CloneMethodKind::Crate, "".to_string())
} else if let Some(repo) = repo {
self.detect_repo(&repo)?
} else {
(CloneMethodKind::Crate, "".to_string())
}
}
CloneMethodKind::Crate => (method_kind, "".to_string()),
_ => {
if repo.is_none() {
bail!("Could not find repository path in crates.io.");
}
(method_kind, repo.unwrap())
}
};
match method {
CloneMethodKind::Crate => {
if !extra.is_empty() {
bail!("Got extra arguments, crate downloads take no extra arguments.");
}
self.clone_crate(name, version_req, &pkg_info)?;
}
CloneMethodKind::Git
| CloneMethodKind::Mercurial
| CloneMethodKind::Pijul
| CloneMethodKind::Fossil => {
if let Some(version_req) = version_req {
bail!(
"Specifying a version `{}` only works with the `crate` method.",
version_req
);
}
self.run_clone(method.command(), &repo, extra)?;
}
CloneMethodKind::Auto => unreachable!(),
}
Ok(())
}
fn detect_repo(&self, repo: &str) -> Result<(CloneMethodKind, String), Error> {
if repo.ends_with(".git") {
return Ok((CloneMethodKind::Git, repo.to_string()));
}
if let Some(c) = Regex::new(r"https?://(?:www\.)?github\.com/([^/]+)/([^/]+)")
.unwrap()
.captures(repo)
{
return Ok((
CloneMethodKind::Git,
format!(
"{}/{}/{}.git",
self.github_url,
c.get(1).unwrap().as_str(),
c.get(2).unwrap().as_str()
),
));
}
if let Some(c) = Regex::new(r"https?://(?:www\.)?gitlab\.com/([^/]+)/([^/]+)")
.unwrap()
.captures(repo)
{
return Ok((
CloneMethodKind::Git,
format!(
"{}/{}/{}.git",
self.gitlab_url,
c.get(1).unwrap().as_str(),
c.get(2).unwrap().as_str()
),
));
}
if let Some(c) = Regex::new(r"https?://(?:www\.)?bitbucket\.(?:org|com)/([^/]+)/([^/]+)")
.unwrap()
.captures(repo)
{
let user = c.get(1).unwrap().as_str();
let name = c.get(2).unwrap().as_str();
return self.bitbucket(user, name);
}
if repo.starts_with("https://nest.pijul.com/") {
return Ok((CloneMethodKind::Pijul, repo.to_string()));
}
bail!(
"Could not determine the VCS from repo `{}`, \
use the `--method` option to specify how to download.",
repo
);
}
fn bitbucket(&self, user: &str, name: &str) -> Result<(CloneMethodKind, String), Error> {
let api_url = &format!("{}/{}/{}", self.bitbutcket_url, user, name);
let repo_info =
reqwest_get(api_url).context("Failed to fetch repo info from bitbucket.")?;
let code = repo_info.status();
if !code.is_success() {
bail!(
"Failed to get repo info from bitbucket API `{}`: `{}`",
api_url,
code
);
}
let repo_info: Value = repo_info
.json()
.context("Failed to convert to bitbucket json.")?;
let method = repo_info["scm"]
.as_str()
.expect("Could not get `scm` from bitbucket.");
let method = match method {
"git" => CloneMethodKind::Git,
"hg" => CloneMethodKind::Mercurial,
_ => bail!("Unexpected bitbucket scm: `{}`", method),
};
let clones = repo_info["links"]["clone"]
.as_array()
.expect("Could not get `clone` from bitbucket.");
let href = clones
.iter()
.find(|c| {
c["name"]
.as_str()
.expect("Could not get clone `name` from bitbucket.")
== "https"
})
.expect("Could not find `https` clone in bitbucket.")["href"]
.as_str()
.expect("Could not get clone `href` from bitbucket.");
Ok((method, href.to_string()))
}
fn get_pkg_info(&self, name: &str) -> Result<Value, Error> {
let url = format!("{}/api/v1/crates/{}", self.registry_url, name);
debug!("GET {url}");
let pkg_info = reqwest_get(&url).context("Failed to fetch package info from crates.io.")?;
let code = pkg_info.status();
match code {
StatusCode::OK => {}
StatusCode::NOT_FOUND => bail!("Package `{}` not found on crates.io.", name),
_ => bail!("Failed to get package info from crates.io: `{}`", code),
}
let pkg_info: Value = pkg_info.json().context("Failed to convert to json.")?;
Ok(pkg_info)
}
fn clone_crate(
&self,
name: &str,
version_req: Option<String>,
pkg_info: &Value,
) -> Result<(), Error> {
let versions = pkg_info["versions"]
.as_array()
.expect("Could not find `versions` array on crates.io.");
let versions = versions.iter().map(|crate_version| {
let num = crate_version["num"]
.as_str()
.expect("Could not get `num` from version.");
let v = semver::Version::parse(num).expect("Could not parse crate `num`.");
(crate_version, v)
});
let mut versions: Vec<_> = if let Some(version_req) = version_req {
let req = semver::VersionReq::parse(&version_req)?;
versions
.filter(|(_crate_version, ver)| req.matches(ver))
.collect()
} else {
versions.collect()
};
if versions.is_empty() {
bail!("Could not find any matching versions.");
}
versions.sort_unstable_by_key(|x| x.1.clone());
let last = versions.last().unwrap().0;
let dl_path = last["dl_path"]
.as_str()
.expect("Could not find `dl_path` in crate version info.");
let dl_path = format!("{}{}", self.registry_url, dl_path);
let version = last["num"]
.as_str()
.expect("Could not find `num` in crate version info.");
info!("Downloading `{}`", dl_path);
let mut response =
reqwest_get(&dl_path).context(format!("Failed to download `{}`", dl_path))?;
let mut body = Vec::new();
response.copy_to(&mut body)?;
let gz = GzDecoder::new(body.as_slice());
let mut tar = Archive::new(gz);
let base = format!("{}-{}", name.to_lowercase(), version);
for entry in tar.entries()? {
let mut entry = entry.context("Failed to get tar entry.")?;
let entry_path = entry
.path()
.context("Failed to read entry path.")?
.into_owned();
info!("{}", entry_path.display());
if !entry_path.starts_with(&base) {
bail!(
"Expected path `{}` in tarball, got `{}`.",
base,
entry_path.display()
);
}
entry.unpack_in(&self.out_dir()?).context(format!(
"failed to unpack entry at `{}`",
entry_path.display()
))?;
}
Ok(())
}
fn run_clone(&self, method: &str, repo: &str, extra: &[&str]) -> Result<(), Error> {
info!("Running: {} clone {} {}", method, repo, extra.join(" "));
let status = Command::new(method)
.arg("clone")
.arg(repo)
.args(extra)
.current_dir(&self.out_dir()?)
.status()
.context(format!("Failed to run `{}`.", method))?;
if !status.success() {
bail!("`{} clone` did not finish successfully.", method);
}
Ok(())
}
}
pub fn clone(
method_name: &str,
spec: &str,
version: Option<&str>,
extra: &[&str],
) -> Result<(), Error> {
Cloner::new().clone(
CloneMethodKind::from(method_name).unwrap(),
spec,
version,
extra,
)
}