cargo-cvm 0.5.1

Rust Crate Version Manager (CVM)
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
485
486
487
488
489
490
491
492
493
494
495
496
use anyhow::Error;
use cargo_toml::Manifest;
use clap::ArgMatches;
use git2::{BranchType, Repository, Tree};
use std::cmp::Ordering;
use std::convert::TryInto;
use std::fs::read_to_string;
use std::fs::{remove_file, File};
use std::io::Write;
use std::path::PathBuf;
use std::process::Command;

#[derive(Debug, Clone, Eq)]
pub struct Version {
    major: u8,
    minor: u8,
    patch: u8,
}

impl Ord for Version {
    fn cmp(&self, other: &Self) -> Ordering {
        let major_ord = self.major.cmp(&other.major);
        let minor_ord = self.minor.cmp(&other.minor);
        let patch_ord = self.patch.cmp(&other.patch);

        match major_ord {
            Ordering::Equal => match minor_ord {
                Ordering::Equal => patch_ord,
                _ => minor_ord,
            },
            _ => major_ord,
        }
    }
}

impl PartialOrd for Version {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for Version {
    fn eq(&self, other: &Self) -> bool {
        self.major == other.major && self.minor == other.minor && self.patch == other.patch
    }
}

impl Version {
    pub fn bump(&mut self, semver: SemVer) {
        match semver {
            SemVer::Major => {
                self.major += 1;
                self.minor = 0;
                self.patch = 0;
            }
            SemVer::Minor => {
                self.minor += 1;
                self.patch = 0;
            }
            SemVer::Patch => self.patch += 1,
        };
    }

    pub fn default() -> Self {
        Self {
            major: 0,
            minor: 1,
            patch: 0,
        }
    }
}
#[derive(Debug, Clone)]
pub enum SemVer {
    Minor,
    Major,
    Patch,
}

impl TryInto<Version> for Manifest {
    type Error = Error;
    fn try_into(self) -> Result<Version, Self::Error> {
        if let Some(pkg) = self.package {
            Ok(pkg.version.try_into()?)
        } else {
            Err(Error::msg("Invalid cargo manifest"))
        }
    }
}

impl TryInto<SemVer> for &str {
    type Error = Error;
    fn try_into(self) -> Result<SemVer, Error> {
        let semver = match self {
            "minor" => SemVer::Minor,
            "major" => SemVer::Major,
            "patch" => SemVer::Patch,
            _ => return Err(Error::msg(format!("Invalid option: {:?}", self))),
        };

        Ok(semver)
    }
}

impl TryInto<SemVer> for String {
    type Error = Error;
    fn try_into(self) -> Result<SemVer, Error> {
        let semver = match self.as_ref() {
            "minor" => SemVer::Minor,
            "major" => SemVer::Major,
            "patch" => SemVer::Patch,
            _ => return Err(Error::msg(format!("Invalid option: {:?}", self))),
        };

        Ok(semver)
    }
}

impl std::fmt::Display for Version {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
    }
}

impl TryInto<Version> for String {
    type Error = Error;
    fn try_into(self) -> Result<Version, Self::Error> {
        let version = self
            .split('.')
            .map(|v| v.parse())
            .collect::<Result<Vec<u8>, std::num::ParseIntError>>()?;

        if version.len() < 3 {
            return Err(Error::msg(format!("Invalid version number: {:?}", version)));
        }

        Ok(Version {
            major: version[0],
            minor: version[1],
            patch: version[2],
        })
    }
}

pub struct Manager {
    semver: SemVer,
    target_remote: String,
    target_branch: String,
    current_branch: String,
    workspaces: Vec<String>,
    check: bool,
    fix: bool,
    warn: bool,
    force: bool,
    commit: bool,
    repo: Repository,
    ssh_key_path: String
}

impl Manager {
    pub fn new(args: &ArgMatches) -> Result<Self, Error> {
        let dir = std::env::current_dir()?;
        let repo = Repository::discover(dir.clone())?;
        let ssh_key_path = format!("{}/.ssh/id_rsa", std::env::var("HOME")?);

        Ok(Self {
            semver: args.value_of("semver").unwrap_or("minor").try_into()?,
            check: args.is_present("check"),
            fix: args.is_present("fix"),
            warn: args.is_present("warn"),
            force: args.is_present("force"),
            commit: args.is_present("commit"),
            target_branch: args.value_of("branch").unwrap_or("master").to_string(),
            target_remote: args.value_of("remote").unwrap_or("origin").to_string(),
            current_branch: Self::get_current_branch(&repo)?,
            workspaces: Self::get_cargo_workspaces(dir)?,
            ssh_key_path: args.value_of("ssh-key").unwrap_or(&ssh_key_path).to_string(),
            repo,
        })
    }

    pub fn get_current_branch(repo: &Repository) -> Result<String, Error> {
        if let Some(name) = repo.head()?.name() {
            Ok(name.replace("refs/heads", ""))
        } else {
            panic!("Failed to find current branch")
        }
    }

    pub fn get_cargo_workspaces(dir: PathBuf) -> Result<Vec<String>, Error> {
        let mut cargo_toml = dir;
        cargo_toml.push("Cargo.toml");

        if !cargo_toml.exists() {
            panic!("`cargo cvm` must be run in a directory containing a `Cargo.toml` file.\nFile does not exist at: {:?}", cargo_toml.display())
        }

        let config: Manifest = toml::from_str(&read_to_string(&cargo_toml)?)?;
        let mut paths: Vec<String> = Vec::new();

        if config.package.is_some() {
            let dir = std::env::current_dir()?;
            if let Some(path) = dir.to_str() {
                paths.push(String::from(path));
            }
        }

        if let Some(workspace) = config.workspace {
            paths.extend(workspace.members.into_iter())
        }

        Ok(paths)
    }

    pub fn bump_version(&self, workspace: PathBuf) -> Result<(), Error> {
        let mut cargo_toml = workspace.clone();
        cargo_toml.push("Cargo.toml");

        let config = read_to_string(&cargo_toml)?;
        if let Some(pkg) = toml::from_str::<Manifest>(&config)?.package {
            let old_version: Version = pkg.version.try_into()?;
            let mut new_version = old_version.clone();
            new_version.bump(self.semver.clone());

            // Replace only the first instance of the old_version to the new_version;
            // this will not replace dependency versions;
            let updated_config =
                config.replacen(&old_version.to_string(), &new_version.to_string(), 1);

            // Remove the old version of the file;
            remove_file(&cargo_toml)?;

            // Update the new version;
            let mut file = File::create(&cargo_toml)?;
            file.write_all(updated_config.as_bytes())?;

            // Commit the changes;
            Self::git_add_version_update(cargo_toml, new_version.to_string())?;

            Ok(())
        } else {
            panic!("invalid cargo file");
        }
    }

    pub fn git_add_version_update(cargo_toml: PathBuf, version: String) -> Result<(), Error> {
        Command::new("git")
            .args(&["add", &cargo_toml.display().to_string()])
            .output()
            .expect("Failed to add updated config");

        println!("version {} update added to git.", version);
        Ok(())
    }

    pub fn fetch_target(&self) -> Result<(), Error> {
        let mut callbacks = git2::RemoteCallbacks::new();
        callbacks.credentials(|_url, username_from_url, _allowed_types| {
          git2::Cred::ssh_key(
            username_from_url.unwrap_or_default(),
            None,
            std::path::Path::new(&self.ssh_key_path),
            None,
          )
        });

        let mut fetch_options = git2::FetchOptions::new();
        fetch_options.remote_callbacks(callbacks);

        match self.repo.find_remote(&self.target_remote) {
            Ok(mut remote) => {
                remote.fetch(&[&self.target_branch], Some(&mut fetch_options), None)?;
                Ok(())
            },
            Err(e) => {
                eprint!("Failed to find target remote host: {:?}; Error: {:?}", &self.target_remote, e);
                let remotes = self.repo.remotes()?;
                let remotes = &remotes.iter().map(|remote| remote.unwrap_or("")).collect::<Vec<&str>>();
                println!("\nAvailable Remotes: {:?}", remotes);
                panic!("Remote does not exist; try again with an available remote.");
            }
        }
    }

    pub fn check_workspaces(&self) -> Result<(), Error> {
        self.fetch_target()?;

        let mut failed = false;

        // For each of the workspace directories, check if any files in the src directory have changed;
        for workspace in self.workspaces.iter() {
            if let Some((version, cargo_toml)) =
                self.is_version_outdated(PathBuf::from(workspace))?
            {
                let msg = format!(
                    "version {} is not updated for changes in workspace Cargo.toml file: {:?}",
                    version, cargo_toml
                );

                if self.check {
                    eprintln!("{}", msg.clone());
                    // set failed to true;
                    failed = true;
                } else if self.fix {
                    self.bump_version(PathBuf::from(workspace))?;
                } else if self.warn {
                    eprintln!("{}", &msg);
                } else {
                    println!("{}", &msg);
                }
            } else if self.force {
                // force an update even if the workspace version is already updated;
                self.bump_version(PathBuf::from(workspace))?;
            }
        }

        if failed {
            panic!("One or more workspace versions are out of date");
        }

        if (self.commit && self.fix) || (self.commit && self.force) {
            let commit_msg = format!("updated crate version(s)");
            Command::new("git")
                .args(&["commit", "-m", &commit_msg])
                .output()
                .expect("Failed to add updated crate versions");
        }

        Ok(())
    }

    /// Returns (target, current) trees based on target and current branch;
    pub fn get_comparison_trees(&self) -> Result<(Tree, Tree), Error> {
        let target_branch_tree = self
            .repo
            .find_branch(&self.target_branch, BranchType::Local)?
            .into_reference()
            .peel_to_tree()?;
        let current_branch_tree = self
            .repo
            .find_branch(&self.current_branch, BranchType::Local)?
            .into_reference()
            .peel_to_tree()?;
        Ok((target_branch_tree, current_branch_tree))
    }

    pub fn get_version_comparison(
        &self,
        old_oid: git2::Oid,
        new_oid: git2::Oid,
    ) -> Result<(Version, Version), Error> {
        let old_manifest: Manifest = toml::from_slice(self.repo.find_blob(old_oid)?.content())?;
        let new_manifest: Manifest = toml::from_slice(self.repo.find_blob(new_oid)?.content())?;

        let old_version: Version = old_manifest.try_into()?;
        let new_version: Version = new_manifest.try_into()?;

        Ok((old_version, new_version))
    }

    pub fn get_workspace_version(workspace: PathBuf) -> Result<Version, Error> {
        let mut cargo_toml = workspace;
        cargo_toml.push("Cargo.toml");
        let config: Manifest = toml::from_str(&read_to_string(&cargo_toml)?)?;
        Ok(config.try_into()?)
    }

    pub fn is_version_outdated(
        &self,
        workspace: PathBuf,
    ) -> Result<Option<(Version, PathBuf)>, Error> {
        let mut src_dir = workspace.clone();
        let mut cargo_toml = workspace.clone();

        // Only check the src directory;
        src_dir.push("src");
        cargo_toml.push("Cargo.toml");

        if !src_dir.exists() || !src_dir.is_dir() || !cargo_toml.exists() || !cargo_toml.is_file() {
            panic!("src directory does not exist at {:?}", src_dir.display())
        }

        let (target_tree, current_tree) = self.get_comparison_trees()?;

        let diff = self
            .repo
            .diff_tree_to_tree(Some(&target_tree), Some(&current_tree), None)?;

        let mut no_changes = true;
        let mut src_files_changed = false;
        let mut version_is_updated = false;
        let mut outdated_version: Version = Self::get_workspace_version(workspace)?;

        diff.foreach(
            &mut |delta, _value| {
                no_changes = false;
                let old_file = delta.old_file();
                let new_file = delta.new_file();

                if let Some(path) = new_file.path() {
                    if let Some(uri) = PathBuf::from(path).to_str() {
                        if let Some(repo_path) = self.repo.path().to_str() {
                            let mut path = PathBuf::from(repo_path.replace("/.git", ""));
                            path.push(uri);
                            if let Some(dir) = src_dir.to_str() {
                                if let Some(file) = path.to_str() {
                                    if file.contains(dir) {
                                        src_files_changed = true;
                                    }
                                }
                            }

                            if cargo_toml == path {
                                if let Ok((old_version, new_version)) =
                                    self.get_version_comparison(old_file.id(), new_file.id())
                                {
                                    version_is_updated = new_version > old_version;

                                    if !version_is_updated {
                                        outdated_version = new_version;
                                    } else {
                                        outdated_version = old_version;
                                    }
                                }
                            }
                        }
                    }
                }

                true
            },
            None,
            None,
            None,
        )?;

        if src_files_changed && version_is_updated || no_changes {
            Ok(None)
        } else {
            Ok(Some((outdated_version, cargo_toml)))
        }
    }
}

#[cfg(test)]
mod tests {
    use std::convert::TryInto;

    fn dummy_manager() -> Result<super::Manager, Box<dyn std::error::Error>> {
        let dir = std::env::current_dir()?;

        println!("Current directory: {:?}", dir);

        let repo = git2::Repository::discover(dir.clone())?;
        let ssh_key_path = format!("{}/.ssh/id_rsa", std::env::var("HOME")?);

        Ok(super::Manager {
            semver: String::from("minor").try_into()?,
            check: false,
            fix: false,
            warn: true,
            force: false,
            commit: false,
            target_remote: String::from("origin"),
            target_branch: String::from("master"),
            current_branch: super::Manager::get_current_branch(&repo)?,
            workspaces: super::Manager::get_cargo_workspaces(dir)?,
            ssh_key_path,
            repo,
        })
    }

    #[test]
    fn test_current_branch() -> Result<(), Box<dyn std::error::Error>> {
        let dir = std::env::current_dir()?;

        let repo = git2::Repository::discover(dir)?;
        let branch = super::Manager::get_current_branch(&repo)?;
        println!("branch: {:?}", branch.replace("refs/heads/", ""));
        assert_eq!(branch.is_empty(), false);

        Ok(())
    }

    #[test]
    fn test_is_workspace_updated() -> Result<(), Box<dyn std::error::Error>> {
        let mgr = dummy_manager()?;

        println!("index: {:?}", mgr.repo.index()?.path());

        let dir = std::env::current_dir()?;

        assert_eq!(mgr.is_version_outdated(dir)?.is_some(), false);

        Ok(())
    }
}