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
use anyhow::Result;
use url::Url;
use std::path::PathBuf;
use clap::{arg, Parser};
use serde::Deserialize;
use crate::git::Git;

const REPO_DIR: &str = "mined";

struct LocalGit {
    /// If path is set, then a local copy exists, otherwise not
    path: PathBuf,

    /// Info about the repo
    info: RepoInfo,
}

// By default, struct field names are deserialized based on the position of
// a corresponding field in the CSV data's header record.
#[allow(dead_code)]
#[derive(Debug, Deserialize)]
struct RepoInfo {
    created_at: String,
    description: String,
    documentation: String,
    downloads: u64,
    homepage: String,
    id: u64,
    max_upload_size: Option<u64>,
    name: String,
    readme: String,
    repository: String,
    updated_at: String,
}

type CratesInfo = Vec<RepoInfo>;

pub struct CratesIO {
    repos: Vec<LocalGit>,
}

impl CratesIO {
    pub fn apply<F>(&self, f: F) -> Result<()>
        where F: Fn(&PathBuf) -> Result<()> {
        for repo in &self.repos {
            f(&repo.path)?;
        }
        Ok(())
    }

    fn from_csv(csv: String, subset_repos: Option<Vec<String>>) -> Result<CratesInfo> {
        let mut crates = Self::read_cratesio_csv(csv)?;
        // sort in descending order
        crates.sort_by(|a,b| b.downloads.cmp(&a.downloads));
        // filter to subset asked
        if let Some(allowed) = subset_repos {
            let crates = crates
                .into_iter()
                .filter(|c| allowed.contains(&c.name))
                .collect();
            return Ok(crates)
        }
        Ok(crates)
    }

    fn mk_local(crates: CratesInfo, ssh_username: &str, dir: Option<String>) -> Result<Self> {
        let mut git = Git::init(ssh_username);
        let dir = dir.unwrap_or(REPO_DIR.to_string());
        let git_exists = |info: &RepoInfo| -> bool {
            reqwest::blocking::get(&info.repository)
                .map(|g| g.status().is_success()) // did we successfully get data
                .unwrap_or(false) // if get building failed return false
        };
        let mut repos = vec![];
        for info in crates.into_iter() {
            // stale repos do exist in crates.io, where github links are invalid
            if !git_exists(&info) {
                println!("Ignoring stale repo [{}] for [{}]", &info.repository, &info.name);
                continue;
            }
            // clone crate
            let clone = Self::download(&info, &mut git, dir.as_str());
            if let Ok(path) = clone {
                repos.push(LocalGit { path, info });
            } else {
                println!("!! Git clone failed [{}]", &info.repository);
            }
        }
        Ok(CratesIO { repos })
    }

    /// check that the path that exists contains a valid repo
    fn already_local_git(path: &PathBuf) -> bool {
        path.exists() && Git::is_repo(path)
    }

    fn download(info: &RepoInfo, git: &mut Git, dir: &str) -> Result<PathBuf> {
        let mut location = PathBuf::new();
        location.push(dir);
        location.push(info.name.clone());

        if Self::already_local_git(&location) {
            println!("Already local: [{}] at [{:?}]", info.repository, location);
            return Ok(location);
        }
        println!("Cloning: [{}] to [{:?}]", info.repository, location);

        // clone repo
        let url = Url::parse(&info.repository)?;
        git.clone(&url, &location)?;
        assert!(Self::already_local_git(&location));

        Ok(location)
    }

    fn read_cratesio_csv(path: String) -> Result<CratesInfo> {
        // created_at,description,documentation,downloads,homepage,id,max_upload_size,name,readme,repository,updated_at
        // pick subset we care about:
        let all_fields = vec![
            "created_at",
            "description",
            "documentation",
            "downloads",
            "homepage",
            "id",
            "max_upload_size",
            "name",
            "readme",
            "repository",
            "updated_at",
        ];

        let mut records = vec![];
        let mut rdr = csv::Reader::from_path(path)?;
        let headers = rdr.headers()?.clone();
        let fields = csv::StringRecord::from(all_fields);
        assert!(fields == headers);
        for r in rdr.records() {
            let row: RepoInfo = r?.deserialize(Some(&fields))?;
            records.push(row)
        }
        Ok(records)
    }
}

#[derive(Debug, Parser)]
#[command(author, version, about)]
pub struct Args {
    /// Location of crates.io csv, from urls:
    /// https://crates.io/data-access
    /// https://static.crates.io/db-dump.tar.gz
    #[arg(short, long)]
    csv: String,

    /// Names of crates to process.
    /// If none then all crates will be processed
    #[arg(short, long)]
    names: Option<Vec<String>>,

    /// SSH username
    #[arg(short, long)]
    username: String,

    /// Output directory.
    /// If not specified then default "mined" used
    #[arg(short, long)]
    dir: Option<String>,
}

impl CratesIO {
    pub fn cli_mk() -> Result<Self> {
        let args = Args::parse();
        let crates = Self::from_csv(args.csv, args.names)?;
        Self::mk_local(crates, &args.username, args.dir)
    }
}