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
#![allow(deprecated)] // supporting old versions

#[macro_use]
extern crate serde_derive;
extern crate semver;
extern crate serde;
extern crate serde_json;

use regfork::YankSpec;
use cargo::CargoConfig;
use semver::VersionReq;
use std::io;
use std::fs;
use std::env;
use std::process::Command;
use std::path::Path;

mod cargo;
mod cargo_repository_hash;

mod regfork;
use regfork::ForkedRegistryIndex;

/// See [the README for the CLI version](https://lib.rs/crates/lts).
pub fn cli_run() -> io::Result<()> {
    let cargo_config = CargoConfig::new();

    match parse_args() {
        Op::Exit => return Ok(()),
        Op::Fail => std::process::exit(1),
        Op::Setup => {
            setup_if_needed(&cargo_config)?;
        },
        Op::Prefetch => {
            fetch_registry(&cargo_config)?
        },
        Op::Update => {
            fetch_registry(&cargo_config)?;
            cargo_config.cargo_update_from_current_index()?;
        },
        Op::Reset => delete_local_fork(&cargo_config)?,
        Op::Yank(specs) => {
            if specs.is_empty() {
                eprintln!("Nothing to change");
                std::process::exit(1);
            }
            let fork = setup_if_needed(&cargo_config)?;
            fork.set_yanked_state(&specs, true)?
        }
    }

    Ok(())
}

enum Op {
    Reset,
    Prefetch,
    Setup,
    Update,
    Yank(Vec<YankSpec>),
    Exit,
    Fail,
}

fn parse_args() -> Op {
    let mut args = env::args().skip(1);
    let cmd = match args.by_ref().filter(|arg| arg != "lts").next() {
        Some(cmd) => cmd,
        None => {
            print_help();
            return Op::Fail;
        },
    };

    match cmd.as_str() {
        "setup" => Op::Setup,
        "prefetch" => Op::Prefetch,
        "update" => Op::Update,
        "yank" => {
            Op::Yank(parse_yankspecs(args, true))
        },
        "unyank" => {
            Op::Yank(parse_yankspecs(args, false))
        },
        "reset" | "unset" => {
            Op::Reset
        },
        "-h" | "--help" => {
            print_help();
            Op::Exit
        },
        "--version" | "-V" => {
            print_version();
            Op::Exit
        },
        wat => {
            eprintln!("Unknown arg: {}", wat);
            Op::Fail
        }
    }
}

fn print_version() {
    println!("lts {} https://lib.rs/lts", env!("CARGO_PKG_VERSION"));
}

fn print_help() {
    print_version();
println!(r#"Locally patch crates.io registry for a Cargo project

Remove any crate from the registry:
    cargo lts yank "SPEC"

SPEC is crate's name followed by a semver range without a space in between,
e.g. "pkg-config<=0.3.6", "semver>=0.11", or "openssl=0.0.1", or "file*".
SPEC must be in quotes. Run `cargo update` to apply changes.

Bring back yanked crate:
    cargo lts unyank "SPEC"

Pull new crate versions from the crates.io registry:
    cargo lts update

When using a patched registry `cargo update` doesn't fetch from crates.io.

Reset back to normal crates.io registry:
    cargo lts reset
"#
);
}

fn parse_yankspecs<I>(args: I, yank: bool) -> Vec<YankSpec> where I: Iterator<Item=String> {
    args.filter_map(|arg| {
        let pos = match arg.as_bytes().iter().position(|&c| !(c as char).is_alphanumeric() && c != b'_' && c != b'-') {
            Some(p) => p,
            None => {
                eprintln!("Spec '{arg}' doesn't contain semver version. It should be like '{arg}<=0.0.1'", arg = arg);
                return None;
            },
        };
        let (crate_name, range) = arg.split_at(pos);
        if crate_name.is_empty() {
            eprintln!("'{arg}' was interpreted as a semver range, but is missing crate name like 'cratename{arg}'", arg = arg);
            return None;
        }

        let range = match VersionReq::parse(range) {
            Ok(r) => r,
            Err(e) => {
                eprintln!("Semver range '{}' for '{}' doesn't parse: {}", range, crate_name, e);
                return None;
            }
        };
        Some(YankSpec {
            crate_name: crate_name.into(),
            range,
            yank,
        })
    }).collect()
}

fn setup_if_needed(cargo: &CargoConfig) -> io::Result<ForkedRegistryIndex> {
    let fork = ForkedRegistryIndex::new(cargo.default_forked_index_repository_path());
    fork.init()?;
    cargo.set_index_source_override(&fork.git_dir())?;
    Ok(fork)
}

fn io_err(s: &str) -> io::Result<()> {
    Err(io::Error::new(io::ErrorKind::Other, s))
}


fn force_update_crates_io_index() -> io::Result<()> {
    let _ = Command::new("cargo")
        .arg("install") // install always uses crates.io index, even if there's a local override
        .arg("libc") // safe trusted crate that can't actually be installed (that's good)
        .arg("--vers").arg("99.99.99-index-update-hack") // just to be sure
        .output()?; // don't print anything
    Ok(())
}

fn delete_local_fork(cargo: &CargoConfig) -> io::Result<()> {
    cargo.unset_index_source_override()?;
    let f = ForkedRegistryIndex::new(cargo.default_forked_index_repository_path());
    f.deinit()?;
    Ok(())
}

fn fetch_registry(cargo: &CargoConfig) -> io::Result<()> {
    let local_repo_copy_dir = cargo.default_forked_index_repository_path();
    if local_repo_copy_dir.exists() {
        let f = ForkedRegistryIndex::new(local_repo_copy_dir);
        f.update_cloned_repo_fork()?;
    } else {
        force_update_crates_io_index()?;
    }
    Ok(())
}

fn read(path: &Path) -> io::Result<Vec<u8>> {
    use io::Read;
    let mut f = fs::File::open(path)?;
    let mut out = Vec::new();
    f.read_to_end(&mut out)?;
    Ok(out)
}

fn write(path: &Path, data: &[u8]) -> io::Result<()> {
    use io::Write;
    let mut f = fs::File::create(path)?;
    f.write_all(data)
}