Files
topgrade/src/utils.rs

155 lines
4.7 KiB
Rust
Raw Normal View History

use crate::error::SkipStep;
2022-11-11 09:39:29 -05:00
use color_eyre::eyre::Result;
use std::env;
2018-06-17 14:17:36 +03:00
use std::ffi::OsStr;
use std::fmt::Debug;
use std::path::{Path, PathBuf};
2022-11-16 13:43:57 -05:00
use tracing::{debug, error};
2018-07-07 09:18:53 +03:00
pub trait PathExt
where
Self: Sized,
{
fn if_exists(self) -> Option<Self>;
2018-08-22 10:43:32 +03:00
fn is_descendant_of(&self, ancestor: &Path) -> bool;
2019-01-13 23:20:32 +02:00
/// Returns the path if it exists or ErrorKind::SkipStep otherwise
fn require(self) -> Result<Self>;
2018-07-07 09:18:53 +03:00
}
2019-09-28 20:26:03 +03:00
impl<T> PathExt for T
where
T: AsRef<Path>,
{
2018-07-07 09:18:53 +03:00
fn if_exists(self) -> Option<Self> {
2019-09-28 20:26:03 +03:00
if self.as_ref().exists() {
debug!("Path {:?} exists", self.as_ref());
2018-07-07 09:18:53 +03:00
Some(self)
} else {
debug!("Path {:?} doesn't exist", self.as_ref());
2018-07-07 09:18:53 +03:00
None
}
2018-06-17 11:43:25 +03:00
}
2018-07-07 09:18:53 +03:00
fn is_descendant_of(&self, ancestor: &Path) -> bool {
2019-09-28 20:26:03 +03:00
self.as_ref().iter().zip(ancestor.iter()).all(|(a, b)| a == b)
2018-07-07 09:18:53 +03:00
}
2019-01-13 23:20:32 +02:00
fn require(self) -> Result<Self> {
2019-09-28 20:26:03 +03:00
if self.as_ref().exists() {
2019-12-08 20:56:03 +02:00
debug!("Path {:?} exists", self.as_ref());
2019-01-13 23:20:32 +02:00
Ok(self)
} else {
2020-08-21 23:04:36 +03:00
Err(SkipStep(format!("Path {:?} doesn't exist", self.as_ref())).into())
2019-01-13 23:20:32 +02:00
}
}
2018-06-17 11:43:25 +03:00
}
2018-06-17 14:17:36 +03:00
pub fn which<T: AsRef<OsStr> + Debug>(binary_name: T) -> Option<PathBuf> {
2018-12-09 10:30:41 +02:00
match which_crate::which(&binary_name) {
2018-06-17 14:17:36 +03:00
Ok(path) => {
debug!("Detected {:?} as {:?}", &path, &binary_name);
Some(path)
}
Err(e) => {
2020-06-18 22:25:27 +03:00
match e {
which_crate::Error::CannotFindBinaryPath => {
2018-06-17 14:17:36 +03:00
debug!("Cannot find {:?}", &binary_name);
}
_ => {
error!("Detecting {:?} failed: {}", &binary_name, e);
}
}
None
}
}
}
2020-06-24 08:59:06 +03:00
pub fn editor() -> Vec<String> {
env::var("EDITOR")
.unwrap_or_else(|_| String::from(if cfg!(windows) { "notepad" } else { "vi" }))
.split_whitespace()
.map(|s| s.to_owned())
.collect()
}
pub fn require<T: AsRef<OsStr> + Debug>(binary_name: T) -> Result<PathBuf> {
2019-01-13 23:20:32 +02:00
match which_crate::which(&binary_name) {
Ok(path) => {
debug!("Detected {:?} as {:?}", &path, &binary_name);
Ok(path)
}
2020-06-18 22:25:27 +03:00
Err(e) => match e {
which_crate::Error::CannotFindBinaryPath => {
2020-08-21 23:04:36 +03:00
Err(SkipStep(format!("Cannot find {:?} in PATH", &binary_name)).into())
2019-01-13 23:20:32 +02:00
}
_ => {
panic!("Detecting {:?} failed: {}", &binary_name, e);
}
},
}
}
2019-02-11 14:10:06 +02:00
2019-02-11 20:38:51 +02:00
#[allow(dead_code)]
2020-08-21 23:04:36 +03:00
pub fn require_option<T>(option: Option<T>, cause: String) -> Result<T> {
2021-10-28 22:05:35 +03:00
if let Some(value) = option {
Ok(value)
} else {
Err(SkipStep(cause).into())
}
2019-02-11 14:10:06 +02:00
}
/* sys-info-rs
*
* Copyright (c) 2015 Siyu Wang
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#[cfg(target_family = "unix")]
pub fn hostname() -> Result<String> {
use std::ffi;
extern crate libc;
unsafe {
let buf_size = libc::sysconf(libc::_SC_HOST_NAME_MAX) as usize;
let mut buf = Vec::<u8>::with_capacity(buf_size + 1);
if libc::gethostname(buf.as_mut_ptr() as *mut libc::c_char, buf_size) < 0 {
return Err(SkipStep(format!("Failed to get hostname: {}", std::io::Error::last_os_error())).into());
}
let hostname_len = libc::strnlen(buf.as_ptr() as *const libc::c_char, buf_size);
buf.set_len(hostname_len);
Ok(ffi::CString::new(buf).unwrap().into_string().unwrap())
}
}
#[cfg(target_family = "windows")]
pub fn hostname() -> Result<String> {
use crate::command::CommandExt;
use std::process::Command;
Command::new("hostname")
.output_checked_utf8()
v10.2.5 release (#330) * Don't show desktop notification on error (if `skip_notify = true`) (#275) * Use ─ (U+2500) to draw borders (#282) * Adds Pclinuxos support (#283) * Add Devkitpro Pacman support (#291) * Added support for Neovim package manager lazy.nvim (#293) * Added support for lazy.nvim From https://github.com/folke/lazy.nvim Authored-by: Jacob Lane Ledbetter <jledbetter460@gmail.com> * Make garuda-update update AUR packages by default (#296) * fix(#298): Don't throw error if no Helm repository found (#305) * Skip .NET when `dotnet tool list` is not successful (#302) * feat(pacstall): add `-y` flag variant (#312) * Add openSUSE MicroOS support (#315) * Adds notify-send timeout of 10s (#318) * Don't run yum when rpm-ostree is available (#313) * don't run yum when rpm-ostree is available * Clippy fix * rpm-ostree: set default value to true * Fixes if loop error * Fixes gem update --system requires sudo now (#317) * Fixes gem update --system requires sudo now * rubygem: Adds arg -EH to sudo * Use fixed nala path instead of which(nala) (#314) * Adds notify-send bug warning when topgrade is run (#324) * Adds notify-send bug warning when topgrade is run * fix typo + clippy * notify-send warning respects skip_notify flag * nix: Adds additional arguments support (#325) * Adds pip-review and pipupgrade support (#316) * Adds pip-review and pipupgrade support * Python: fixes pip_review and pipupgrade * v10.2.5 patch (#329) * WSL: Adds new wsl --update flags (#327) * wsl: Updates available flags * Clippy fix * Add WslUpdate runner * wsl: Code Typo * wsl: Code Typos * wsl: Code Typos * wsl: Code Typo * Adds AM Package Manager (#328) * Adds AM Package Manager * Clippy fixes * Cargo fmt * Moves am to linux only in main file --------- Co-authored-by: Guilherme Silva <626206+guihkx@users.noreply.github.com> Co-authored-by: Gabriel Augendre <gabriel@augendre.info> Co-authored-by: Cat Core <34719527+arthurbambou@users.noreply.github.com> Co-authored-by: Hugo Haas <hugoh@hugoh.net> Co-authored-by: Baptiste <32563450+BapRx@users.noreply.github.com> Co-authored-by: bbx0 <39773919+bbx0@users.noreply.github.com> Co-authored-by: Sourajyoti Basak <wiz28@protonmail.com>
2023-01-29 19:19:27 +00:00
.map_err(|err| SkipStep(format!("Failed to get hostname: {err}")).into())
.map(|output| output.stdout.trim().to_owned())
}