cargo.rc 55.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

11 12 13 14 15 16 17 18 19

// cargo.rs - Rust package manager

// Local Variables:
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
E
Elly Jones 已提交
20 21

#[link(name = "cargo",
22
       vers = "0.6",
E
Elly Jones 已提交
23
       uuid = "9ff87a04-8fed-4295-9ff8-f99bb802650b",
24
       url = "https://github.com/mozilla/rust/tree/master/src/cargo")];
25

26
#[crate_type = "lib"];
27

28 29
#[no_core];

30 31
#[legacy_modes];

32 33
#[allow(vecs_implicitly_copyable,
        non_implicitly_copyable_typarams)];
34
#[allow(non_camel_case_types)];
35 36
#[allow(deprecated_mode)];
#[allow(deprecated_pattern)];
37
#[allow(deprecated_self)];
38

39 40 41 42
extern mod core(vers = "0.6");
extern mod std(vers = "0.6");
extern mod rustc(vers = "0.6");
extern mod syntax(vers = "0.6");
43

44
mod pgp;
B
Brian Anderson 已提交
45

46 47
use rustc::metadata::filesearch::{get_cargo_root, get_cargo_root_nearest};
use rustc::metadata::filesearch::{get_cargo_sysroot, libdir};
B
Brian Anderson 已提交
48

49 50 51 52 53
use core::*;

use core::dvec::DVec;
use core::io::WriterUtil;
use core::result::{Ok, Err};
D
Daniel Micay 已提交
54
use core::hashmap::linear::LinearMap;
55
use std::getopts::{optflag, optopt, opt_present};
56 57
use std::oldmap::HashMap;
use std::{oldmap, json, tempfile, term, sort, getopts};
58 59 60 61
use syntax::codemap::span;
use syntax::diagnostic::span_handler;
use syntax::diagnostic;
use syntax::{ast, codemap, parse, visit, attr};
B
Brian Anderson 已提交
62

63
pub struct Package {
B
Brian Anderson 已提交
64 65 66 67 68 69 70 71 72 73
    name: ~str,
    uuid: ~str,
    url: ~str,
    method: ~str,
    description: ~str,
    reference: Option<~str>,
    tags: ~[~str],
    versions: ~[(~str, ~str)]
}

74
pub impl Package : cmp::Ord {
B
Brian Anderson 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
    pure fn lt(&self, other: &Package) -> bool {
        if (*self).name.lt(&(*other).name) { return true; }
        if (*other).name.lt(&(*self).name) { return false; }
        if (*self).uuid.lt(&(*other).uuid) { return true; }
        if (*other).uuid.lt(&(*self).uuid) { return false; }
        if (*self).url.lt(&(*other).url) { return true; }
        if (*other).url.lt(&(*self).url) { return false; }
        if (*self).method.lt(&(*other).method) { return true; }
        if (*other).method.lt(&(*self).method) { return false; }
        if (*self).description.lt(&(*other).description) { return true; }
        if (*other).description.lt(&(*self).description) { return false; }
        if (*self).tags.lt(&(*other).tags) { return true; }
        if (*other).tags.lt(&(*self).tags) { return false; }
        if (*self).versions.lt(&(*other).versions) { return true; }
        return false;
    }
    pure fn le(&self, other: &Package) -> bool { !(*other).lt(&(*self)) }
    pure fn ge(&self, other: &Package) -> bool { !(*self).lt(other)     }
    pure fn gt(&self, other: &Package) -> bool { (*other).lt(&(*self))  }
}

96
pub struct Source {
B
Brian Anderson 已提交
97 98 99 100 101 102 103 104
    name: ~str,
    mut url: ~str,
    mut method: ~str,
    mut key: Option<~str>,
    mut keyfp: Option<~str>,
    packages: DVec<Package>
}

105
pub struct Cargo {
B
Brian Anderson 已提交
106 107 108 109 110 111 112
    pgp: bool,
    root: Path,
    installdir: Path,
    bindir: Path,
    libdir: Path,
    workdir: Path,
    sourcedir: Path,
113
    sources: oldmap::HashMap<~str, @Source>,
B
Brian Anderson 已提交
114
    mut current_install: ~str,
115
    dep_cache: oldmap::HashMap<~str, bool>,
B
Brian Anderson 已提交
116 117 118
    opts: Options
}

119
pub struct Crate {
B
Brian Anderson 已提交
120 121 122 123 124 125 126 127 128
    name: ~str,
    vers: ~str,
    uuid: ~str,
    desc: Option<~str>,
    sigs: Option<~str>,
    crate_type: Option<~str>,
    deps: ~[~str]
}

129
pub struct Options {
B
Brian Anderson 已提交
130 131 132 133 134 135
    test: bool,
    mode: Mode,
    free: ~[~str],
    help: bool,
}

136 137
#[deriving_eq]
pub enum Mode { SystemMode, UserMode, LocalMode }
B
Brian Anderson 已提交
138

139
pub fn opts() -> ~[getopts::Opt] {
B
Brian Anderson 已提交
140 141 142 143
    ~[optflag(~"g"), optflag(~"G"), optflag(~"test"),
     optflag(~"h"), optflag(~"help")]
}

144
pub fn info(msg: ~str) {
B
Brian Anderson 已提交
145 146 147 148 149 150 151 152 153 154
    let out = io::stdout();

    if term::color_supported() {
        term::fg(out, term::color_green);
        out.write_str(~"info: ");
        term::reset(out);
        out.write_line(msg);
    } else { out.write_line(~"info: " + msg); }
}

155
pub fn warn(msg: ~str) {
B
Brian Anderson 已提交
156 157 158 159 160 161 162 163 164 165
    let out = io::stdout();

    if term::color_supported() {
        term::fg(out, term::color_yellow);
        out.write_str(~"warning: ");
        term::reset(out);
        out.write_line(msg);
    }else { out.write_line(~"warning: " + msg); }
}

166
pub fn error(msg: ~str) {
B
Brian Anderson 已提交
167 168 169 170 171 172 173 174 175 176 177
    let out = io::stdout();

    if term::color_supported() {
        term::fg(out, term::color_red);
        out.write_str(~"error: ");
        term::reset(out);
        out.write_line(msg);
    }
    else { out.write_line(~"error: " + msg); }
}

178
pub fn is_uuid(id: ~str) -> bool {
B
Brian Anderson 已提交
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
    let parts = str::split_str(id, ~"-");
    if vec::len(parts) == 5u {
        let mut correct = 0u;
        for vec::eachi(parts) |i, part| {
            fn is_hex_digit(+ch: char) -> bool {
                ('0' <= ch && ch <= '9') ||
                ('a' <= ch && ch <= 'f') ||
                ('A' <= ch && ch <= 'F')
            }

            if !part.all(is_hex_digit) {
                return false;
            }

            match i {
                0u => {
                    if part.len() == 8u {
                        correct += 1u;
                    }
                }
                1u | 2u | 3u => {
                    if part.len() == 4u {
                        correct += 1u;
                    }
                }
                4u => {
                    if part.len() == 12u {
                        correct += 1u;
                    }
                }
                _ => { }
            }
        }
        if correct >= 5u {
            return true;
        }
    }
    return false;
}

#[test]
220
pub fn test_is_uuid() {
B
Brian Anderson 已提交
221 222 223 224 225 226 227 228 229 230 231 232
    assert is_uuid(~"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaafAF09");
    assert !is_uuid(~"aaaaaaaa-aaaa-aaaa-aaaaa-aaaaaaaaaaaa");
    assert !is_uuid(~"");
    assert !is_uuid(~"aaaaaaaa-aaa -aaaa-aaaa-aaaaaaaaaaaa");
    assert !is_uuid(~"aaaaaaaa-aaa!-aaaa-aaaa-aaaaaaaaaaaa");
    assert !is_uuid(~"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa-a");
    assert !is_uuid(~"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaป");
}

// FIXME (#2661): implement url/URL parsing so we don't have to resort
// to weak checks

233
pub fn has_archive_extension(p: ~str) -> bool {
B
Brian Anderson 已提交
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
    str::ends_with(p, ~".tar") ||
    str::ends_with(p, ~".tar.gz") ||
    str::ends_with(p, ~".tar.bz2") ||
    str::ends_with(p, ~".tar.Z") ||
    str::ends_with(p, ~".tar.lz") ||
    str::ends_with(p, ~".tar.xz") ||
    str::ends_with(p, ~".tgz") ||
    str::ends_with(p, ~".tbz") ||
    str::ends_with(p, ~".tbz2") ||
    str::ends_with(p, ~".tb2") ||
    str::ends_with(p, ~".taz") ||
    str::ends_with(p, ~".tlz") ||
    str::ends_with(p, ~".txz")
}

249
pub fn is_archive_path(u: ~str) -> bool {
B
Brian Anderson 已提交
250 251 252
    has_archive_extension(u) && os::path_exists(&Path(u))
}

253
pub fn is_archive_url(u: ~str) -> bool {
B
Brian Anderson 已提交
254 255 256 257 258 259 260 261 262
    // FIXME (#2661): this requires the protocol bit - if we had proper
    // url parsing, we wouldn't need it

    match str::find_str(u, ~"://") {
        option::Some(_) => has_archive_extension(u),
        _ => false
    }
}

263
pub fn is_git_url(url: ~str) -> bool {
B
Brian Anderson 已提交
264 265 266 267 268 269
    if str::ends_with(url, ~"/") { str::ends_with(url, ~".git/") }
    else {
        str::starts_with(url, ~"git://") || str::ends_with(url, ~".git")
    }
}

270
pub fn assume_source_method(url: ~str) -> ~str {
B
Brian Anderson 已提交
271 272 273 274 275 276 277 278 279 280
    if is_git_url(url) {
        return ~"git";
    }
    if str::starts_with(url, ~"file://") || os::path_exists(&Path(url)) {
        return ~"file";
    }

    ~"curl"
}

281 282 283
pub fn load_link(mis: ~[@ast::meta_item]) -> (Option<~str>,
                                              Option<~str>,
                                              Option<~str>) {
B
Brian Anderson 已提交
284 285 286 287 288
    let mut name = None;
    let mut vers = None;
    let mut uuid = None;
    for mis.each |a| {
        match a.node {
J
John Clements 已提交
289
            ast::meta_name_value(v, codemap::spanned { node: ast::lit_str(s),
290
                                                   _ }) => {
B
Brian Anderson 已提交
291 292 293 294 295 296 297
                match v {
                    ~"name" => name = Some(*s),
                    ~"vers" => vers = Some(*s),
                    ~"uuid" => uuid = Some(*s),
                    _ => { }
                }
            }
298
            _ => die!(~"load_link: meta items must be name-values")
B
Brian Anderson 已提交
299 300 301 302 303
        }
    }
    (name, vers, uuid)
}

304
pub fn load_crate(filename: &Path) -> Option<Crate> {
B
Brian Anderson 已提交
305 306 307 308 309 310 311 312 313 314 315 316
    let sess = parse::new_parse_sess(None);
    let c = parse::parse_crate_from_file(filename, ~[], sess);

    let mut name = None;
    let mut vers = None;
    let mut uuid = None;
    let mut desc = None;
    let mut sigs = None;
    let mut crate_type = None;

    for c.node.attrs.each |a| {
        match a.node.value.node {
J
John Clements 已提交
317
            ast::meta_name_value(v, codemap::spanned { node: ast::lit_str(_),
318
                                                   _ }) => {
B
Brian Anderson 已提交
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
                match v {
                    ~"desc" => desc = Some(v),
                    ~"sigs" => sigs = Some(v),
                    ~"crate_type" => crate_type = Some(v),
                    _ => { }
                }
            }
            ast::meta_list(v, mis) => {
                if v == ~"link" {
                    let (n, v, u) = load_link(mis);
                    name = n;
                    vers = v;
                    uuid = u;
                }
            }
            _ => {
335 336
                die!(~"crate attributes may not contain " +
                     ~"meta_words");
B
Brian Anderson 已提交
337 338 339 340
            }
        }
    }

T
Tim Chevalier 已提交
341
    struct Env {
B
Brian Anderson 已提交
342
        mut deps: ~[~str]
T
Tim Chevalier 已提交
343
    }
B
Brian Anderson 已提交
344

T
Tim Chevalier 已提交
345
    fn goto_view_item(ps: syntax::parse::parse_sess, e: @Env,
B
Brian Anderson 已提交
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
                      i: @ast::view_item) {
        match i.node {
            ast::view_item_use(ident, metas, _) => {
                let name_items =
                    attr::find_meta_items_by_name(metas, ~"name");
                let m = if name_items.is_empty() {
                    metas + ~[attr::mk_name_value_item_str(
                        ~"name", *ps.interner.get(ident))]
                } else {
                    metas
                };
                let mut attr_name = ident;
                let mut attr_vers = ~"";
                let mut attr_from = ~"";

              for m.each |item| {
                    match attr::get_meta_item_value_str(*item) {
                        Some(value) => {
                            let name = attr::get_meta_item_name(*item);

                            match name {
                                ~"vers" => attr_vers = value,
                                ~"from" => attr_from = value,
                                _ => ()
                            }
                        }
                        None => ()
                    }
                }

                let query = if !str::is_empty(attr_from) {
                    attr_from
                } else {
                    if !str::is_empty(attr_vers) {
                        ps.interner.get(attr_name) + ~"@" + attr_vers
                    } else { *ps.interner.get(attr_name) }
                };

                match *ps.interner.get(attr_name) {
                    ~"std" | ~"core" => (),
                    _ => e.deps.push(query)
                }
            }
            _ => ()
        }
    }
T
Tim Chevalier 已提交
392
    fn goto_item(_e: @Env, _i: @ast::item) {
B
Brian Anderson 已提交
393 394
    }

T
Tim Chevalier 已提交
395
    let e = @Env {
B
Brian Anderson 已提交
396 397
        mut deps: ~[]
    };
398
    let v = visit::mk_simple_visitor(@visit::SimpleVisitor {
B
Brian Anderson 已提交
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
        visit_view_item: |a| goto_view_item(sess, e, a),
        visit_item: |a| goto_item(e, a),
        .. *visit::default_simple_visitor()
    });

    visit::visit_crate(*c, (), v);

    let deps = copy e.deps;

    match (name, vers, uuid) {
        (Some(name0), Some(vers0), Some(uuid0)) => {
            Some(Crate {
                name: name0,
                vers: vers0,
                uuid: uuid0,
                desc: desc,
                sigs: sigs,
                crate_type: crate_type,
                deps: deps })
        }
        _ => return None
    }
}

423
pub fn print(s: ~str) {
B
Brian Anderson 已提交
424 425 426
    io::stdout().write_line(s);
}

427
pub fn rest(s: ~str, start: uint) -> ~str {
B
Brian Anderson 已提交
428 429 430 431 432 433 434
    if (start >= str::len(s)) {
        ~""
    } else {
        str::slice(s, start, str::len(s))
    }
}

435
pub fn need_dir(s: &Path) {
B
Brian Anderson 已提交
436 437
    if os::path_is_dir(s) { return; }
    if !os::make_dir(s, 493_i32 /* oct: 755 */) {
438
        die!(fmt!("can't make_dir %s", s.to_str()));
B
Brian Anderson 已提交
439 440 441
    }
}

442
pub fn valid_pkg_name(s: &str) -> bool {
B
Brian Anderson 已提交
443 444 445 446 447 448 449 450 451 452 453
    fn is_valid_digit(+c: char) -> bool {
        ('0' <= c && c <= '9') ||
        ('a' <= c && c <= 'z') ||
        ('A' <= c && c <= 'Z') ||
        c == '-' ||
        c == '_'
    }

    s.all(is_valid_digit)
}

454
pub fn parse_source(name: ~str, j: &json::Json) -> @Source {
B
Brian Anderson 已提交
455
    if !valid_pkg_name(name) {
456
        die!(fmt!("'%s' is an invalid source name", name));
B
Brian Anderson 已提交
457 458 459 460
    }

    match *j {
        json::Object(j) => {
461 462
            let mut url = match j.find(&~"url") {
                Some(&json::String(u)) => copy u,
463
                _ => die!(~"needed 'url' field in source")
B
Brian Anderson 已提交
464
            };
465 466
            let method = match j.find(&~"method") {
                Some(&json::String(u)) => copy u,
B
Brian Anderson 已提交
467 468
                _ => assume_source_method(url)
            };
469 470
            let key = match j.find(&~"key") {
                Some(&json::String(u)) => Some(copy u),
B
Brian Anderson 已提交
471 472
                _ => None
            };
473 474
            let keyfp = match j.find(&~"keyfp") {
                Some(&json::String(u)) => Some(copy u),
B
Brian Anderson 已提交
475 476 477 478 479 480 481 482 483 484 485 486 487
                _ => None
            };
            if method == ~"file" {
                url = os::make_absolute(&Path(url)).to_str();
            }
            return @Source {
                name: name,
                mut url: url,
                mut method: method,
                mut key: key,
                mut keyfp: keyfp,
                packages: DVec() };
        }
488
        _ => die!(~"needed dict value in source")
B
Brian Anderson 已提交
489 490 491
    };
}

492
pub fn try_parse_sources(filename: &Path,
493
                         sources: oldmap::HashMap<~str, @Source>) {
B
Brian Anderson 已提交
494 495 496 497 498 499 500 501 502
    if !os::path_exists(filename)  { return; }
    let c = io::read_whole_file_str(filename);
    match json::from_str(c.get()) {
        Ok(json::Object(j)) => {
            for j.each |k, v| {
                sources.insert(copy *k, parse_source(*k, v));
                debug!("source: %s", *k);
            }
        }
503 504
        Ok(_) => die!(~"malformed sources.json"),
        Err(e) => die!(fmt!("%s:%s", filename.to_str(), e.to_str()))
B
Brian Anderson 已提交
505 506 507
    }
}

508
pub fn load_one_source_package(src: @Source, p: &json::Object) {
509 510
    let name = match p.find(&~"name") {
        Some(&json::String(n)) => {
B
Brian Anderson 已提交
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
            if !valid_pkg_name(n) {
                warn(~"malformed source json: "
                     + src.name + ~", '" + n + ~"'"+
                     ~" is an invalid name (alphanumeric, underscores and" +
                     ~" dashes only)");
                return;
            }
            n
        }
        _ => {
            warn(~"malformed source json: " + src.name + ~" (missing name)");
            return;
        }
    };

526 527
    let uuid = match p.find(&~"uuid") {
        Some(&json::String(n)) => {
B
Brian Anderson 已提交
528 529 530 531 532 533
            if !is_uuid(n) {
                warn(~"malformed source json: "
                     + src.name + ~", '" + n + ~"'"+
                     ~" is an invalid uuid");
                return;
            }
534
            copy n
B
Brian Anderson 已提交
535 536 537 538 539 540 541
        }
        _ => {
            warn(~"malformed source json: " + src.name + ~" (missing uuid)");
            return;
        }
    };

542 543
    let url = match p.find(&~"url") {
        Some(&json::String(n)) => copy n,
B
Brian Anderson 已提交
544 545 546 547 548 549
        _ => {
            warn(~"malformed source json: " + src.name + ~" (missing url)");
            return;
        }
    };

550 551
    let method = match p.find(&~"method") {
        Some(&json::String(n)) => copy n,
B
Brian Anderson 已提交
552 553 554 555 556 557 558
        _ => {
            warn(~"malformed source json: "
                 + src.name + ~" (missing method)");
            return;
        }
    };

559 560
    let reference = match p.find(&~"ref") {
        Some(&json::String(n)) => Some(copy n),
B
Brian Anderson 已提交
561 562 563 564
        _ => None
    };

    let mut tags = ~[];
565 566
    match p.find(&~"tags") {
        Some(&json::List(js)) => {
B
Brian Anderson 已提交
567 568 569 570 571 572 573 574 575 576
          for js.each |j| {
                match *j {
                    json::String(ref j) => tags.grow(1u, j),
                    _ => ()
                }
            }
        }
        _ => ()
    }

577 578
    let description = match p.find(&~"description") {
        Some(&json::String(n)) => copy n,
B
Brian Anderson 已提交
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
        _ => {
            warn(~"malformed source json: " + src.name
                 + ~" (missing description)");
            return;
        }
    };

    let newpkg = Package {
        name: name,
        uuid: uuid,
        url: url,
        method: method,
        description: description,
        reference: reference,
        tags: tags,
        versions: ~[]
    };

    match src.packages.position(|pkg| pkg.uuid == uuid) {
        Some(idx) => {
            src.packages.set_elt(idx, newpkg);
            log(debug, ~"  updated package: " + src.name + ~"/" + name);
        }
        None => {
            src.packages.push(newpkg);
        }
    }

    log(debug, ~"  loaded package: " + src.name + ~"/" + name);
}

610
pub fn load_source_info(c: &Cargo, src: @Source) {
B
Brian Anderson 已提交
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
    let dir = c.sourcedir.push(src.name);
    let srcfile = dir.push("source.json");
    if !os::path_exists(&srcfile) { return; }
    let srcstr = io::read_whole_file_str(&srcfile);
    match json::from_str(srcstr.get()) {
        Ok(ref json @ json::Object(_)) => {
            let o = parse_source(src.name, json);

            src.key = o.key;
            src.keyfp = o.keyfp;
        }
        Ok(_) => {
            warn(~"malformed source.json: " + src.name +
                 ~"(source info is not a dict)");
        }
        Err(e) => {
            warn(fmt!("%s:%s", src.name, e.to_str()));
        }
    };
}
631
pub fn load_source_packages(c: &Cargo, src: @Source) {
B
Brian Anderson 已提交
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
    log(debug, ~"loading source: " + src.name);
    let dir = c.sourcedir.push(src.name);
    let pkgfile = dir.push("packages.json");
    if !os::path_exists(&pkgfile) { return; }
    let pkgstr = io::read_whole_file_str(&pkgfile);
    match json::from_str(pkgstr.get()) {
        Ok(json::List(js)) => {
          for js.each |j| {
                match *j {
                    json::Object(p) => {
                        load_one_source_package(src, p);
                    }
                    _ => {
                        warn(~"malformed source json: " + src.name +
                             ~" (non-dict pkg)");
                    }
                }
            }
        }
        Ok(_) => {
            warn(~"malformed packages.json: " + src.name +
                 ~"(packages is not a list)");
        }
        Err(e) => {
            warn(fmt!("%s:%s", src.name, e.to_str()));
        }
    };
}

661
pub fn build_cargo_options(argv: ~[~str]) -> Options {
662
    let matches = &match getopts::getopts(argv, opts()) {
B
Brian Anderson 已提交
663 664
        result::Ok(m) => m,
        result::Err(f) => {
665
            die!(fmt!("%s", getopts::fail_str(f)));
B
Brian Anderson 已提交
666 667 668 669 670 671 672 673 674 675 676 677
        }
    };

    let test = opt_present(matches, ~"test");
    let G    = opt_present(matches, ~"G");
    let g    = opt_present(matches, ~"g");
    let help = opt_present(matches, ~"h") || opt_present(matches, ~"help");
    let len  = vec::len(matches.free);

    let is_install = len > 1u && matches.free[1] == ~"install";
    let is_uninstall = len > 1u && matches.free[1] == ~"uninstall";

678
    if G && g { die!(~"-G and -g both provided"); }
B
Brian Anderson 已提交
679 680

    if !is_install && !is_uninstall && (g || G) {
681
        die!(~"-g and -G are only valid for `install` and `uninstall|rm`");
B
Brian Anderson 已提交
682 683 684 685 686 687 688 689 690 691
    }

    let mode =
        if (!is_install && !is_uninstall) || g { UserMode }
        else if G { SystemMode }
        else { LocalMode };

    Options {test: test, mode: mode, free: matches.free, help: help}
}

692
pub fn configure(opts: Options) -> Cargo {
B
Brian Anderson 已提交
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
    let home = match get_cargo_root() {
        Ok(home) => home,
        Err(_err) => get_cargo_sysroot().get()
    };

    let get_cargo_dir = match opts.mode {
        SystemMode => get_cargo_sysroot,
        UserMode => get_cargo_root,
        LocalMode => get_cargo_root_nearest
    };

    let p = get_cargo_dir().get();

    let sources = HashMap();
    try_parse_sources(&home.push("sources.json"), sources);
    try_parse_sources(&home.push("local-sources.json"), sources);

    let dep_cache = HashMap();

    let mut c = Cargo {
        pgp: pgp::supported(),
        root: home,
        installdir: p,
        bindir: p.push("bin"),
        libdir: p.push("lib"),
        workdir: p.push("work"),
        sourcedir: home.push("sources"),
        sources: sources,
        mut current_install: ~"",
        dep_cache: dep_cache,
        opts: opts
    };

    need_dir(&c.root);
    need_dir(&c.installdir);
    need_dir(&c.sourcedir);
    need_dir(&c.workdir);
    need_dir(&c.libdir);
    need_dir(&c.bindir);

733
    for sources.each_key_ref |&k| {
B
Brian Anderson 已提交
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
        let mut s = sources.get(k);
        load_source_packages(&c, s);
        sources.insert(k, s);
    }

    if c.pgp {
        pgp::init(&c.root);
    } else {
        warn(~"command `gpg` was not found");
        warn(~"you have to install gpg from source " +
             ~" or package manager to get it to work correctly");
    }

    move c
}

750
pub fn for_each_package(c: &Cargo, b: fn(s: @Source, p: &Package)) {
751
    for c.sources.each_value_ref |&v| {
B
Brian Anderson 已提交
752 753 754 755 756 757 758
        for v.packages.each |p| {
            b(v, p);
        }
    }
}

// Runs all programs in directory <buildpath>
759
pub fn run_programs(buildpath: &Path) {
B
Brian Anderson 已提交
760 761 762 763 764 765 766 767
    let newv = os::list_dir_path(buildpath);
    for newv.each |ct| {
        run::run_program(ct.to_str(), ~[]);
    }
}

// Runs rustc in <path + subdir> with the given flags
// and returns <patho + subdir>
768 769
pub fn run_in_buildpath(what: &str, path: &Path, subdir: &Path, cf: &Path,
                        extra_flags: ~[~str]) -> Option<Path> {
B
Brian Anderson 已提交
770 771 772 773 774 775 776 777 778 779 780 781 782 783
    let buildpath = path.push_rel(subdir);
    need_dir(&buildpath);
    debug!("%s: %s -> %s", what, cf.to_str(), buildpath.to_str());
    let p = run::program_output(rustc_sysroot(),
                                ~[~"--out-dir",
                                  buildpath.to_str(),
                                  cf.to_str()] + extra_flags);
    if p.status != 0 {
        error(fmt!("rustc failed: %d\n%s\n%s", p.status, p.err, p.out));
        return None;
    }
    Some(buildpath)
}

784
pub fn test_one_crate(_c: &Cargo, path: &Path, cf: &Path) {
B
Brian Anderson 已提交
785 786 787 788 789 790 791 792 793 794
    let buildpath = match run_in_buildpath(~"testing", path,
                                           &Path("test"),
                                           cf,
                                           ~[ ~"--test"]) {
      None => return,
    Some(bp) => bp
  };
  run_programs(&buildpath);
}

795
pub fn install_one_crate(c: &Cargo, path: &Path, cf: &Path) {
B
Brian Anderson 已提交
796 797 798 799 800 801 802
    let buildpath = match run_in_buildpath(~"installing", path,
                                           &Path("build"),
                                           cf, ~[]) {
      None => return,
      Some(bp) => bp
    };
    let newv = os::list_dir_path(&buildpath);
I
ILyoan 已提交
803
    let exec_suffix = str::from_slice(os::EXE_SUFFIX);
B
Brian Anderson 已提交
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
    for newv.each |ct| {
        if (exec_suffix != ~"" && str::ends_with(ct.to_str(),
                                                 exec_suffix)) ||
            (exec_suffix == ~"" &&
             !str::starts_with(ct.filename().get(),
                               ~"lib")) {
            debug!("  bin: %s", ct.to_str());
            install_to_dir(*ct, &c.bindir);
            if c.opts.mode == SystemMode {
                // FIXME (#2662): Put this file in PATH / symlink it so it can
                // be used as a generic executable
                // `cargo install -G rustray` and `rustray file.obj`
            }
        } else {
            debug!("  lib: %s", ct.to_str());
            install_to_dir(*ct, &c.libdir);
        }
    }
}


825
pub fn rustc_sysroot() -> ~str {
B
Brian Anderson 已提交
826 827 828 829 830 831 832 833 834 835
    match os::self_exe_path() {
        Some(path) => {
            let rustc = path.push_many([~"..", ~"bin", ~"rustc"]);
            debug!("  rustc: %s", rustc.to_str());
            rustc.to_str()
        }
        None => ~"rustc"
    }
}

D
Daniel Micay 已提交
836
pub fn install_source(c: &mut Cargo, path: &Path) {
B
Brian Anderson 已提交
837 838 839 840 841 842 843 844 845 846 847
    debug!("source: %s", path.to_str());
    os::change_dir(path);

    let mut cratefiles = ~[];
    for os::walk_dir(&Path(".")) |p| {
        if p.filetype() == Some(~".rc") {
            cratefiles.push(*p);
        }
    }

    if vec::is_empty(cratefiles) {
848
        die!(~"this doesn't look like a rust package (no .rc files)");
B
Brian Anderson 已提交
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
    }

    for cratefiles.each |cf| {
        match load_crate(cf) {
            None => loop,
            Some(crate) => {
              for crate.deps.each |query| {
                    // FIXME (#1356): handle cyclic dependencies
                    // (n.b. #1356 says "Cyclic dependency is an error
                    // condition")

                    let wd = get_temp_workdir(c);
                    install_query(c, &wd, *query);
                }

                os::change_dir(path);

                if c.opts.test {
                    test_one_crate(c, path, cf);
                }
                install_one_crate(c, path, cf);
            }
        }
    }
}

D
Daniel Micay 已提交
875 876
pub fn install_git(c: &mut Cargo, wd: &Path, url: ~str,
                   reference: Option<~str>) {
B
Brian Anderson 已提交
877 878 879 880 881 882 883 884 885 886
    run::program_output(~"git", ~[~"clone", url, wd.to_str()]);
    if reference.is_some() {
        let r = reference.get();
        os::change_dir(wd);
        run::run_program(~"git", ~[~"checkout", r]);
    }

    install_source(c, wd);
}

D
Daniel Micay 已提交
887
pub fn install_curl(c: &mut Cargo, wd: &Path, url: ~str) {
B
Brian Anderson 已提交
888 889 890 891
    let tarpath = wd.push("pkg.tar");
    let p = run::program_output(~"curl", ~[~"-f", ~"-s", ~"-o",
                                         tarpath.to_str(), url]);
    if p.status != 0 {
892
        die!(fmt!("fetch of %s failed: %s", url, p.err));
B
Brian Anderson 已提交
893 894 895 896 897 898 899
    }
    run::run_program(~"tar", ~[~"-x", ~"--strip-components=1",
                               ~"-C", wd.to_str(),
                               ~"-f", tarpath.to_str()]);
    install_source(c, wd);
}

D
Daniel Micay 已提交
900
pub fn install_file(c: &mut Cargo, wd: &Path, path: &Path) {
B
Brian Anderson 已提交
901 902 903 904 905 906
    run::program_output(~"tar", ~[~"-x", ~"--strip-components=1",
                                  ~"-C", wd.to_str(),
                                  ~"-f", path.to_str()]);
    install_source(c, wd);
}

D
Daniel Micay 已提交
907
pub fn install_package(c: &mut Cargo, src: ~str, wd: &Path, pkg: Package) {
B
Brian Anderson 已提交
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
    let url = copy pkg.url;
    let method = match pkg.method {
        ~"git" => ~"git",
        ~"file" => ~"file",
        _ => ~"curl"
    };

    info(fmt!("installing %s/%s via %s...", src, pkg.name, method));

    match method {
        ~"git" => install_git(c, wd, url, copy pkg.reference),
        ~"file" => install_file(c, wd, &Path(url)),
        ~"curl" => install_curl(c, wd, url),
        _ => ()
    }
}

925
pub fn cargo_suggestion(c: &Cargo, fallback: fn()) {
926
    if c.sources.is_empty() {
B
Brian Anderson 已提交
927 928 929 930 931 932 933
        error(~"no sources defined - you may wish to run " +
              ~"`cargo init`");
        return;
    }
    fallback();
}

D
Daniel Micay 已提交
934
pub fn install_uuid(c: &mut Cargo, wd: &Path, uuid: ~str) {
B
Brian Anderson 已提交
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
    let mut ps = ~[];
    for_each_package(c, |s, p| {
        if p.uuid == uuid {
            vec::push(&mut ps, (s.name, copy *p));
        }
    });
    if vec::len(ps) == 1u {
        let (sname, p) = copy ps[0];
        install_package(c, sname, wd, p);
        return;
    } else if vec::len(ps) == 0u {
        cargo_suggestion(c, || {
            error(~"can't find package: " + uuid);
        });
        return;
    }
    error(~"found multiple packages:");
    for ps.each |elt| {
        let (sname,p) = copy *elt;
        info(~"  " + sname + ~"/" + p.uuid + ~" (" + p.name + ~")");
    }
}

D
Daniel Micay 已提交
958
pub fn install_named(c: &mut Cargo, wd: &Path, name: ~str) {
B
Brian Anderson 已提交
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
    let mut ps = ~[];
    for_each_package(c, |s, p| {
        if p.name == name {
            vec::push(&mut ps, (s.name, copy *p));
        }
    });
    if vec::len(ps) == 1u {
        let (sname, p) = copy ps[0];
        install_package(c, sname, wd, p);
        return;
    } else if vec::len(ps) == 0u {
        cargo_suggestion(c, || {
            error(~"can't find package: " + name);
        });
        return;
    }
    error(~"found multiple packages:");
    for ps.each |elt| {
        let (sname,p) = copy *elt;
        info(~"  " + sname + ~"/" + p.uuid + ~" (" + p.name + ~")");
    }
}

D
Daniel Micay 已提交
982 983
pub fn install_uuid_specific(c: &mut Cargo, wd: &Path, src: ~str,
                             uuid: ~str) {
B
Brian Anderson 已提交
984 985 986 987 988 989 990 991 992 993 994 995 996 997
    match c.sources.find(src) {
        Some(s) => {
            for s.packages.each |p| {
                if p.uuid == uuid {
                    install_package(c, src, wd, *p);
                    return;
                }
            }
        }
        _ => ()
    }
    error(~"can't find package: " + src + ~"/" + uuid);
}

D
Daniel Micay 已提交
998 999
pub fn install_named_specific(c: &mut Cargo, wd: &Path, src: ~str,
                              name: ~str) {
B
Brian Anderson 已提交
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
    match c.sources.find(src) {
        Some(s) => {
            for s.packages.each |p| {
                if p.name == name {
                    install_package(c, src, wd, *p);
                    return;
                }
            }
        }
        _ => ()
    }
    error(~"can't find package: " + src + ~"/" + name);
}

1014
pub fn cmd_uninstall(c: &Cargo) {
B
Brian Anderson 已提交
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
    if vec::len(c.opts.free) < 3u {
        cmd_usage();
        return;
    }

    let lib = &c.libdir;
    let bin = &c.bindir;
    let target = c.opts.free[2u];

    // FIXME (#2662): needs stronger pattern matching
    // FIXME (#2662): needs to uninstall from a specified location in a
    // cache instead of looking for it (binaries can be uninstalled by
    // name only)

    fn try_uninstall(p: &Path) -> bool {
        if os::remove_file(p) {
            info(~"uninstalled: '" + p.to_str() + ~"'");
            true
        } else {
            error(~"could not uninstall: '" +
                  p.to_str() + ~"'");
            false
        }
    }

    if is_uuid(target) {
        for os::list_dir(lib).each |file| {
            match str::find_str(*file, ~"-" + target + ~"-") {
              Some(_) => if !try_uninstall(&lib.push(*file)) { return },
              None => ()
            }
        }
        error(~"can't find package with uuid: " + target);
    } else {
        for os::list_dir(lib).each |file| {
            match str::find_str(*file, ~"lib" + target + ~"-") {
              Some(_) => if !try_uninstall(&lib.push(*file)) { return },
              None => ()
            }
        }
        for os::list_dir(bin).each |file| {
            match str::find_str(*file, target) {
              Some(_) => if !try_uninstall(&lib.push(*file)) { return },
              None => ()
            }
        }

        error(~"can't find package with name: " + target);
    }
}

D
Daniel Micay 已提交
1066
pub fn install_query(c: &mut Cargo, wd: &Path, target: ~str) {
B
Brian Anderson 已提交
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
    match c.dep_cache.find(target) {
        Some(inst) => {
            if inst {
                return;
            }
        }
        None => ()
    }

    c.dep_cache.insert(target, true);

    if is_archive_path(target) {
        install_file(c, wd, &Path(target));
        return;
    } else if is_git_url(target) {
        let reference = if c.opts.free.len() >= 4u {
            Some(c.opts.free[3u])
        } else {
            None
        };
        install_git(c, wd, target, reference);
    } else if !valid_pkg_name(target) && has_archive_extension(target) {
        install_curl(c, wd, target);
        return;
    } else {
        let mut ps = copy target;

        match str::find_char(ps, '/') {
            option::Some(idx) => {
                let source = str::slice(ps, 0u, idx);
                ps = str::slice(ps, idx + 1u, str::len(ps));
                if is_uuid(ps) {
                    install_uuid_specific(c, wd, source, ps);
                } else {
                    install_named_specific(c, wd, source, ps);
                }
            }
            option::None => {
                if is_uuid(ps) {
                    install_uuid(c, wd, ps);
                } else {
                    install_named(c, wd, ps);
                }
            }
        }
    }

    // FIXME (#2662): This whole dep_cache and current_install thing is
    // a bit of a hack. It should be cleaned up in the future.

    if target == c.current_install {
D
Daniel Micay 已提交
1118
        c.dep_cache.clear();
B
Brian Anderson 已提交
1119 1120 1121 1122
        c.current_install = ~"";
    }
}

1123
pub fn get_temp_workdir(c: &Cargo) -> Path {
B
Brian Anderson 已提交
1124 1125
    match tempfile::mkdtemp(&c.workdir, "cargo") {
      Some(wd) => wd,
1126 1127
      None => die!(fmt!("needed temp dir: %s",
                        c.workdir.to_str()))
B
Brian Anderson 已提交
1128 1129 1130
    }
}

D
Daniel Micay 已提交
1131
pub fn cmd_install(c: &mut Cargo) {
1132 1133
    unsafe {
        let wd = get_temp_workdir(c);
B
Brian Anderson 已提交
1134

1135 1136 1137 1138
        if vec::len(c.opts.free) == 2u {
            let cwd = os::getcwd();
            let status = run::run_program(~"cp", ~[~"-R", cwd.to_str(),
                                                   wd.to_str()]);
B
Brian Anderson 已提交
1139

1140
            if status != 0 {
1141
                die!(fmt!("could not copy directory: %s", cwd.to_str()));
1142
            }
B
Brian Anderson 已提交
1143

1144 1145 1146
            install_source(c, &wd);
            return;
        }
B
Brian Anderson 已提交
1147

1148
        sync(c);
B
Brian Anderson 已提交
1149

1150 1151
        let query = c.opts.free[2];
        c.current_install = query.to_str();
B
Brian Anderson 已提交
1152

1153 1154
        install_query(c, &wd, query);
    }
B
Brian Anderson 已提交
1155 1156
}

1157
pub fn sync(c: &Cargo) {
1158
    for c.sources.each_key_ref |&k| {
B
Brian Anderson 已提交
1159 1160 1161 1162 1163 1164
        let mut s = c.sources.get(k);
        sync_one(c, s);
        c.sources.insert(k, s);
    }
}

1165
pub fn sync_one_file(c: &Cargo, dir: &Path, src: @Source) -> bool {
B
Brian Anderson 已提交
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
    let name = src.name;
    let srcfile = dir.push("source.json.new");
    let destsrcfile = dir.push("source.json");
    let pkgfile = dir.push("packages.json.new");
    let destpkgfile = dir.push("packages.json");
    let keyfile = dir.push("key.gpg");
    let srcsigfile = dir.push("source.json.sig");
    let sigfile = dir.push("packages.json.sig");
    let url = Path(src.url);
    let mut has_src_file = false;

    if !os::copy_file(&url.push("packages.json"), &pkgfile) {
        error(fmt!("fetch for source %s (url %s) failed",
                   name, url.to_str()));
        return false;
    }

    if os::copy_file(&url.push("source.json"), &srcfile) {
        has_src_file = false;
    }

    os::copy_file(&url.push("source.json.sig"), &srcsigfile);
    os::copy_file(&url.push("packages.json.sig"), &sigfile);

    match copy src.key {
        Some(u) => {
            let p = run::program_output(~"curl",
                                        ~[~"-f", ~"-s",
                                          ~"-o", keyfile.to_str(), u]);
            if p.status != 0 {
                error(fmt!("fetch for source %s (key %s) failed", name, u));
                return false;
            }
            pgp::add(&c.root, &keyfile);
        }
        _ => ()
    }
    match (src.key, src.keyfp) {
        (Some(_), Some(f)) => {
            let r = pgp::verify(&c.root, &pkgfile, &sigfile);

            if !r {
                error(fmt!("signature verification failed for source %s with \
                            key %s", name, f));
                return false;
            }

            if has_src_file {
                let e = pgp::verify(&c.root, &srcfile, &srcsigfile);

                if !e {
                    error(fmt!("signature verification failed for source %s \
                                with key %s", name, f));
                    return false;
                }
            }
        }
        _ => ()
    }

    copy_warn(&pkgfile, &destpkgfile);

    if has_src_file {
        copy_warn(&srcfile, &destsrcfile);
    }

    os::remove_file(&keyfile);
    os::remove_file(&srcfile);
    os::remove_file(&srcsigfile);
    os::remove_file(&pkgfile);
    os::remove_file(&sigfile);

    info(fmt!("synced source: %s", name));

    return true;
}

1243
pub fn sync_one_git(c: &Cargo, dir: &Path, src: @Source) -> bool {
B
Brian Anderson 已提交
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
    let name = src.name;
    let srcfile = dir.push("source.json");
    let pkgfile = dir.push("packages.json");
    let keyfile = dir.push("key.gpg");
    let srcsigfile = dir.push("source.json.sig");
    let sigfile = dir.push("packages.json.sig");
    let url = src.url;

    fn rollback(name: ~str, dir: &Path, insecure: bool) {
        fn msg(name: ~str, insecure: bool) {
            error(fmt!("could not rollback source: %s", name));

            if insecure {
                warn(~"a past security check failed on source " +
                     name + ~" and rolling back the source failed -"
                     + ~" this source may be compromised");
            }
        }

        if !os::change_dir(dir) {
            msg(name, insecure);
        }
        else {
            let p = run::program_output(~"git", ~[~"reset", ~"--hard",
                                                ~"HEAD@{1}"]);

            if p.status != 0 {
                msg(name, insecure);
            }
        }
    }

    if !os::path_exists(&dir.push(".git")) {
        let p = run::program_output(~"git", ~[~"clone", url, dir.to_str()]);

        if p.status != 0 {
            error(fmt!("fetch for source %s (url %s) failed", name, url));
            return false;
        }
    }
    else {
        if !os::change_dir(dir) {
            error(fmt!("fetch for source %s (url %s) failed", name, url));
            return false;
        }

        let p = run::program_output(~"git", ~[~"pull"]);

        if p.status != 0 {
            error(fmt!("fetch for source %s (url %s) failed", name, url));
            return false;
        }
    }

    let has_src_file = os::path_exists(&srcfile);

    match copy src.key {
        Some(u) => {
            let p = run::program_output(~"curl",
                                        ~[~"-f", ~"-s",
                                          ~"-o", keyfile.to_str(), u]);
            if p.status != 0 {
                error(fmt!("fetch for source %s (key %s) failed", name, u));
                rollback(name, dir, false);
                return false;
            }
            pgp::add(&c.root, &keyfile);
        }
        _ => ()
    }
    match (src.key, src.keyfp) {
        (Some(_), Some(f)) => {
            let r = pgp::verify(&c.root, &pkgfile, &sigfile);

            if !r {
                error(fmt!("signature verification failed for source %s with \
                            key %s", name, f));
                rollback(name, dir, false);
                return false;
            }

            if has_src_file {
                let e = pgp::verify(&c.root, &srcfile, &srcsigfile);

                if !e {
                    error(fmt!("signature verification failed for source %s \
                                with key %s", name, f));
                    rollback(name, dir, false);
                    return false;
                }
            }
        }
        _ => ()
    }

    os::remove_file(&keyfile);

    info(fmt!("synced source: %s", name));

    return true;
}

1346
pub fn sync_one_curl(c: &Cargo, dir: &Path, src: @Source) -> bool {
B
Brian Anderson 已提交
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
    let name = src.name;
    let srcfile = dir.push("source.json.new");
    let destsrcfile = dir.push("source.json");
    let pkgfile = dir.push("packages.json.new");
    let destpkgfile = dir.push("packages.json");
    let keyfile = dir.push("key.gpg");
    let srcsigfile = dir.push("source.json.sig");
    let sigfile = dir.push("packages.json.sig");
    let mut url = src.url;
    let smart = !str::ends_with(src.url, ~"packages.json");
    let mut has_src_file = false;

    if smart {
        url += ~"/packages.json";
    }

    let p = run::program_output(~"curl",
                                ~[~"-f", ~"-s",
                                  ~"-o", pkgfile.to_str(), url]);

    if p.status != 0 {
        error(fmt!("fetch for source %s (url %s) failed", name, url));
        return false;
    }
    if smart {
        url = src.url + ~"/source.json";
        let p =
            run::program_output(~"curl",
                                ~[~"-f", ~"-s",
                                  ~"-o", srcfile.to_str(), url]);

        if p.status == 0 {
            has_src_file = true;
        }
    }

    match copy src.key {
       Some(u) => {
            let p = run::program_output(~"curl",
                                        ~[~"-f", ~"-s",
                                          ~"-o", keyfile.to_str(), u]);
            if p.status != 0 {
                error(fmt!("fetch for source %s (key %s) failed", name, u));
                return false;
            }
            pgp::add(&c.root, &keyfile);
        }
        _ => ()
    }
    match (src.key, src.keyfp) {
        (Some(_), Some(f)) => {
            if smart {
                url = src.url + ~"/packages.json.sig";
            }
            else {
                url = src.url + ~".sig";
            }

            let mut p = run::program_output(~"curl",
                                            ~[~"-f", ~"-s", ~"-o",
                                              sigfile.to_str(), url]);
            if p.status != 0 {
                error(fmt!("fetch for source %s (sig %s) failed", name, url));
                return false;
            }

            let r = pgp::verify(&c.root, &pkgfile, &sigfile);

            if !r {
                error(fmt!("signature verification failed for source %s with \
                            key %s", name, f));
                return false;
            }

            if smart && has_src_file {
                url = src.url + ~"/source.json.sig";

                p = run::program_output(~"curl",
                                        ~[~"-f", ~"-s", ~"-o",
                                          srcsigfile.to_str(), url]);
                if p.status != 0 {
                    error(fmt!("fetch for source %s (sig %s) failed",
                          name, url));
                    return false;
                }

                let e = pgp::verify(&c.root, &srcfile, &srcsigfile);

                if !e {
                    error(~"signature verification failed for " +
                          ~"source " + name + ~" with key " + f);
                    return false;
                }
            }
        }
        _ => ()
    }

    copy_warn(&pkgfile, &destpkgfile);

    if smart && has_src_file {
        copy_warn(&srcfile, &destsrcfile);
    }

    os::remove_file(&keyfile);
    os::remove_file(&srcfile);
    os::remove_file(&srcsigfile);
    os::remove_file(&pkgfile);
    os::remove_file(&sigfile);

    info(fmt!("synced source: %s", name));

    return true;
}

1462
pub fn sync_one(c: &Cargo, src: @Source) {
B
Brian Anderson 已提交
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
    let name = src.name;
    let dir = c.sourcedir.push(name);

    info(fmt!("syncing source: %s...", name));

    need_dir(&dir);

    let result = match src.method {
        ~"git" => sync_one_git(c, &dir, src),
        ~"file" => sync_one_file(c, &dir, src),
        _ => sync_one_curl(c, &dir, src)
    };

    if result {
        load_source_info(c, src);
        load_source_packages(c, src);
    }
}

1482
pub fn cmd_init(c: &Cargo) {
B
Brian Anderson 已提交
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
    let srcurl = ~"http://www.rust-lang.org/cargo/sources.json";
    let sigurl = ~"http://www.rust-lang.org/cargo/sources.json.sig";

    let srcfile = c.root.push("sources.json.new");
    let sigfile = c.root.push("sources.json.sig");
    let destsrcfile = c.root.push("sources.json");

    let p =
        run::program_output(~"curl", ~[~"-f", ~"-s",
                                       ~"-o", srcfile.to_str(), srcurl]);
    if p.status != 0 {
        error(fmt!("fetch of sources.json failed: %s", p.out));
        return;
    }

    let p =
        run::program_output(~"curl", ~[~"-f", ~"-s",
                                       ~"-o", sigfile.to_str(), sigurl]);
    if p.status != 0 {
        error(fmt!("fetch of sources.json.sig failed: %s", p.out));
        return;
    }

    let r = pgp::verify(&c.root, &srcfile, &sigfile);
    if !r {
        error(fmt!("signature verification failed for '%s'",
                   srcfile.to_str()));
        return;
    }

    copy_warn(&srcfile, &destsrcfile);
    os::remove_file(&srcfile);
    os::remove_file(&sigfile);

    info(fmt!("initialized .cargo in %s", c.root.to_str()));
}

1520
pub fn print_pkg(s: @Source, p: &Package) {
B
Brian Anderson 已提交
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
    let mut m = s.name + ~"/" + p.name + ~" (" + p.uuid + ~")";
    if vec::len(p.tags) > 0u {
        m = m + ~" [" + str::connect(p.tags, ~", ") + ~"]";
    }
    info(m);
    if p.description != ~"" {
        print(~"   >> " + p.description + ~"\n")
    }
}

1531
pub fn print_source(s: @Source) {
B
Brian Anderson 已提交
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
    info(s.name + ~" (" + s.url + ~")");

    let pks = sort::merge_sort(s.packages.get(), sys::shape_lt);
    let l = vec::len(pks);

    print(io::with_str_writer(|writer| {
        let mut list = ~"   >> ";

        for vec::eachi(pks) |i, pk| {
            if str::len(list) > 78u {
                writer.write_line(list);
                list = ~"   >> ";
            }
            list += pk.name + (if l - 1u == i { ~"" } else { ~", " });
        }

        writer.write_line(list);
    }));
}

1552
pub fn cmd_list(c: &Cargo) {
B
Brian Anderson 已提交
1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
    sync(c);

    if vec::len(c.opts.free) >= 3u {
        let v = vec::view(c.opts.free, 2u, vec::len(c.opts.free));
        for vec::each(v) |name| {
            if !valid_pkg_name(*name) {
                error(fmt!("'%s' is an invalid source name", *name));
            } else {
                match c.sources.find(*name) {
                    Some(source) => {
                        print_source(source);
                    }
                    None => {
                        error(fmt!("no such source: %s", *name));
                    }
                }
            }
        }
    } else {
1572
        for c.sources.each_value_ref |&v| {
B
Brian Anderson 已提交
1573 1574 1575 1576 1577
            print_source(v);
        }
    }
}

1578
pub fn cmd_search(c: &Cargo) {
B
Brian Anderson 已提交
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
    if vec::len(c.opts.free) < 3u {
        cmd_usage();
        return;
    }

    sync(c);

    let mut n = 0;
    let name = c.opts.free[2];
    let tags = vec::slice(c.opts.free, 3u, vec::len(c.opts.free));
    for_each_package(c, |s, p| {
        if (str::contains(p.name, name) || name == ~"*") &&
            vec::all(tags, |t| vec::contains(p.tags, t) ) {
            print_pkg(s, p);
            n += 1;
        }
    });
    info(fmt!("found %d packages", n));
}

1599
pub fn install_to_dir(srcfile: &Path, destdir: &Path) {
B
Brian Anderson 已提交
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
    let newfile = destdir.push(srcfile.filename().get());

    let status = run::run_program(~"cp", ~[~"-r", srcfile.to_str(),
                                           newfile.to_str()]);
    if status == 0 {
        info(fmt!("installed: '%s'", newfile.to_str()));
    } else {
        error(fmt!("could not install: '%s'", newfile.to_str()));
    }
}

1611
pub fn dump_cache(c: &Cargo) {
B
Brian Anderson 已提交
1612 1613 1614
    need_dir(&c.root);

    let out = c.root.push("cache.json");
1615
    let _root = json::Object(~LinearMap::new());
B
Brian Anderson 已提交
1616 1617 1618 1619 1620

    if os::path_exists(&out) {
        copy_warn(&out, &c.root.push("cache.json.old"));
    }
}
1621 1622

pub fn dump_sources(c: &Cargo) {
1623
    if c.sources.is_empty() {
B
Brian Anderson 已提交
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
        return;
    }

    need_dir(&c.root);

    let out = c.root.push("sources.json");

    if os::path_exists(&out) {
        copy_warn(&out, &c.root.push("sources.json.old"));
    }

    match io::buffered_file_writer(&out) {
        result::Ok(writer) => {
1637
            let mut hash = ~LinearMap::new();
B
Brian Anderson 已提交
1638

D
Daniel Micay 已提交
1639
            for c.sources.each_ref |&k, &v| {
1640
                let mut chash = ~LinearMap::new();
B
Brian Anderson 已提交
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668

                chash.insert(~"url", json::String(v.url));
                chash.insert(~"method", json::String(v.method));

                match copy v.key {
                    Some(key) => {
                        chash.insert(~"key", json::String(copy key));
                    }
                    _ => ()
                }
                match copy v.keyfp {
                    Some(keyfp) => {
                        chash.insert(~"keyfp", json::String(copy keyfp));
                    }
                    _ => ()
                }

                hash.insert(copy k, json::Object(move chash));
            }

            json::to_writer(writer, &json::Object(move hash))
        }
        result::Err(e) => {
            error(fmt!("could not dump sources: %s", e));
        }
    }
}

1669
pub fn copy_warn(srcfile: &Path, destfile: &Path) {
B
Brian Anderson 已提交
1670 1671 1672 1673 1674 1675
    if !os::copy_file(srcfile, destfile) {
        warn(fmt!("copying %s to %s failed",
                  srcfile.to_str(), destfile.to_str()));
    }
}

1676
pub fn cmd_sources(c: &Cargo) {
B
Brian Anderson 已提交
1677
    if vec::len(c.opts.free) < 3u {
1678
        for c.sources.each_value_ref |&v| {
B
Brian Anderson 已提交
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
            info(fmt!("%s (%s) via %s",
                      v.name, v.url, v.method));
        }
        return;
    }

    let action = c.opts.free[2u];

    match action {
        ~"clear" => {
1689
          for c.sources.each_key_ref |&k| {
B
Brian Anderson 已提交
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
                c.sources.remove(k);
            }

            info(~"cleared sources");
        }
        ~"add" => {
            if vec::len(c.opts.free) < 5u {
                cmd_usage();
                return;
            }

            let name = c.opts.free[3u];
            let url = c.opts.free[4u];

            if !valid_pkg_name(name) {
                error(fmt!("'%s' is an invalid source name", name));
                return;
            }

1709
            if c.sources.contains_key_ref(&name) {
B
Brian Anderson 已提交
1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
                error(fmt!("source already exists: %s", name));
            } else {
                c.sources.insert(name, @Source {
                    name: name,
                    mut url: url,
                    mut method: assume_source_method(url),
                    mut key: None,
                    mut keyfp: None,
                    packages: DVec()
                });
                info(fmt!("added source: %s", name));
            }
        }
        ~"remove" => {
            if vec::len(c.opts.free) < 4u {
                cmd_usage();
                return;
            }

            let name = c.opts.free[3u];

            if !valid_pkg_name(name) {
                error(fmt!("'%s' is an invalid source name", name));
                return;
            }

1736
            if c.sources.contains_key_ref(&name) {
B
Brian Anderson 已提交
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
                c.sources.remove(name);
                info(fmt!("removed source: %s", name));
            } else {
                error(fmt!("no such source: %s", name));
            }
        }
        ~"set-url" => {
            if vec::len(c.opts.free) < 5u {
                cmd_usage();
                return;
            }

            let name = c.opts.free[3u];
            let url = c.opts.free[4u];

            if !valid_pkg_name(name) {
                error(fmt!("'%s' is an invalid source name", name));
                return;
            }

            match c.sources.find(name) {
                Some(source) => {
                    let old = copy source.url;
                    let method = assume_source_method(url);

                    source.url = url;
                    source.method = method;

                    c.sources.insert(name, source);

                    info(fmt!("changed source url: '%s' to '%s'", old, url));
                }
                None => {
                    error(fmt!("no such source: %s", name));
                }
            }
        }
        ~"set-method" => {
            if vec::len(c.opts.free) < 5u {
                cmd_usage();
                return;
            }

            let name = c.opts.free[3u];
            let method = c.opts.free[4u];

            if !valid_pkg_name(name) {
                error(fmt!("'%s' is an invalid source name", name));
                return;
            }

            match c.sources.find(name) {
                Some(source) => {
                    let old = copy source.method;

                    source.method = match method {
                        ~"git" => ~"git",
                        ~"file" => ~"file",
                        _ => ~"curl"
                    };

                    c.sources.insert(name, source);

                    info(fmt!("changed source method: '%s' to '%s'", old,
                         method));
                }
                None => {
                    error(fmt!("no such source: %s", name));
                }
            }
        }
        ~"rename" => {
            if vec::len(c.opts.free) < 5u {
                cmd_usage();
                return;
            }

            let name = c.opts.free[3u];
            let newn = c.opts.free[4u];

            if !valid_pkg_name(name) {
                error(fmt!("'%s' is an invalid source name", name));
                return;
            }
            if !valid_pkg_name(newn) {
                error(fmt!("'%s' is an invalid source name", newn));
                return;
            }

            match c.sources.find(name) {
                Some(source) => {
                    c.sources.remove(name);
                    c.sources.insert(newn, source);
                    info(fmt!("renamed source: %s to %s", name, newn));
                }
                None => {
                    error(fmt!("no such source: %s", name));
                }
            }
        }
        _ => cmd_usage()
    }
}

1841
pub fn cmd_usage() {
B
Brian Anderson 已提交
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855
    print(~"Usage: cargo <cmd> [options] [args..]
e.g. cargo install <name>

Where <cmd> is one of:
    init, install, list, search, sources,
    uninstall, usage

Options:

    -h, --help                  Display this message
    <cmd> -h, <cmd> --help      Display help for <cmd>
");
}

1856
pub fn cmd_usage_init() {
B
Brian Anderson 已提交
1857 1858 1859 1860 1861 1862
    print(~"cargo init

Re-initialize cargo in ~/.cargo. Clears all sources and then adds the
default sources from <www.rust-lang.org/sources.json>.");
}

1863
pub fn cmd_usage_install() {
B
Brian Anderson 已提交
1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881
    print(~"cargo install
cargo install [source/]<name>[@version]
cargo install [source/]<uuid>[@version]
cargo install <git url> [ref]
cargo install <tarball url>
cargo install <tarball file>

Options:
    --test      Run crate tests before installing
    -g          Install to the user level (~/.cargo/bin/ instead of
                locally in ./.cargo/bin/ by default)
    -G          Install to the system level (/usr/local/lib/cargo/bin/)

Install a crate. If no arguments are supplied, it installs from
the current working directory. If a source is provided, only install
from that source, otherwise it installs from any source.");
}

1882
pub fn cmd_usage_uninstall() {
B
Brian Anderson 已提交
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
    print(~"cargo uninstall [source/]<name>[@version]
cargo uninstall [source/]<uuid>[@version]
cargo uninstall <meta-name>[@version]
cargo uninstall <meta-uuid>[@version]

Options:
    -g          Remove from the user level (~/.cargo/bin/ instead of
                locally in ./.cargo/bin/ by default)
    -G          Remove from the system level (/usr/local/lib/cargo/bin/)

Remove a crate. If a source is provided, only remove
from that source, otherwise it removes from any source.
If a crate was installed directly (git, tarball, etc.), you can remove
it by metadata.");
}

1899
pub fn cmd_usage_list() {
B
Brian Anderson 已提交
1900 1901 1902 1903 1904 1905 1906
    print(~"cargo list [sources..]

If no arguments are provided, list all sources and their packages.
If source names are provided, list those sources and their packages.
");
}

1907
pub fn cmd_usage_search() {
B
Brian Anderson 已提交
1908 1909 1910 1911 1912
    print(~"cargo search <query | '*'> [tags..]

Search packages.");
}

1913
pub fn cmd_usage_sources() {
B
Brian Anderson 已提交
1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
    print(~"cargo sources
cargo sources add <name> <url>
cargo sources remove <name>
cargo sources rename <name> <new>
cargo sources set-url <name> <url>
cargo sources set-method <name> <method>

If no arguments are supplied, list all sources (but not their packages).

Commands:
    add             Add a source. The source method will be guessed
                    from the URL.
    remove          Remove a source.
    rename          Rename a source.
    set-url         Change the URL for a source.
    set-method      Change the method for a source.");
}

1932
pub fn main() {
B
Brian Anderson 已提交
1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
    let argv = os::args();
    let o = build_cargo_options(argv);

    if vec::len(o.free) < 2u {
        cmd_usage();
        return;
    }
    if o.help {
        match o.free[1] {
            ~"init" => cmd_usage_init(),
            ~"install" => cmd_usage_install(),
            ~"uninstall" => cmd_usage_uninstall(),
            ~"list" => cmd_usage_list(),
            ~"search" => cmd_usage_search(),
            ~"sources" => cmd_usage_sources(),
            _ => cmd_usage()
        }
        return;
    }
    if o.free[1] == ~"usage" {
        cmd_usage();
        return;
    }

    let mut c = configure(o);
    let home = c.root;
    let first_time = os::path_exists(&home.push("sources.json"));

    if !first_time && o.free[1] != ~"init" {
        cmd_init(&c);

        // FIXME (#2662): shouldn't need to reconfigure
        c = configure(o);
    }

    match o.free[1] {
1969
        ~"init" => cmd_init(&c),
D
Daniel Micay 已提交
1970
        ~"install" => cmd_install(&mut c),
1971 1972 1973 1974
        ~"uninstall" => cmd_uninstall(&c),
        ~"list" => cmd_list(&c),
        ~"search" => cmd_search(&c),
        ~"sources" => cmd_sources(&c),
B
Brian Anderson 已提交
1975 1976 1977
        _ => cmd_usage()
    }

1978 1979
    dump_cache(&c);
    dump_sources(&c);
B
Brian Anderson 已提交
1980
}
1981