Modules refactor

This commit is contained in:
Roey Darwish Dror
2018-12-15 21:52:21 +02:00
parent 66c6338b42
commit 47a271af47
14 changed files with 63 additions and 61 deletions

14
src/steps/emacs.el Normal file
View File

@@ -0,0 +1,14 @@
(if (fboundp 'paradox-upgrade-packages)
(progn
(paradox-upgrade-packages)
(princ
(if (get-buffer "*Paradox Report*")
(with-current-buffer "*Paradox Report*" (buffer-string))
"\nNothing to upgrade\n")))
(progn
(let ((package-menu-async nil))
(package-list-packages))
(package-menu-mark-upgrades)
(condition-case nil
(package-menu-execute 'noquery)
(user-error nil))))

261
src/steps/generic.rs Normal file
View File

@@ -0,0 +1,261 @@
use crate::error::{Error, ErrorKind};
use crate::executor::Executor;
use crate::terminal::print_separator;
use crate::utils::{self, Check, PathExt};
use directories::BaseDirs;
use failure::ResultExt;
use std::path::PathBuf;
use std::process::Command;
const EMACS_UPGRADE: &str = include_str!("emacs.el");
#[must_use]
pub fn run_cargo_update(dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(cargo_update) = utils::which("cargo-install-update") {
print_separator("Cargo");
let success = || -> Result<(), Error> {
Executor::new(cargo_update, dry_run)
.args(&["install-update", "--git", "--all"])
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
return Some(("Cargo", success));
}
None
}
#[must_use]
pub fn run_gem(base_dirs: &BaseDirs, dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(gem) = utils::which("gem") {
if base_dirs.home_dir().join(".gem").exists() {
print_separator("RubyGems");
let success = || -> Result<(), Error> {
Executor::new(&gem, dry_run)
.args(&["update", "--user-install"])
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
return Some(("RubyGems", success));
}
}
None
}
#[must_use]
pub fn run_emacs(base_dirs: &BaseDirs, dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(emacs) = utils::which("emacs") {
if let Some(init_file) = base_dirs.home_dir().join(".emacs.d/init.el").if_exists() {
print_separator("Emacs");
let success = || -> Result<(), Error> {
Executor::new(&emacs, dry_run)
.args(&["--batch", "-l", init_file.to_str().unwrap(), "--eval", EMACS_UPGRADE])
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
return Some(("Emacs", success));
}
}
None
}
#[must_use]
#[cfg(not(any(
target_os = "freebsd",
target_os = "openbsd",
target_os = "netbsd",
target_os = "dragonfly"
)))]
pub fn run_apm(dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(apm) = utils::which("apm") {
print_separator("Atom Package Manager");
let success = || -> Result<(), Error> {
Executor::new(&apm, dry_run)
.args(&["upgrade", "--confirm=false"])
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
return Some(("apm", success));
}
None
}
#[must_use]
pub fn run_rustup(base_dirs: &BaseDirs, dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(rustup) = utils::which("rustup") {
print_separator("rustup");
let success = || -> Result<(), Error> {
if rustup.is_descendant_of(base_dirs.home_dir()) {
Executor::new(&rustup, dry_run)
.args(&["self", "update"])
.spawn()?
.wait()?
.check()?;
}
Executor::new(&rustup, dry_run).arg("update").spawn()?.wait()?.check()?;
Ok(())
}()
.is_ok();
return Some(("rustup", success));
}
None
}
#[must_use]
pub fn run_jetpack(dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(jetpack) = utils::which("jetpack") {
print_separator("Jetpack");
let success = || -> Result<(), Error> {
Executor::new(&jetpack, dry_run)
.args(&["global", "update"])
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
return Some(("Jetpack", success));
}
None
}
#[must_use]
pub fn run_opam_update(dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(opam) = utils::which("opam") {
print_separator("OCaml Package Manager");
let success = || -> Result<(), Error> {
Executor::new(&opam, dry_run).arg("update").spawn()?.wait()?.check()?;
Executor::new(&opam, dry_run).arg("upgrade").spawn()?.wait()?.check()?;
Ok(())
}()
.is_ok();
return Some(("OPAM", success));
}
None
}
#[must_use]
pub fn run_vcpkg_update(dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(vcpkg) = utils::which("vcpkg") {
print_separator("vcpkg");
let success = || -> Result<(), Error> {
Executor::new(&vcpkg, dry_run)
.args(&["upgrade", "--no-dry-run"])
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
return Some(("vcpkg", success));
}
None
}
#[must_use]
pub fn run_pipx_update(dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(pipx) = utils::which("pipx") {
print_separator("pipx");
let success = || -> Result<(), Error> {
Executor::new(&pipx, dry_run)
.arg("upgrade-all")
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
return Some(("pipx", success));
}
None
}
#[must_use]
pub fn run_custom_command(name: &str, command: &str, dry_run: bool) -> Result<(), Error> {
print_separator(name);
Executor::new("sh", dry_run)
.arg("-c")
.arg(command)
.spawn()?
.wait()?
.check()?;
Ok(())
}
#[must_use]
pub fn run_composer_update(base_dirs: &BaseDirs, dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(composer) = utils::which("composer") {
let composer_home = || -> Result<PathBuf, Error> {
let output = Command::new(&composer)
.args(&["global", "config", "--absolute", "home"])
.output()
.context(ErrorKind::ProcessExecution)?;
output.status.check()?;
Ok(PathBuf::from(
&String::from_utf8(output.stdout).context(ErrorKind::ProcessExecution)?,
))
}();
if let Ok(composer_home) = composer_home {
if composer_home.is_descendant_of(base_dirs.home_dir()) {
print_separator("Composer");
let success = || -> Result<(), Error> {
Executor::new(&composer, dry_run)
.args(&["global", "update"])
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
return Some(("Composer", success));
}
}
}
None
}

108
src/steps/git.rs Normal file
View File

@@ -0,0 +1,108 @@
use crate::error::Error;
use crate::executor::Executor;
use crate::terminal::print_separator;
use crate::utils::{which, Check};
use log::{debug, error};
use std::collections::HashSet;
use std::io;
use std::path::{Path, PathBuf};
use std::process::Command;
pub struct Git {
git: Option<PathBuf>,
}
pub struct Repositories<'a> {
git: &'a Git,
repositories: HashSet<String>,
}
impl Git {
pub fn new() -> Self {
Self { git: which("git") }
}
pub fn get_repo_root<P: AsRef<Path>>(&self, path: P) -> Option<String> {
match path.as_ref().canonicalize() {
Ok(mut path) => {
debug_assert!(path.exists());
if path.is_file() {
debug!("{} is a file. Checking {}", path.display(), path.parent()?.display());
path = path.parent()?.to_path_buf();
}
debug!("Checking if {} is a git repository", path.display());
if let Some(git) = &self.git {
let output = Command::new(&git)
.args(&["rev-parse", "--show-toplevel"])
.current_dir(path)
.output();
if let Ok(output) = output {
if !output.status.success() {
return None;
}
return Some(String::from_utf8_lossy(&output.stdout).trim().to_string());
}
}
}
Err(e) => match e.kind() {
io::ErrorKind::NotFound => debug!("{} does not exists", path.as_ref().display()),
_ => error!("Error looking for {}: {}", path.as_ref().display(), e),
},
}
None
}
pub fn pull<P: AsRef<Path>>(&self, path: P, dry_run: bool) -> Option<(String, bool)> {
let path = path.as_ref();
print_separator(format!("Pulling {}", path.display()));
let git = self.git.as_ref().unwrap();
let success = || -> Result<(), Error> {
Executor::new(git, dry_run)
.args(&["pull", "--rebase", "--autostash"])
.current_dir(&path)
.spawn()?
.wait()?
.check()?;
Executor::new(git, dry_run)
.args(&["submodule", "update", "--init", "--recursive"])
.current_dir(&path)
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
Some((format!("git: {}", path.display()), success))
}
}
impl<'a> Repositories<'a> {
pub fn new(git: &'a Git) -> Self {
Self {
git,
repositories: HashSet::new(),
}
}
pub fn insert<P: AsRef<Path>>(&mut self, path: P) {
if let Some(repo) = self.git.get_repo_root(path) {
self.repositories.insert(repo);
}
}
pub fn repositories(&self) -> &HashSet<String> {
&self.repositories
}
}

9
src/steps/mod.rs Normal file
View File

@@ -0,0 +1,9 @@
pub mod generic;
pub mod git;
pub mod node;
pub mod os;
#[cfg(unix)]
pub mod tmux;
pub mod vim;
pub use self::os::*;

76
src/steps/node.rs Normal file
View File

@@ -0,0 +1,76 @@
use crate::error::{Error, ErrorKind};
use crate::executor::Executor;
use crate::terminal::print_separator;
use crate::utils::{which, Check, PathExt};
use directories::BaseDirs;
use failure::ResultExt;
use std::path::PathBuf;
use std::process::Command;
struct NPM {
command: PathBuf,
}
impl NPM {
fn new(command: PathBuf) -> Self {
Self { command }
}
fn root(&self) -> Result<PathBuf, Error> {
let output = Command::new(&self.command)
.args(&["root", "-g"])
.output()
.context(ErrorKind::ProcessExecution)?;
output.status.check()?;
Ok(PathBuf::from(
&String::from_utf8(output.stdout).context(ErrorKind::ProcessExecution)?,
))
}
fn upgrade(&self, dry_run: bool) -> Result<(), Error> {
Executor::new(&self.command, dry_run)
.args(&["update", "-g"])
.spawn()?
.wait()?
.check()?;
Ok(())
}
}
#[must_use]
pub fn run_npm_upgrade(base_dirs: &BaseDirs, dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(npm) = which("npm").map(NPM::new) {
if let Ok(npm_root) = npm.root() {
if npm_root.is_descendant_of(base_dirs.home_dir()) {
print_separator("Node Package Manager");
let success = npm.upgrade(dry_run).is_ok();
return Some(("NPM", success));
}
}
}
None
}
#[must_use]
pub fn yarn_global_update(dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(yarn) = which("yarn") {
print_separator("Yarn");
let success = || -> Result<(), Error> {
Executor::new(&yarn, dry_run)
.args(&["global", "upgrade", "-s"])
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
return Some(("yarn", success));
}
None
}

64
src/steps/os/freebsd.rs Normal file
View File

@@ -0,0 +1,64 @@
use crate::error::{Error, ErrorKind};
use crate::executor::Executor;
use crate::terminal::{print_separator, print_warning};
use crate::utils::Check;
use failure::ResultExt;
use std::path::PathBuf;
use std::process::Command;
#[must_use]
pub fn upgrade_freebsd(sudo: &Option<PathBuf>, dry_run: bool) -> Option<(&'static str, bool)> {
print_separator("FreeBSD Update");
if let Some(sudo) = sudo {
let success = || -> Result<(), Error> {
Executor::new(sudo, dry_run)
.args(&["/usr/sbin/freebsd-update", "fetch", "install"])
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
Some(("FreeBSD Update", success))
} else {
print_warning("No sudo or yay detected. Skipping system upgrade");
None
}
}
#[must_use]
pub fn upgrade_packages(sudo: &Option<PathBuf>, dry_run: bool) -> Option<(&'static str, bool)> {
print_separator("FreeBSD Packages");
if let Some(sudo) = sudo {
let success = || -> Result<(), Error> {
Executor::new(sudo, dry_run)
.args(&["/usr/sbin/pkg", "upgrade"])
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
Some(("FreeBSD Packages", success))
} else {
print_warning("No sudo or yay detected. Skipping package upgrade");
None
}
}
pub fn audit_packages(sudo: &Option<PathBuf>) -> Result<(), Error> {
if let Some(sudo) = sudo {
println!();
Command::new(sudo)
.args(&["/usr/sbin/pkg", "audit", "-Fr"])
.spawn()
.context(ErrorKind::ProcessExecution)?
.wait()
.context(ErrorKind::ProcessExecution)?;
}
Ok(())
}

407
src/steps/os/linux.rs Normal file
View File

@@ -0,0 +1,407 @@
use crate::error::{Error, ErrorKind};
use crate::executor::Executor;
use crate::terminal::{print_separator, print_warning};
use crate::utils::{which, Check};
use failure::ResultExt;
use std::fs;
use std::path::PathBuf;
use walkdir::WalkDir;
#[derive(Copy, Clone, Debug)]
pub enum Distribution {
Arch,
CentOS,
Fedora,
Debian,
Ubuntu,
Gentoo,
OpenSuse,
Void,
}
impl Distribution {
pub fn detect() -> Result<Self, Error> {
let content = fs::read_to_string("/etc/os-release").context(ErrorKind::UnknownLinuxDistribution)?;
if content.contains("Arch") | content.contains("Manjaro") | content.contains("Antergos") {
return Ok(Distribution::Arch);
}
if content.contains("CentOS") || content.contains("Oracle Linux") {
return Ok(Distribution::CentOS);
}
if content.contains("Fedora") {
return Ok(Distribution::Fedora);
}
if content.contains("Ubuntu") {
return Ok(Distribution::Ubuntu);
}
if content.contains("Debian") {
return Ok(Distribution::Debian);
}
if content.contains("openSUSE") {
return Ok(Distribution::OpenSuse);
}
if content.contains("void") {
return Ok(Distribution::Void);
}
if PathBuf::from("/etc/gentoo-release").exists() {
return Ok(Distribution::Gentoo);
}
Err(ErrorKind::UnknownLinuxDistribution)?
}
#[must_use]
pub fn upgrade(self, sudo: &Option<PathBuf>, cleanup: bool, dry_run: bool) -> Option<(&'static str, bool)> {
print_separator("System update");
let success = match self {
Distribution::Arch => upgrade_arch_linux(&sudo, dry_run),
Distribution::CentOS => upgrade_redhat(&sudo, dry_run),
Distribution::Fedora => upgrade_fedora(&sudo, dry_run),
Distribution::Ubuntu | Distribution::Debian => upgrade_debian(&sudo, cleanup, dry_run),
Distribution::Gentoo => upgrade_gentoo(&sudo, dry_run),
Distribution::OpenSuse => upgrade_opensuse(&sudo, dry_run),
Distribution::Void => upgrade_void(&sudo, dry_run),
};
Some(("System update", success.is_ok()))
}
pub fn show_summary(self) {
if let Distribution::Arch = self {
show_pacnew();
}
}
}
pub fn show_pacnew() {
let mut iter = WalkDir::new("/etc")
.into_iter()
.filter_map(|e| e.ok())
.filter(|f| {
f.path()
.extension()
.filter(|ext| ext == &"pacnew" || ext == &"pacsave")
.is_some()
})
.peekable();
if iter.peek().is_some() {
println!("\nPacman backup configuration files found:");
for entry in iter {
println!("{}", entry.path().display());
}
}
}
fn upgrade_arch_linux(sudo: &Option<PathBuf>, dry_run: bool) -> Result<(), Error> {
if let Some(yay) = which("yay") {
if let Some(python) = which("python") {
if python != PathBuf::from("/usr/bin/python") {
print_warning(format!(
"Python detected at {:?}, which is probably not the system Python.
It's dangerous to run yay since Python based AUR packages will be installed in the wrong location",
python
));
return Err(ErrorKind::NotSystemPython)?;
}
}
Executor::new(yay, dry_run).spawn()?.wait()?.check()?;
} else if let Some(sudo) = &sudo {
Executor::new(&sudo, dry_run)
.args(&["/usr/bin/pacman", "-Syu"])
.spawn()?
.wait()?
.check()?;
} else {
print_warning("No sudo or yay detected. Skipping system upgrade");
}
Ok(())
}
fn upgrade_redhat(sudo: &Option<PathBuf>, dry_run: bool) -> Result<(), Error> {
if let Some(sudo) = &sudo {
Executor::new(&sudo, dry_run)
.args(&["/usr/bin/yum", "upgrade"])
.spawn()?
.wait()?
.check()?;
} else {
print_warning("No sudo detected. Skipping system upgrade");
}
Ok(())
}
fn upgrade_opensuse(sudo: &Option<PathBuf>, dry_run: bool) -> Result<(), Error> {
if let Some(sudo) = &sudo {
Executor::new(&sudo, dry_run)
.args(&["/usr/bin/zypper", "refresh"])
.spawn()?
.wait()?
.check()?;
Executor::new(&sudo, dry_run)
.args(&["/usr/bin/zypper", "dist-upgrade"])
.spawn()?
.wait()?
.check()?;
} else {
print_warning("No sudo detected. Skipping system upgrade");
}
Ok(())
}
fn upgrade_void(sudo: &Option<PathBuf>, dry_run: bool) -> Result<(), Error> {
if let Some(sudo) = &sudo {
Executor::new(&sudo, dry_run)
.args(&["/usr/bin/xbps-install", "-Su"])
.spawn()?
.wait()?
.check()?;
} else {
print_warning("No sudo detected. Skipping system upgrade");
}
Ok(())
}
fn upgrade_fedora(sudo: &Option<PathBuf>, dry_run: bool) -> Result<(), Error> {
if let Some(sudo) = &sudo {
Executor::new(&sudo, dry_run)
.args(&["/usr/bin/dnf", "upgrade"])
.spawn()?
.wait()?
.check()?;
} else {
print_warning("No sudo detected. Skipping system upgrade");
}
Ok(())
}
fn upgrade_gentoo(sudo: &Option<PathBuf>, dry_run: bool) -> Result<(), Error> {
if let Some(sudo) = &sudo {
if let Some(layman) = which("layman") {
Executor::new(&sudo, dry_run)
.arg(layman)
.args(&["-s", "ALL"])
.spawn()?
.wait()?
.check()?;
}
println!("Syncing portage");
Executor::new(&sudo, dry_run)
.arg("/usr/bin/emerge")
.args(&["-q", "--sync"])
.spawn()?
.wait()?
.check()?;
if let Some(eix_update) = which("eix-update") {
Executor::new(&sudo, dry_run).arg(eix_update).spawn()?.wait()?.check()?;
}
Executor::new(&sudo, dry_run)
.arg("/usr/bin/emerge")
.args(&["-uDNa", "world"])
.spawn()?
.wait()?
.check()?;
} else {
print_warning("No sudo detected. Skipping system upgrade");
}
Ok(())
}
fn upgrade_debian(sudo: &Option<PathBuf>, cleanup: bool, dry_run: bool) -> Result<(), Error> {
if let Some(sudo) = &sudo {
Executor::new(&sudo, dry_run)
.args(&["/usr/bin/apt", "update"])
.spawn()?
.wait()?
.check()?;
Executor::new(&sudo, dry_run)
.args(&["/usr/bin/apt", "dist-upgrade"])
.spawn()?
.wait()?
.check()?;
if cleanup {
Executor::new(&sudo, dry_run)
.args(&["/usr/bin/apt", "clean"])
.spawn()?
.wait()?
.check()?;
Executor::new(&sudo, dry_run)
.args(&["/usr/bin/apt", "autoremove"])
.spawn()?
.wait()?
.check()?;
}
} else {
print_warning("No sudo detected. Skipping system upgrade");
}
Ok(())
}
#[must_use]
pub fn run_needrestart(sudo: &Option<PathBuf>, dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(sudo) = sudo {
if let Some(needrestart) = which("needrestart") {
print_separator("Check for needed restarts");
let success = || -> Result<(), Error> {
Executor::new(&sudo, dry_run)
.arg(needrestart)
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
return Some(("Restarts", success));
}
}
None
}
#[must_use]
pub fn run_fwupdmgr(dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(fwupdmgr) = which("fwupdmgr") {
print_separator("Firmware upgrades");
let success = || -> Result<(), Error> {
Executor::new(&fwupdmgr, dry_run)
.arg("refresh")
.spawn()?
.wait()?
.check()?;
Executor::new(&fwupdmgr, dry_run)
.arg("get-updates")
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
return Some(("Firmware upgrade", success));
}
None
}
#[must_use]
pub fn flatpak_user_update(dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(flatpak) = which("flatpak") {
print_separator("Flatpak User Packages");
let success = || -> Result<(), Error> {
Executor::new(&flatpak, dry_run)
.args(&["update", "--user", "-y"])
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
return Some(("Flatpak User Packages", success));
}
None
}
#[must_use]
pub fn flatpak_global_update(sudo: &Option<PathBuf>, dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(sudo) = sudo {
if let Some(flatpak) = which("flatpak") {
print_separator("Flatpak Global Packages");
let success = || -> Result<(), Error> {
Executor::new(&sudo, dry_run)
.args(&[flatpak.to_str().unwrap(), "update", "-y"])
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
return Some(("Flatpak Global Packages", success));
}
}
None
}
#[must_use]
pub fn run_snap(sudo: &Option<PathBuf>, dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(sudo) = sudo {
if let Some(snap) = which("snap") {
if PathBuf::from("/var/snapd.socket").exists() {
print_separator("snap");
let success = || -> Result<(), Error> {
Executor::new(&sudo, dry_run)
.args(&[snap.to_str().unwrap(), "refresh"])
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
return Some(("snap", success));
}
}
}
None
}
#[must_use]
pub fn run_etc_update(sudo: &Option<PathBuf>, dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(sudo) = sudo {
if let Some(etc_update) = which("etc-update") {
print_separator("etc-update");
let success = || -> Result<(), Error> {
Executor::new(&sudo, dry_run)
.arg(&etc_update.to_str().unwrap())
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
return Some(("etc-update", success));
}
}
None
}

21
src/steps/os/macos.rs Normal file
View File

@@ -0,0 +1,21 @@
use crate::error::Error;
use crate::executor::Executor;
use crate::terminal::print_separator;
use crate::utils::Check;
#[must_use]
pub fn upgrade_macos(dry_run: bool) -> Option<(&'static str, bool)> {
print_separator("App Store");
let success = || -> Result<(), Error> {
Executor::new("softwareupdate", dry_run)
.args(&["--install", "--all"])
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
Some(("App Store", success))
}

10
src/steps/os/mod.rs Normal file
View File

@@ -0,0 +1,10 @@
#[cfg(target_os = "freebsd")]
pub mod freebsd;
#[cfg(target_os = "linux")]
pub mod linux;
#[cfg(target_os = "macos")]
pub mod macos;
#[cfg(unix)]
pub mod unix;
#[cfg(target_os = "windows")]
pub mod windows;

101
src/steps/os/unix.rs Normal file
View File

@@ -0,0 +1,101 @@
use crate::error::Error;
use crate::executor::Executor;
use crate::terminal::print_separator;
use crate::utils::{which, Check};
use directories::BaseDirs;
pub fn run_zplug(base_dirs: &BaseDirs, dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(zsh) = which("zsh") {
if base_dirs.home_dir().join(".zplug").exists() {
print_separator("zplug");
let success = || -> Result<(), Error> {
Executor::new(zsh, dry_run)
.args(&["-c", "source ~/.zshrc && zplug update"])
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
return Some(("zplug", success));
}
}
None
}
pub fn run_fisher(base_dirs: &BaseDirs, dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(fish) = which("fish") {
if base_dirs.home_dir().join(".config/fish/functions/fisher.fish").exists() {
print_separator("fisher");
let success = || -> Result<(), Error> {
Executor::new(&fish, dry_run)
.args(&["-c", "fisher self-update"])
.spawn()?
.wait()?
.check()?;
Executor::new(&fish, dry_run)
.args(&["-c", "fisher"])
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
return Some(("fisher", success));
}
}
None
}
#[must_use]
pub fn run_homebrew(cleanup: bool, dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(brew) = which("brew") {
print_separator("Brew");
let inner = || -> Result<(), Error> {
Executor::new(&brew, dry_run).arg("update").spawn()?.wait()?.check()?;
Executor::new(&brew, dry_run).arg("upgrade").spawn()?.wait()?.check()?;
if cleanup {
Executor::new(&brew, dry_run).arg("cleanup").spawn()?.wait()?.check()?;
}
Ok(())
};
return Some(("Brew", inner().is_ok()));
}
None
}
#[must_use]
pub fn run_nix(dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(nix) = which("nix") {
if let Some(nix_env) = which("nix-env") {
print_separator("Nix");
let inner = || -> Result<(), Error> {
Executor::new(&nix, dry_run)
.arg("upgrade-nix")
.spawn()?
.wait()?
.check()?;
Executor::new(&nix_env, dry_run)
.arg("--upgrade")
.spawn()?
.wait()?
.check()?;
Ok(())
};
return Some(("Nix", inner().is_ok()));
}
}
None
}

144
src/steps/os/windows.rs Normal file
View File

@@ -0,0 +1,144 @@
use crate::error::{Error, ErrorKind};
use crate::executor::Executor;
use crate::terminal::print_separator;
use crate::utils::{self, which, Check};
use failure::ResultExt;
use log::error;
use std::path::PathBuf;
use std::process::Command;
#[must_use]
pub fn run_chocolatey(dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(choco) = utils::which("choco") {
print_separator("Chocolatey");
let success = || -> Result<(), Error> {
Executor::new(&choco, dry_run)
.args(&["upgrade", "all"])
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
return Some(("Chocolatey", success));
}
None
}
#[must_use]
pub fn run_scoop(dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(scoop) = utils::which("scoop") {
print_separator("Scoop");
let success = || -> Result<(), Error> {
Executor::new(&scoop, dry_run)
.args(&["update"])
.spawn()?
.wait()?
.check()?;
Executor::new(&scoop, dry_run)
.args(&["update", "*"])
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
return Some(("Scoop", success));
}
None
}
pub struct Powershell {
path: Option<PathBuf>,
}
impl Powershell {
pub fn new() -> Self {
Powershell {
path: which("powershell"),
}
}
pub fn has_command(powershell: &PathBuf, command: &str) -> bool {
|| -> Result<(), Error> {
Command::new(&powershell)
.args(&["-Command", &format!("Get-Command {}", command)])
.output()
.context(ErrorKind::ProcessExecution)?
.check()?;
Ok(())
}()
.is_ok()
}
pub fn profile(&self) -> Option<PathBuf> {
if let Some(powershell) = &self.path {
let result = || -> Result<PathBuf, Error> {
let output = Command::new(powershell)
.args(&["-Command", "echo $profile"])
.output()
.context(ErrorKind::ProcessExecution)?;
output.status.check()?;
Ok(PathBuf::from(
String::from_utf8_lossy(&output.stdout).trim().to_string(),
))
}();
match result {
Err(e) => error!("Error getting Powershell profile: {}", e),
Ok(path) => return Some(path),
}
}
None
}
#[must_use]
pub fn update_modules(&self, dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(powershell) = &self.path {
print_separator("Powershell Modules Update");
let success = || -> Result<(), Error> {
Executor::new(&powershell, dry_run)
.arg("Update-Module")
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
return Some(("Powershell Modules Update", success));
}
None
}
#[must_use]
pub fn windows_update(&self, dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(powershell) = &self.path {
if Self::has_command(&powershell, "Install-WindowsUpdate") {
print_separator("Windows Update");
let success = || -> Result<(), Error> {
Executor::new(&powershell, dry_run)
.args(&["-Command", "Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -Verbose"])
.spawn()?
.wait()?
.check()?;
Ok(())
}()
.is_ok();
return Some(("Windows Update", success));
}
}
None
}
}

81
src/steps/tmux.rs Normal file
View File

@@ -0,0 +1,81 @@
use crate::error::{Error, ErrorKind};
use crate::executor::Executor;
use crate::terminal::print_separator;
use crate::utils::{which, Check, PathExt};
use directories::BaseDirs;
use failure::ResultExt;
use std::env;
use std::io;
use std::os::unix::process::CommandExt;
use std::path::Path;
use std::process::Command;
pub fn run_tpm(base_dirs: &BaseDirs, dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(tpm) = base_dirs
.home_dir()
.join(".tmux/plugins/tpm/bin/update_plugins")
.if_exists()
{
print_separator("tmux plugins");
let success = || -> Result<(), Error> {
Executor::new(&tpm, dry_run).arg("all").spawn()?.wait()?.check()?;
Ok(())
}()
.is_ok();
return Some(("tmux", success));
}
None
}
fn has_session(tmux: &Path, session_name: &str) -> Result<bool, io::Error> {
Ok(Command::new(tmux)
.args(&["has-session", "-t", session_name])
.spawn()?
.wait()?
.success())
}
fn run_in_session(tmux: &Path, command: &str) -> Result<(), Error> {
Command::new(tmux)
.args(&["new-window", "-a", "-t", "topgrade:1", command])
.spawn()
.context(ErrorKind::ProcessExecution)?
.wait()
.context(ErrorKind::ProcessExecution)?
.check()?;
Ok(())
}
pub fn run_in_tmux() -> ! {
let tmux = which("tmux").expect("Could not find tmux");
let command = env::args().collect::<Vec<String>>().join(" ");
if has_session(&tmux, "topgrade").expect("Error launching tmux") {
run_in_session(&tmux, &command).expect("Error launching tmux");
let err = Command::new(tmux).args(&["attach", "-t", "topgrade"]).exec();
panic!("{:?}", err);
} else {
let err = Command::new(tmux)
.args(&[
"new-session",
"-s",
"topgrade",
"-n",
"topgrade",
&command,
";",
"set",
"remain-on-exit",
"on",
])
.exec();
panic!("{:?}", err);
}
}

108
src/steps/vim.rs Normal file
View File

@@ -0,0 +1,108 @@
use crate::error::Error;
use crate::executor::Executor;
use crate::terminal::print_separator;
use crate::utils::{which, Check, PathExt};
use directories::BaseDirs;
use std::fs;
use std::path::PathBuf;
#[derive(Debug, Clone, Copy)]
pub enum PluginFramework {
Plug,
Vundle,
NeoBundle,
}
impl PluginFramework {
pub fn detect(vimrc: &PathBuf) -> Option<PluginFramework> {
let content = fs::read_to_string(vimrc).ok()?;
if content.contains("NeoBundle") {
Some(PluginFramework::NeoBundle)
} else if content.contains("Vundle") {
Some(PluginFramework::Vundle)
} else if content.contains("plug#begin") {
Some(PluginFramework::Plug)
} else {
None
}
}
pub fn upgrade_command(self) -> &'static str {
match self {
PluginFramework::NeoBundle => "NeoBundleUpdate",
PluginFramework::Vundle => "PluginUpdate",
PluginFramework::Plug => "PlugUpgrade | PlugUpdate",
}
}
}
pub fn vimrc(base_dirs: &BaseDirs) -> Option<PathBuf> {
base_dirs
.home_dir()
.join(".vimrc")
.if_exists()
.or_else(|| base_dirs.home_dir().join(".vim/vimrc").if_exists())
}
fn nvimrc(base_dirs: &BaseDirs) -> Option<PathBuf> {
#[cfg(unix)]
return base_dirs.config_dir().join("nvim/init.vim").if_exists();
#[cfg(windows)]
return base_dirs.cache_dir().join("nvim/init.vim").if_exists();
}
#[must_use]
fn upgrade(vim: &PathBuf, vimrc: &PathBuf, plugin_framework: PluginFramework, dry_run: bool) -> Result<(), Error> {
Executor::new(&vim, dry_run)
.args(&[
"-N",
"-u",
vimrc.to_str().unwrap(),
"-c",
plugin_framework.upgrade_command(),
"-c",
"quitall",
"-e",
"-s",
"-V1",
])
.spawn()?
.wait()?
.check()?;
println!();
Ok(())
}
#[must_use]
pub fn upgrade_vim(base_dirs: &BaseDirs, dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(vim) = which("vim") {
if let Some(vimrc) = vimrc(&base_dirs) {
if let Some(plugin_framework) = PluginFramework::detect(&vimrc) {
print_separator(&format!("Vim ({:?})", plugin_framework));
let success = upgrade(&vim, &vimrc, plugin_framework, dry_run).is_ok();
return Some(("vim", success));
}
}
}
None
}
#[must_use]
pub fn upgrade_neovim(base_dirs: &BaseDirs, dry_run: bool) -> Option<(&'static str, bool)> {
if let Some(nvim) = which("nvim") {
if let Some(nvimrc) = nvimrc(&base_dirs) {
if let Some(plugin_framework) = PluginFramework::detect(&nvimrc) {
print_separator(&format!("Neovim ({:?})", plugin_framework));
let success = upgrade(&nvim, &nvimrc, plugin_framework, dry_run).is_ok();
return Some(("Neovim", success));
}
}
}
None
}