Debug logging for transaction state and all clippy warnings fixed
This commit is contained in:
parent
a2a8d0651a
commit
e25d807bd7
63 changed files with 570 additions and 462 deletions
|
@ -49,7 +49,7 @@ use pacwrap_core::{
|
|||
|
||||
use crate::error::AgentError;
|
||||
|
||||
const AGENT_PARAMS: &'static str = "/mnt/agent_params";
|
||||
const AGENT_PARAMS: &str = "/mnt/agent_params";
|
||||
|
||||
pub fn transact() -> Result<()> {
|
||||
let mut header = ByteBuffer::with_capacity(7).read();
|
||||
|
@ -96,10 +96,10 @@ fn conduct_transaction(config: &Global, handle: &mut TransactionHandle, agent: T
|
|||
let files = agent.files();
|
||||
|
||||
if let Err(error) = handle.alpm_mut().trans_init(flags.1.unwrap()) {
|
||||
err!(SyncError::InitializationFailure(error.to_string().into()))?
|
||||
err!(SyncError::InitializationFailure(error.to_string()))?
|
||||
}
|
||||
|
||||
handle.ignore();
|
||||
handle.ignore(&mut None);
|
||||
|
||||
if let TransactionType::Upgrade(upgrade, downgrade, _) = action {
|
||||
if upgrade {
|
||||
|
|
|
@ -79,12 +79,6 @@ impl Display for ConfigError {
|
|||
}
|
||||
}
|
||||
|
||||
impl From<ConfigError> for String {
|
||||
fn from(value: ConfigError) -> Self {
|
||||
value.into()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn provide_handle(instance: &str) -> Result<ContainerHandle> {
|
||||
let vars = ContainerVariables::new(instance);
|
||||
|
||||
|
@ -115,13 +109,11 @@ pub fn provide_new_handle<'a>(instance: &'a str, instype: ContainerType, deps: V
|
|||
Ok(handle.create())
|
||||
}
|
||||
Err(err) => {
|
||||
if let Ok(err) = err.downcast::<ConfigError>() {
|
||||
if let ConfigError::ConfigNotFound(..) = err {
|
||||
let cfg = Container::new(instype, deps, vec![]);
|
||||
let vars = ContainerVariables::new(instance);
|
||||
if let Ok(ConfigError::ConfigNotFound(..)) = err.downcast::<ConfigError>() {
|
||||
let cfg = Container::new(instype, deps, vec![]);
|
||||
let vars = ContainerVariables::new(instance);
|
||||
|
||||
return Ok(ContainerHandle::new(cfg, vars).create());
|
||||
}
|
||||
return Ok(ContainerHandle::new(cfg, vars).create());
|
||||
}
|
||||
|
||||
Err(err)?
|
||||
|
|
|
@ -35,6 +35,12 @@ pub struct ContainerCache<'a> {
|
|||
instances: IndexMap<&'a str, ContainerHandle<'a>>,
|
||||
}
|
||||
|
||||
impl<'a> Default for ContainerCache<'a> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> ContainerCache<'a> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
|
@ -43,37 +49,40 @@ impl<'a> ContainerCache<'a> {
|
|||
}
|
||||
|
||||
pub fn add(&mut self, ins: &'a str, instype: ContainerType, deps: Vec<&'a str>) -> Result<()> {
|
||||
if let Some(_) = self.instances.get(ins) {
|
||||
if self.instances.get(ins).is_some() {
|
||||
err!(ConfigError::AlreadyExists(ins.into()))?
|
||||
}
|
||||
|
||||
for dep in deps.iter() {
|
||||
if let None = self.instances.get(dep) {
|
||||
if self.instances.get(dep).is_none() {
|
||||
err!(ErrorKind::DependencyNotFound((*dep).into(), ins.into()))?
|
||||
}
|
||||
}
|
||||
|
||||
Ok(self.register(ins, provide_new_handle(ins, instype, deps.iter().map(|a| (*a).into()).collect())?))
|
||||
self.register(ins, provide_new_handle(ins, instype, deps.to_vec())?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn replace(&mut self, ins: &'a str, handle: ContainerHandle<'a>) -> Result<()> {
|
||||
Ok(self.register(ins, handle.default_vars()))
|
||||
self.register(ins, handle.default_vars());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn add_handle(&mut self, ins: &'a str, handle: ContainerHandle<'a>) -> Result<()> {
|
||||
if let Some(_) = self.instances.get(ins) {
|
||||
if self.instances.get(ins).is_some() {
|
||||
err!(ConfigError::AlreadyExists(ins.into()))?
|
||||
}
|
||||
|
||||
Ok(self.register(ins, handle.default_vars()))
|
||||
self.register(ins, handle.default_vars());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn map(&mut self, ins: &'a str) -> Result<()> {
|
||||
if let Some(_) = self.instances.get(ins) {
|
||||
if self.instances.get(ins).is_some() {
|
||||
err!(ConfigError::AlreadyExists(ins.to_owned()))?
|
||||
}
|
||||
|
||||
Ok(self.register(
|
||||
self.register(
|
||||
ins,
|
||||
match provide_handle(ins) {
|
||||
Ok(ins) => ins,
|
||||
|
@ -82,7 +91,8 @@ impl<'a> ContainerCache<'a> {
|
|||
return Ok(());
|
||||
}
|
||||
},
|
||||
))
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn register(&mut self, ins: &'a str, handle: ContainerHandle<'a>) {
|
||||
|
@ -97,7 +107,7 @@ impl<'a> ContainerCache<'a> {
|
|||
self.instances.iter().map(|a| a.1).collect()
|
||||
}
|
||||
|
||||
pub fn filter_target(&'a self, target: &Vec<&'a str>, filter: Vec<ContainerType>) -> Vec<&'a str> {
|
||||
pub fn filter_target(&'a self, target: &[&'a str], filter: Vec<ContainerType>) -> Vec<&'a str> {
|
||||
self.instances
|
||||
.iter()
|
||||
.filter(|a| target.contains(a.0) && (filter.contains(a.1.metadata().container_type()) || filter.is_empty()))
|
||||
|
@ -105,7 +115,7 @@ impl<'a> ContainerCache<'a> {
|
|||
.collect()
|
||||
}
|
||||
|
||||
pub fn filter_target_handle(&'a self, target: &Vec<&'a str>, filter: Vec<ContainerType>) -> Vec<&'a ContainerHandle<'a>> {
|
||||
pub fn filter_target_handle(&'a self, target: &[&'a str], filter: Vec<ContainerType>) -> Vec<&'a ContainerHandle<'a>> {
|
||||
self.instances
|
||||
.iter()
|
||||
.filter(|a| target.contains(a.0) && (filter.contains(a.1.metadata().container_type()) || filter.is_empty()))
|
||||
|
@ -152,11 +162,11 @@ impl<'a> ContainerCache<'a> {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn populate_from<'a>(vec: &Vec<&'a str>) -> Result<ContainerCache<'a>> {
|
||||
pub fn populate_from<'a>(vec: &[&'a str]) -> Result<ContainerCache<'a>> {
|
||||
let mut cache = ContainerCache::new();
|
||||
|
||||
for name in vec {
|
||||
cache.map(&name)?;
|
||||
cache.map(name)?;
|
||||
}
|
||||
|
||||
Ok(cache)
|
||||
|
@ -166,7 +176,7 @@ pub fn populate_config_from<'a>(vec: &Vec<&'a str>) -> Result<ContainerCache<'a>
|
|||
let mut cache = ContainerCache::new();
|
||||
|
||||
for name in vec {
|
||||
cache.add_handle(&name, handle(ContainerVariables::new(name))?)?;
|
||||
cache.add_handle(name, handle(ContainerVariables::new(name))?)?;
|
||||
}
|
||||
|
||||
Ok(cache)
|
||||
|
@ -178,14 +188,14 @@ pub fn populate<'a>() -> Result<ContainerCache<'a>> {
|
|||
.prepend_io(|| CONTAINER_DIR.to_string())?
|
||||
.filter_map(StdResult::ok)
|
||||
.filter(|e| e.metadata().is_ok_and(|f| f.is_dir() || f.is_symlink()))
|
||||
.filter_map(|e| e.file_name().to_str().and_then(|f| Some(f.to_string().leak() as &'a str)))
|
||||
.collect(),
|
||||
.filter_map(|e| e.file_name().to_str().map(|f| f.to_string().leak() as &'a str))
|
||||
.collect::<Vec<&str>>(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn populate_config<'a>() -> Result<ContainerCache<'a>> {
|
||||
populate_config_from(
|
||||
&read_dir(&format!("{}/container", *CONFIG_DIR))
|
||||
&read_dir(format!("{}/container", *CONFIG_DIR))
|
||||
.prepend_io(|| format!("{}/container", *CONFIG_DIR))?
|
||||
.filter_map(StdResult::ok)
|
||||
.filter(|e| e.metadata().is_ok_and(|f| f.is_file() && !f.is_symlink()))
|
||||
|
|
|
@ -59,7 +59,7 @@ impl<'a> TryFrom<ContainerShadow<'a>> for Container<'a> {
|
|||
type Error = &'static str;
|
||||
|
||||
fn try_from(value: ContainerShadow<'a>) -> StdResult<Self, Self::Error> {
|
||||
if value.metadata.container_type == ContainerType::Base && value.metadata.dependencies.len() > 0 {
|
||||
if value.metadata.container_type == ContainerType::Base && !value.metadata.dependencies.is_empty() {
|
||||
Err("Dependencies cannot be specified for Base type containers.")?;
|
||||
}
|
||||
|
||||
|
@ -168,6 +168,12 @@ pub struct ContainerRuntime {
|
|||
dbus: Vec<Box<dyn Dbus>>,
|
||||
}
|
||||
|
||||
impl Default for ContainerRuntime {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ContainerRuntime {
|
||||
pub fn new() -> Self {
|
||||
let default_fs: [Box<dyn Filesystem>; 2] = [Box::new(Root {}), Box::new(Home {})];
|
||||
|
|
|
@ -36,8 +36,8 @@ pub struct Dir {
|
|||
#[typetag::serde(name = "dir")]
|
||||
impl Filesystem for Dir {
|
||||
fn check(&self, _vars: &ContainerVariables) -> Result<(), BindError> {
|
||||
if self.path.len() == 0 {
|
||||
Err(BindError::Fail(format!("Path not specified.")))?
|
||||
if self.path.is_empty() {
|
||||
Err(BindError::Fail("Path not specified.".into()))?
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
|
|
@ -36,7 +36,7 @@ pub struct Home;
|
|||
impl Filesystem for Home {
|
||||
fn check(&self, vars: &ContainerVariables) -> Result<(), BindError> {
|
||||
if !Path::new(vars.home()).exists() {
|
||||
Err(BindError::Fail(format!("Specified home directory not found.")))?
|
||||
Err(BindError::Fail("Specified home directory not found.".into()))?
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
@ -48,18 +48,16 @@ struct Mount {
|
|||
#[typetag::serde(name = "to_home")]
|
||||
impl Filesystem for ToHome {
|
||||
fn check(&self, _vars: &ContainerVariables) -> Result<(), BindError> {
|
||||
if self.mounts.len() == 0 {
|
||||
Err(BindError::Warn(format!("Mount volumes undeclared.")))?
|
||||
if self.mounts.is_empty() {
|
||||
Err(BindError::Warn("Mount volumes undeclared.".into()))?
|
||||
}
|
||||
|
||||
for m in self.mounts.iter() {
|
||||
if m.path.len() == 0 {
|
||||
Err(BindError::Warn(format!("Mount volumes undeclared.")))?
|
||||
if m.path.is_empty() {
|
||||
Err(BindError::Warn("Mount volumes undeclared.".into()))?
|
||||
}
|
||||
|
||||
if let Err(e) = check_mount(&m.permission, &m.path) {
|
||||
return Err(e);
|
||||
}
|
||||
check_mount(&m.permission, &m.path)?
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
|
|
@ -47,18 +47,16 @@ struct Mount {
|
|||
#[typetag::serde(name = "to_root")]
|
||||
impl Filesystem for ToRoot {
|
||||
fn check(&self, _vars: &ContainerVariables) -> Result<(), BindError> {
|
||||
if self.mounts.len() == 0 {
|
||||
Err(BindError::Warn(format!("Mount volumes undeclared.")))?
|
||||
if self.mounts.is_empty() {
|
||||
Err(BindError::Warn("Mount volumes undeclared.".into()))?
|
||||
}
|
||||
|
||||
for m in self.mounts.iter() {
|
||||
if m.path.len() == 0 {
|
||||
Err(BindError::Warn(format!("Mount volumes undeclared.")))?
|
||||
if m.path.is_empty() {
|
||||
Err(BindError::Warn("Mount volumes undeclared.".into()))?
|
||||
}
|
||||
|
||||
if let Err(e) = check_mount(&m.permission, &m.path) {
|
||||
return Err(e);
|
||||
}
|
||||
check_mount(&m.permission, &m.path)?
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
@ -95,7 +93,7 @@ fn check_mount(permission: &String, path: &String) -> Result<(), BindError> {
|
|||
}
|
||||
|
||||
if !Path::new(path).exists() {
|
||||
Err(BindError::Fail(format!("Source path not found.")))?
|
||||
Err(BindError::Fail("Source path not found.".into()))?
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
|
|
@ -181,6 +181,12 @@ impl AlpmConfiguration {
|
|||
}
|
||||
}
|
||||
|
||||
impl Default for Global {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Global {
|
||||
fn load() -> Self {
|
||||
match config() {
|
||||
|
@ -205,7 +211,7 @@ impl Global {
|
|||
}
|
||||
|
||||
pub fn save(&self) -> Result<()> {
|
||||
save(&self, &*CONFIG_FILE)
|
||||
save(&self, &CONFIG_FILE)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -28,8 +28,8 @@ use crate::{
|
|||
Result,
|
||||
};
|
||||
|
||||
static REPO_CONF_DEFAULT: &'static str = include_str!(env!("PACWRAP_DIST_REPO_CONF"));
|
||||
static PACWRAP_CONF_DEFAULT: &'static str = include_str!(env!("PACWRAP_DIST_CONF"));
|
||||
static REPO_CONF_DEFAULT: &str = include_str!(env!("PACWRAP_DIST_REPO_CONF"));
|
||||
static PACWRAP_CONF_DEFAULT: &str = include_str!(env!("PACWRAP_DIST_CONF"));
|
||||
|
||||
pub struct DirectoryLayout {
|
||||
dirs: Vec<&'static str>,
|
||||
|
@ -80,7 +80,7 @@ fn initialize_file(location: &str, contents: &str) -> Result<()> {
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
let mut f = match File::create(&location) {
|
||||
let mut f = match File::create(location) {
|
||||
Ok(f) => f,
|
||||
Err(error) => err!(ErrorKind::IOError(location.into(), error.kind()))?,
|
||||
};
|
||||
|
|
|
@ -59,8 +59,8 @@ impl Permission for Display {
|
|||
Err(e) => Err(e)?,
|
||||
}
|
||||
|
||||
if let None = bound {
|
||||
Err(Fail(format!("Expected environment variables were not found.")))
|
||||
if bound.is_none() {
|
||||
Err(Fail("Expected environment variables were not found.".into()))
|
||||
} else {
|
||||
Ok(bound)
|
||||
}
|
||||
|
@ -87,7 +87,7 @@ fn validate_wayland_socket() -> Result<Option<Condition>, PermError> {
|
|||
Err(Fail(format!("Wayland socket '{}' not found.", &*WAYLAND_SOCKET)))?
|
||||
}
|
||||
|
||||
if !check_socket(&*WAYLAND_SOCKET) {
|
||||
if !check_socket(&WAYLAND_SOCKET) {
|
||||
Err(Fail(format!("'{}' is not a valid UNIX socket.", &*WAYLAND_SOCKET)))?
|
||||
}
|
||||
|
||||
|
@ -103,7 +103,7 @@ fn validate_xorg_socket() -> Result<Option<Condition>, PermError> {
|
|||
let xorg_socket = format!("/tmp/.X11-unix/X{}", display[1]);
|
||||
|
||||
if XAUTHORITY.is_empty() {
|
||||
Err(Fail(format!("XAUTHORITY environment variable unspecified.")))?
|
||||
Err(Fail("XAUTHORITY environment variable unspecified.".into()))?
|
||||
}
|
||||
|
||||
if !Path::new(*XAUTHORITY).exists() {
|
||||
|
|
|
@ -54,7 +54,7 @@ impl Permission for Environment {
|
|||
}
|
||||
|
||||
fn register(&self, args: &mut ExecutionArgs) {
|
||||
if self.var != "" {
|
||||
if !self.var.is_empty() {
|
||||
let set = env_var(&self.var, &self.set);
|
||||
args.env(&self.var, &set);
|
||||
}
|
||||
|
@ -71,11 +71,11 @@ impl Permission for Environment {
|
|||
}
|
||||
|
||||
fn env_var(var: &String, set: &String) -> String {
|
||||
if set != "" {
|
||||
if !set.is_empty() {
|
||||
return set.to_owned();
|
||||
}
|
||||
|
||||
match env::var(&var) {
|
||||
match env::var(var) {
|
||||
Ok(env) => env,
|
||||
Err(_) => {
|
||||
print_warning(&format!("Environment variable {} is unset.", var));
|
||||
|
|
|
@ -44,16 +44,16 @@ impl Permission for Graphics {
|
|||
fn check(&self) -> Result<Option<Condition>, PermError> {
|
||||
let gpu_dev = populate_dev().map_err(|f| {
|
||||
f.error();
|
||||
Fail(format!("No graphics devices are available."))
|
||||
Fail("No graphics devices are available.".into())
|
||||
})?;
|
||||
let nvidia = !gpu_dev.iter().filter(|a| a.contains("nvidia")).collect::<Vec<_>>().is_empty();
|
||||
|
||||
if GPU_DEV.get_or_init(|| gpu_dev).is_empty() {
|
||||
Err(Fail(format!("No graphics devices are available.")))?
|
||||
Err(Fail("No graphics devices are available.".into()))?
|
||||
}
|
||||
|
||||
if nvidia && !Path::new("/sys/module/nvidia").exists() {
|
||||
return Ok(Some(SuccessWarn(format!("'/sys/module/nvidia': Device module unavailable."))));
|
||||
return Ok(Some(SuccessWarn("'/sys/module/nvidia': Device module unavailable.".into())));
|
||||
}
|
||||
|
||||
Ok(Some(Success))
|
||||
|
@ -79,8 +79,7 @@ impl Permission for Graphics {
|
|||
|
||||
fn populate_dev() -> Result<Vec<String>, Error> {
|
||||
Ok(read_dir("/dev/")
|
||||
.prepend_io(|| format!("/dev"))?
|
||||
.into_iter()
|
||||
.prepend_io(|| "/dev".into())?
|
||||
.filter_map(|f| {
|
||||
f.map_or_else(
|
||||
|_| None,
|
||||
|
|
|
@ -41,7 +41,7 @@ struct Pipewire {
|
|||
impl Permission for Pipewire {
|
||||
fn check(&self) -> Result<Option<Condition>, PermError> {
|
||||
if !Path::new(&self.socket).exists() {
|
||||
Err(Warn(format!("Pipewire socket not found.")))?
|
||||
Err(Warn("Pipewire socket not found.".to_string()))?
|
||||
}
|
||||
|
||||
if !check_socket(&self.socket) {
|
||||
|
|
|
@ -41,7 +41,7 @@ struct Pulseaudio {
|
|||
impl Permission for Pulseaudio {
|
||||
fn check(&self) -> Result<Option<Condition>, PermError> {
|
||||
if !Path::new(&self.socket).exists() {
|
||||
Err(Warn(format!("Pulseaudio socket not found.")))?
|
||||
Err(Warn("Pulseaudio socket not found.".into()))?
|
||||
}
|
||||
|
||||
if !check_socket(&self.socket) {
|
||||
|
|
|
@ -33,7 +33,7 @@ use crate::{
|
|||
utils::print_warning,
|
||||
};
|
||||
|
||||
pub fn register_filesystems(per: &Vec<Box<dyn Filesystem>>, vars: &ContainerVariables, args: &mut ExecutionArgs) -> Result<()> {
|
||||
pub fn register_filesystems(per: &[Box<dyn Filesystem>], vars: &ContainerVariables, args: &mut ExecutionArgs) -> Result<()> {
|
||||
for p in per.iter() {
|
||||
match p.check(vars) {
|
||||
Ok(_) => p.register(args, vars),
|
||||
|
@ -47,7 +47,7 @@ pub fn register_filesystems(per: &Vec<Box<dyn Filesystem>>, vars: &ContainerVari
|
|||
Ok(())
|
||||
}
|
||||
|
||||
pub fn register_permissions(per: &Vec<Box<dyn Permission>>, args: &mut ExecutionArgs) -> Result<()> {
|
||||
pub fn register_permissions(per: &[Box<dyn Permission>], args: &mut ExecutionArgs) -> Result<()> {
|
||||
for p in per.iter() {
|
||||
match p.check() {
|
||||
Ok(condition) => match condition {
|
||||
|
@ -70,7 +70,7 @@ pub fn register_permissions(per: &Vec<Box<dyn Permission>>, args: &mut Execution
|
|||
Ok(())
|
||||
}
|
||||
|
||||
pub fn register_dbus(per: &Vec<Box<dyn Dbus>>, args: &mut ExecutionArgs) -> Result<()> {
|
||||
pub fn register_dbus(per: &[Box<dyn Dbus>], args: &mut ExecutionArgs) -> Result<()> {
|
||||
for p in per.iter() {
|
||||
p.register(args);
|
||||
}
|
||||
|
|
|
@ -41,10 +41,10 @@ impl ContainerVariables {
|
|||
Self {
|
||||
home: var("PACWRAP_HOME").unwrap_or(format!("{}/home/{ins}", *DATA_DIR)),
|
||||
root: var("PACWRAP_ROOT").unwrap_or(format!("{}/root/{ins}", *DATA_DIR)),
|
||||
config: format!("{}/container/{ins}.yml", *CONFIG_DIR).into(),
|
||||
pacman_gnupg: format!("{}/pacman/gnupg", *DATA_DIR).into(),
|
||||
pacman_cache: format!("{}/pkg", *CACHE_DIR).into(),
|
||||
home_mount: format!("/home/{ins}").into(),
|
||||
config: format!("{}/container/{ins}.yml", *CONFIG_DIR),
|
||||
pacman_gnupg: format!("{}/pacman/gnupg", *DATA_DIR),
|
||||
pacman_cache: format!("{}/pkg", *CACHE_DIR),
|
||||
home_mount: format!("/home/{ins}"),
|
||||
user: ins.into(),
|
||||
instance: ins.into(),
|
||||
}
|
||||
|
|
|
@ -100,6 +100,7 @@ impl Error {
|
|||
eprintln!("{}warning:{} {}", *BOLD_YELLOW, *RESET, self.kind);
|
||||
}
|
||||
|
||||
#[allow(clippy::borrowed_box)]
|
||||
pub fn kind(&self) -> &Box<dyn ErrorTrait> {
|
||||
&self.kind
|
||||
}
|
||||
|
@ -157,9 +158,3 @@ where
|
|||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&Box<dyn ErrorTrait>> for String {
|
||||
fn from(value: &Box<dyn ErrorTrait>) -> Self {
|
||||
value.into()
|
||||
}
|
||||
}
|
||||
|
|
|
@ -164,8 +164,8 @@ pub fn fakeroot_container(exec_type: ExecutionType, trap: Option<fn(i32)>, ins:
|
|||
|
||||
if let ContainerType::Slice = ins.metadata().container_type() {
|
||||
process.arg("--dir").arg("/root")
|
||||
.arg("--ro-bind").arg(&format!("{}/bin", *DIST_IMG)).arg("/mnt/fs/bin")
|
||||
.arg("--ro-bind").arg(&format!("{}/lib", *DIST_IMG)).arg("/mnt/fs/lib64")
|
||||
.arg("--ro-bind").arg(format!("{}/bin", *DIST_IMG)).arg("/mnt/fs/bin")
|
||||
.arg("--ro-bind").arg(format!("{}/lib", *DIST_IMG)).arg("/mnt/fs/lib64")
|
||||
.arg("--dir").arg("/mnt/fs/root") ;
|
||||
|
||||
if arguments[0] == "ash" {
|
||||
|
@ -216,8 +216,8 @@ pub fn transaction_agent(ins: &ContainerHandle, params: TransactionParameters, m
|
|||
match Command::new(BWRAP_EXECUTABLE).env_clear()
|
||||
.arg("--bind").arg(ins.vars().root()).arg("/mnt/fs")
|
||||
.arg("--symlink").arg("/mnt/fs/usr").arg("/usr")
|
||||
.arg("--ro-bind").arg(&format!("{}/bin", *DIST_IMG)).arg("/bin")
|
||||
.arg("--ro-bind").arg(&format!("{}/lib", *DIST_IMG)).arg("/lib64")
|
||||
.arg("--ro-bind").arg(format!("{}/bin", *DIST_IMG)).arg("/bin")
|
||||
.arg("--ro-bind").arg(format!("{}/lib", *DIST_IMG)).arg("/lib64")
|
||||
.arg("--symlink").arg("lib").arg("/lib")
|
||||
.arg("--ro-bind").arg("/etc/resolv.conf").arg("/etc/resolv.conf")
|
||||
.arg("--ro-bind").arg("/etc/localtime").arg("/etc/localtime")
|
||||
|
|
|
@ -65,6 +65,12 @@ impl Argument {
|
|||
}
|
||||
}
|
||||
|
||||
impl Default for ExecutionArgs {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecutionArgs {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
|
@ -122,9 +128,7 @@ impl ExecutionArgs {
|
|||
}
|
||||
|
||||
pub fn arguments(&self) -> Vec<&str> {
|
||||
let mut vec = Vec::new();
|
||||
|
||||
vec.reserve((self.sys.len() + self.bind.len() + self.env.len()) * 4);
|
||||
let mut vec = Vec::with_capacity((self.sys.len() + self.bind.len() + self.env.len()) * 4);
|
||||
|
||||
for values in self.bind.iter().chain(self.sys.iter()).chain(self.env.iter()) {
|
||||
vec.extend(values.to_vec());
|
||||
|
@ -143,7 +147,7 @@ impl Debug for ExecutionArgs {
|
|||
writeln!(fmter, "sys: {:?}", self.sys)?;
|
||||
}
|
||||
|
||||
if self.dbus.len() > 0 {
|
||||
if !self.dbus.is_empty() {
|
||||
writeln!(fmter, "dbus: {:?}", self.dbus)?;
|
||||
}
|
||||
|
||||
|
|
|
@ -28,8 +28,8 @@ use crate::{
|
|||
Result,
|
||||
};
|
||||
|
||||
pub fn check_path(ins: &ContainerHandle, args: &Vec<&str>, path: Vec<&str>) -> Result<()> {
|
||||
if let (Slice, true) = (ins.metadata().container_type(), args.len() > 0) {
|
||||
pub fn check_path(ins: &ContainerHandle, args: &[&str], path: Vec<&str>) -> Result<()> {
|
||||
if let (Slice, true) = (ins.metadata().container_type(), !args.is_empty()) {
|
||||
if dest_exists(*DIST_IMG, "/bin", args[0])? {
|
||||
return Ok(());
|
||||
}
|
||||
|
@ -37,7 +37,7 @@ pub fn check_path(ins: &ContainerHandle, args: &Vec<&str>, path: Vec<&str>) -> R
|
|||
err!(ExecutionError::ExecutableUnavailable(args[0].into()))?
|
||||
}
|
||||
|
||||
if args.len() == 0 {
|
||||
if args.is_empty() {
|
||||
err!(ExecutionError::RuntimeArguments)?
|
||||
}
|
||||
|
||||
|
@ -82,7 +82,7 @@ fn dest_exists(root: &str, dir: &str, exec: &str) -> Result<bool> {
|
|||
}
|
||||
|
||||
fn obtain_path(path: &Path, exec: &str) -> Result<PathBuf> {
|
||||
match Path::canonicalize(&path) {
|
||||
match Path::canonicalize(path) {
|
||||
Ok(path) => Ok(path),
|
||||
Err(err) => match err.kind() {
|
||||
std::io::ErrorKind::NotFound => Ok(path.to_path_buf()),
|
||||
|
|
|
@ -52,7 +52,7 @@ static ENOSYS: Action = Action::Errno(libc::ENOSYS);
|
|||
static PERSONALITY: u64 = if cfg!(target_pointer_width = "64") {
|
||||
0x0000
|
||||
} else {
|
||||
0x0000 | 0x0800000
|
||||
0x0800000
|
||||
};
|
||||
|
||||
/*
|
||||
|
@ -66,7 +66,7 @@ static PERSONALITY: u64 = if cfg!(target_pointer_width = "64") {
|
|||
*
|
||||
* This encumbers a great responsibility upon the user when exercising this great power.
|
||||
*/
|
||||
static RULES: [(FilterType, &'static str, Action); 28] = [
|
||||
static RULES: [(FilterType, &str, Action); 28] = [
|
||||
(Standard, "syslog", EPERM),
|
||||
(Standard, "uselib", EPERM),
|
||||
(Standard, "acct", EPERM),
|
||||
|
@ -96,7 +96,7 @@ static RULES: [(FilterType, &'static str, Action); 28] = [
|
|||
(Namespaces, "pivot_root", EPERM),
|
||||
(Namespaces, "chroot", EPERM),
|
||||
];
|
||||
static RULES_COND: [(FilterType, &'static str, Action, Compare); 4] = [
|
||||
static RULES_COND: [(FilterType, &str, Action, Compare); 4] = [
|
||||
(TtyControl, "ioctl", EPERM, Compare::new(1, Op::MaskedEqual(libc::TIOCLINUX), libc::TIOCLINUX)),
|
||||
(TtyControl, "ioctl", EPERM, Compare::new(1, Op::MaskedEqual(libc::TIOCSTI), libc::TIOCSTI)),
|
||||
(Namespaces, "clone", EPERM, Compare::new(0, Op::MaskedEqual(libc::CLONE_NEWUSER as u64), libc::CLONE_NEWUSER as u64)),
|
||||
|
|
|
@ -171,7 +171,7 @@ fn serialize<T: for<'de> Serialize>(input: &T, file: &PipeWriter) -> Result<()>
|
|||
pub fn handle_process(name: &'static str, result: std::result::Result<Child, std::io::Error>) -> Result<()> {
|
||||
match result {
|
||||
Ok(child) => wait_on_process(name, child),
|
||||
Err(error) => err!(ErrorKind::ProcessInitFailure(name.into(), error.kind())),
|
||||
Err(error) => err!(ErrorKind::ProcessInitFailure(name, error.kind())),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -54,6 +54,12 @@ pub struct Lock {
|
|||
time: i64,
|
||||
}
|
||||
|
||||
impl Default for Lock {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Lock {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
|
@ -90,7 +96,7 @@ impl Lock {
|
|||
}
|
||||
|
||||
pub fn unlock(&self) -> Result<()> {
|
||||
Ok(remove_file(self.lock).prepend(|| format!("Failed to remove lock file '{}'", self.lock))?)
|
||||
remove_file(self.lock).prepend(|| format!("Failed to remove lock file '{}'", self.lock))
|
||||
}
|
||||
|
||||
pub fn exists(&self) -> bool {
|
||||
|
|
|
@ -22,11 +22,20 @@ use std::{
|
|||
fs::{File, OpenOptions},
|
||||
io::Write,
|
||||
path::Path,
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
use time::{format_description::FormatItem, macros::format_description, OffsetDateTime, UtcOffset};
|
||||
|
||||
use crate::{constants::LOG_LOCATION, err, impl_error, Error, ErrorKind, ErrorTrait, Result};
|
||||
use crate::{
|
||||
constants::{LOG_LOCATION, UNIX_TIMESTAMP},
|
||||
err,
|
||||
impl_error,
|
||||
Error,
|
||||
ErrorKind,
|
||||
ErrorTrait,
|
||||
Result,
|
||||
};
|
||||
|
||||
const DATE_FORMAT: &[FormatItem<'static>] =
|
||||
format_description!("[year]-[month]-[day]T[hour]:[minute]:[second][offset_hour][offset_minute]");
|
||||
|
@ -47,6 +56,7 @@ impl Display for LoggerError {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq)]
|
||||
pub enum Level {
|
||||
Info,
|
||||
Warn,
|
||||
|
@ -65,6 +75,22 @@ impl Level {
|
|||
Self::Debug => "DEBUG",
|
||||
}
|
||||
}
|
||||
|
||||
fn verbosity(&self) -> i8 {
|
||||
self.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&Level> for i8 {
|
||||
fn from(val: &Level) -> Self {
|
||||
match val {
|
||||
Level::Info => 0,
|
||||
Level::Warn => 1,
|
||||
Level::Error => 2,
|
||||
Level::Fatal => 3,
|
||||
Level::Debug => 4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<i8> for Level {
|
||||
|
@ -87,6 +113,7 @@ impl Display for Level {
|
|||
}
|
||||
|
||||
pub struct Logger {
|
||||
verbosity: i8,
|
||||
file: Option<File>,
|
||||
module: &'static str,
|
||||
offset: UtcOffset,
|
||||
|
@ -106,6 +133,7 @@ impl Logger {
|
|||
let ofs = UtcOffset::parse(ofs.as_str(), UTC_OFFSET).unwrap();
|
||||
|
||||
Self {
|
||||
verbosity: 3,
|
||||
file: None,
|
||||
module: module_name,
|
||||
offset: ofs,
|
||||
|
@ -114,17 +142,24 @@ impl Logger {
|
|||
|
||||
pub fn init(mut self) -> Result<Self> {
|
||||
let path = Path::new(*LOG_LOCATION);
|
||||
let file = OpenOptions::new().create(true).write(true).append(true).truncate(false).open(path);
|
||||
let file = OpenOptions::new().create(true).append(true).truncate(false).open(path);
|
||||
|
||||
self.file = Some(match file {
|
||||
Ok(file) => file,
|
||||
Err(error) => err!(ErrorKind::IOError(LOG_LOCATION.to_string(), error.kind()))?,
|
||||
});
|
||||
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
pub fn set_verbosity(&mut self, verbosity: i8) {
|
||||
self.verbosity = verbosity
|
||||
}
|
||||
|
||||
pub fn log(&mut self, level: Level, msg: &str) -> Result<()> {
|
||||
if level.verbosity() > self.verbosity {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
/*
|
||||
* Then attempt to update it here.
|
||||
*
|
||||
|
@ -137,12 +172,20 @@ impl Logger {
|
|||
}
|
||||
|
||||
let time: OffsetDateTime = OffsetDateTime::now_utc().to_offset(self.offset);
|
||||
let write = match self.file.as_mut() {
|
||||
Some(file) =>
|
||||
file.write(format!("[{}] [{}] [{}] {}\n", time.format(DATE_FORMAT).unwrap(), self.module, level, msg).as_bytes()),
|
||||
None => err!(LoggerError::Uninitialized)?,
|
||||
let write = if let Some(file) = self.file.as_mut() {
|
||||
file.write(format!("[{}] [{}] [{}] {}\n", time.format(DATE_FORMAT).unwrap(), self.module, level, msg).as_bytes())
|
||||
} else {
|
||||
err!(LoggerError::Uninitialized)?
|
||||
};
|
||||
|
||||
if let Level::Debug = level {
|
||||
let now = SystemTime::now().duration_since(UNIX_EPOCH).expect("SystemTime now");
|
||||
let time = now.as_secs() as usize - *UNIX_TIMESTAMP as usize;
|
||||
let nano = now.subsec_nanos().to_string();
|
||||
|
||||
eprintln!("[{}.{:.6}] [{}] {}", time, nano, self.module, msg);
|
||||
}
|
||||
|
||||
match write {
|
||||
Ok(_) => Ok(()),
|
||||
Err(error) => err!(ErrorKind::IOError(LOG_LOCATION.to_string(), error.kind())),
|
||||
|
|
|
@ -62,11 +62,11 @@ impl ProcessList {
|
|||
self.list.iter().map(|a| a.1).collect()
|
||||
}
|
||||
|
||||
pub fn filter_by_target(&self, targets: &Vec<&str>) -> Vec<&Process> {
|
||||
pub fn filter_by_target(&self, targets: &[&str]) -> Vec<&Process> {
|
||||
self.list.iter().filter(|a| targets.contains(&a.1.instance())).map(|a| a.1).collect()
|
||||
}
|
||||
|
||||
pub fn filter_by_pid(&self, targets: &Vec<i32>) -> Vec<&Process> {
|
||||
pub fn filter_by_pid(&self, targets: &[i32]) -> Vec<&Process> {
|
||||
self.list.iter().filter(|a| targets.contains(&a.1.pid())).map(|a| a.1).collect()
|
||||
}
|
||||
|
||||
|
@ -102,7 +102,7 @@ impl Process {
|
|||
|
||||
pub fn exec(&self) -> &str {
|
||||
match self.cmd[0].char_indices().filter(|c| c.1 == '/').last() {
|
||||
Some((index, ..)) => &self.cmd[0].split_at(index + 1).1,
|
||||
Some((index, ..)) => self.cmd[0].split_at(index + 1).1,
|
||||
None => &self.cmd[0],
|
||||
}
|
||||
}
|
||||
|
@ -140,7 +140,7 @@ impl Process {
|
|||
|
||||
impl ProcStat {
|
||||
fn new(pid: i32) -> Option<Self> {
|
||||
let stat = match File::open(&format!("/proc/{}/stat", pid)) {
|
||||
let stat = match File::open(format!("/proc/{}/stat", pid)) {
|
||||
Ok(file) => file,
|
||||
Err(_) => return None,
|
||||
};
|
||||
|
@ -196,7 +196,7 @@ pub fn list<'a>(cache: &'a ContainerCache<'a>) -> Result<ProcessList, Error> {
|
|||
match groups.get_mut(&ins) {
|
||||
Some(vec) => vec.push(pid),
|
||||
None => {
|
||||
if let None = cache.get_instance_option(&ins) {
|
||||
if cache.get_instance_option(&ins).is_none() {
|
||||
print_warning(&format!("Container {ins} doesn't exist."));
|
||||
}
|
||||
|
||||
|
@ -229,7 +229,7 @@ fn procfs_meta(e: DirEntry) -> Result<Option<(OsString, u64)>, Box<dyn StdError>
|
|||
}
|
||||
|
||||
fn cmdlist(pid: i32) -> Option<Vec<String>> {
|
||||
let list = match File::open(&format!("/proc/{}/cmdline", pid)) {
|
||||
let list = match File::open(format!("/proc/{}/cmdline", pid)) {
|
||||
Ok(file) => file,
|
||||
Err(_) => return None,
|
||||
};
|
||||
|
@ -271,7 +271,7 @@ fn cmdlist(pid: i32) -> Option<Vec<String>> {
|
|||
Some(cmdlist)
|
||||
}
|
||||
|
||||
fn qualify_process(cmdlist: &Vec<String>, parent_id: i32, map: &IndexMap<i32, Process>) -> Option<(String, u32, bool)> {
|
||||
fn qualify_process(cmdlist: &[String], parent_id: i32, map: &IndexMap<i32, Process>) -> Option<(String, u32, bool)> {
|
||||
if let Some(some) = map.get(&parent_id) {
|
||||
return Some((some.instance().into(), some.depth + 1, some.fork()));
|
||||
} else if cmdlist[0] == "pacwrap" {
|
||||
|
@ -279,7 +279,7 @@ fn qualify_process(cmdlist: &Vec<String>, parent_id: i32, map: &IndexMap<i32, Pr
|
|||
if cmdlist[idx].contains("-E") || cmdlist[idx].contains("run") || cmdlist[idx].contains("shell") {
|
||||
let mut pos = 0;
|
||||
|
||||
for idx in 1 .. cmdlist.len() {
|
||||
for (idx, ..) in cmdlist.iter().enumerate().skip(1) {
|
||||
if cmdlist[idx].starts_with("-") || cmdlist[idx] == "run" || cmdlist[idx] == "shell" {
|
||||
continue;
|
||||
}
|
||||
|
@ -299,7 +299,7 @@ fn qualify_process(cmdlist: &Vec<String>, parent_id: i32, map: &IndexMap<i32, Pr
|
|||
}
|
||||
} else if cmdlist[0] == "bwrap" {
|
||||
for idx in 0 .. cmdlist.len() {
|
||||
if !cmdlist[idx].contains(&"--ro-bind") && !cmdlist[idx].contains("--bind") {
|
||||
if !cmdlist[idx].contains("--ro-bind") && !cmdlist[idx].contains("--bind") {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
|
@ -133,12 +133,6 @@ impl From<&Error> for SyncError {
|
|||
}
|
||||
}
|
||||
|
||||
impl From<SyncError> for String {
|
||||
fn from(error: SyncError) -> Self {
|
||||
error.into()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct AlpmRepository {
|
||||
name: String,
|
||||
|
@ -197,7 +191,7 @@ fn alpm_log_callback(level: LogLevel, msg: &str, counter: &mut usize) {
|
|||
|
||||
pub fn instantiate_alpm_agent(config: &Global, remotes: &AlpmConfigData, transflags: &TransactionFlags) -> Alpm {
|
||||
let mut handle = Alpm::new("/mnt/fs", "/mnt/fs/var/lib/pacman/").expect("Unable to acquire ALPM handle");
|
||||
let hook_dirs = vec!["/mnt/fs/usr/share/libalpm/hooks/", "/mnt/fs/etc/pacman.d/hooks/"];
|
||||
let hook_dirs = ["/mnt/fs/usr/share/libalpm/hooks/", "/mnt/fs/etc/pacman.d/hooks/"];
|
||||
let debug = transflags.intersects(TransactionFlags::DEBUG);
|
||||
let disable_sandbox = config.alpm().disable_sandbox() || transflags.intersects(TransactionFlags::NO_ALPM_SANDBOX);
|
||||
|
||||
|
@ -213,7 +207,7 @@ pub fn instantiate_alpm_agent(config: &Global, remotes: &AlpmConfigData, transfl
|
|||
handle.set_logfile("/mnt/share/pacwrap.log").expect("set logfile");
|
||||
handle.set_hookdirs(hook_dirs.iter()).expect("set hookdirs");
|
||||
handle.set_gpgdir("/mnt/share/gnupg").expect("set gpgdir");
|
||||
handle.set_cachedirs(vec!["/mnt/share/cache"].iter()).expect("set cachedirs");
|
||||
handle.set_cachedirs(["/mnt/share/cache"].iter()).expect("set cachedirs");
|
||||
handle.set_parallel_downloads(config.alpm().parallel_downloads());
|
||||
handle.set_disable_dl_timeout(config.alpm().download_timeout());
|
||||
handle.set_check_space(false);
|
||||
|
@ -222,7 +216,7 @@ pub fn instantiate_alpm_agent(config: &Global, remotes: &AlpmConfigData, transfl
|
|||
}
|
||||
|
||||
pub fn instantiate_alpm(inshandle: &ContainerHandle, transflags: &TransactionFlags) -> Alpm {
|
||||
alpm_handle(inshandle.vars(), &*DEFAULT_ALPM_CONF, transflags, format!("{}/var/lib/pacman/", inshandle.vars().root()))
|
||||
alpm_handle(inshandle.vars(), &DEFAULT_ALPM_CONF, transflags, format!("{}/var/lib/pacman/", inshandle.vars().root()))
|
||||
}
|
||||
|
||||
fn alpm_handle(insvars: &ContainerVariables, remotes: &AlpmConfigData, transflags: &TransactionFlags, db_path: String) -> Alpm {
|
||||
|
@ -241,7 +235,7 @@ fn alpm_handle(insvars: &ContainerVariables, remotes: &AlpmConfigData, transflag
|
|||
|
||||
handle.set_logfile(format!("{}/pacwrap.log", *DATA_DIR)).expect("set logfile");
|
||||
handle.set_gpgdir(format!("{}/pacman/gnupg", *DATA_DIR)).expect("set gpgdir");
|
||||
handle.set_cachedirs(vec![format!("{}/pkg", *CACHE_DIR)].iter()).expect("set cachedirs");
|
||||
handle.set_cachedirs([format!("{}/pkg", *CACHE_DIR)].iter()).expect("set cachedirs");
|
||||
handle.set_parallel_downloads(CONFIG.alpm().parallel_downloads());
|
||||
handle.set_disable_dl_timeout(CONFIG.alpm().download_timeout());
|
||||
handle.set_check_space(CONFIG.alpm().check_space());
|
||||
|
@ -318,7 +312,7 @@ fn synchronize_database(ag: &mut TransactionAggregator, force: bool) -> Result<(
|
|||
};
|
||||
let flags = ag.flags();
|
||||
let db_path = format!("{}/pacman/", *DATA_DIR);
|
||||
let mut handle = alpm_handle(&handle.vars(), &*DEFAULT_ALPM_CONF, flags, db_path);
|
||||
let mut handle = alpm_handle(handle.vars(), &DEFAULT_ALPM_CONF, flags, db_path);
|
||||
|
||||
ag.lock()?.assert()?;
|
||||
println!("{} {}Synchronizing package databases...{}", *BAR_GREEN, *BOLD, *RESET);
|
||||
|
@ -353,17 +347,16 @@ fn signature(sigs: &Vec<String>, default: SigLevel) -> SigLevel {
|
|||
let mut sig = SigLevel::empty();
|
||||
|
||||
for level in sigs {
|
||||
sig = sig
|
||||
| match level.as_ref() {
|
||||
"TrustAll" => SigLevel::DATABASE_UNKNOWN_OK | SigLevel::PACKAGE_UNKNOWN_OK,
|
||||
"DatabaseTrustAll" => SigLevel::DATABASE_UNKNOWN_OK | SigLevel::PACKAGE_MARGINAL_OK,
|
||||
"PackageTrustAll" => SigLevel::PACKAGE_UNKNOWN_OK | SigLevel::DATABASE_MARGINAL_OK,
|
||||
"DatabaseRequired" | "DatabaseTrustedOnly" => SigLevel::DATABASE,
|
||||
"PackageRequired" | "Required" => SigLevel::PACKAGE,
|
||||
"PackageOptional" => SigLevel::PACKAGE_OPTIONAL,
|
||||
"DatabaseOptional" => SigLevel::DATABASE_OPTIONAL,
|
||||
_ => SigLevel::empty(),
|
||||
}
|
||||
sig |= match level.as_ref() {
|
||||
"TrustAll" => SigLevel::DATABASE_UNKNOWN_OK | SigLevel::PACKAGE_UNKNOWN_OK,
|
||||
"DatabaseTrustAll" => SigLevel::DATABASE_UNKNOWN_OK | SigLevel::PACKAGE_MARGINAL_OK,
|
||||
"PackageTrustAll" => SigLevel::PACKAGE_UNKNOWN_OK | SigLevel::DATABASE_MARGINAL_OK,
|
||||
"DatabaseRequired" | "DatabaseTrustedOnly" => SigLevel::DATABASE,
|
||||
"PackageRequired" | "Required" => SigLevel::PACKAGE,
|
||||
"PackageOptional" => SigLevel::PACKAGE_OPTIONAL,
|
||||
"DatabaseOptional" => SigLevel::DATABASE_OPTIONAL,
|
||||
_ => SigLevel::empty(),
|
||||
}
|
||||
}
|
||||
|
||||
sig
|
||||
|
|
|
@ -55,6 +55,12 @@ pub struct DownloadEvent {
|
|||
style: Option<ProgressStyle>,
|
||||
}
|
||||
|
||||
impl Default for DownloadEvent {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl DownloadEvent {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
|
@ -147,8 +153,8 @@ impl DownloadEvent {
|
|||
fn insert(&mut self, file: &str) {
|
||||
let pb = match self.total_bar.as_mut() {
|
||||
Some(total) => match self.condensed {
|
||||
true => self.progress.insert_after(&total, ProgressBar::new(0)),
|
||||
false => self.progress.insert_before(&total, ProgressBar::new(0)),
|
||||
true => self.progress.insert_after(total, ProgressBar::new(0)),
|
||||
false => self.progress.insert_before(total, ProgressBar::new(0)),
|
||||
},
|
||||
None => self.progress.add(ProgressBar::new(0)),
|
||||
};
|
||||
|
|
|
@ -41,6 +41,12 @@ pub struct ProgressEvent {
|
|||
bars: HashMap<String, ProgressBar>,
|
||||
}
|
||||
|
||||
impl Default for ProgressEvent {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ProgressEvent {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
|
@ -113,7 +119,7 @@ pub fn simple(kind: Event, pkgname: &str, _: i32, howmany: usize, current: usize
|
|||
}
|
||||
}
|
||||
|
||||
if let None = this.current.as_deref() {
|
||||
if this.current.as_deref().is_none() {
|
||||
let pos = current + this.offset;
|
||||
let total = howmany + this.offset;
|
||||
let progress_name: String = name(kind, pkgname);
|
||||
|
@ -165,11 +171,11 @@ fn name(progress: Event, pkgname: &str) -> String {
|
|||
Event::RemoveStart => format!("Removing {}", pkgname),
|
||||
Event::DowngradeStart => format!("Downgrading {}", pkgname),
|
||||
Event::ReinstallStart => format!("Reinstalling {}", pkgname),
|
||||
Event::KeyringStart => format!("Loading keyring"),
|
||||
Event::IntegrityStart => format!("Checking integrity"),
|
||||
Event::LoadStart => format!("Loading packages"),
|
||||
Event::ConflictsStart => format!("Checking conflicts"),
|
||||
Event::DiskspaceStart => format!("Checking available diskspace"),
|
||||
Event::KeyringStart => "Loading keyring".into(),
|
||||
Event::IntegrityStart => "Checking integrity".into(),
|
||||
Event::LoadStart => "Loading packages".into(),
|
||||
Event::ConflictsStart => "Checking conflicts".into(),
|
||||
Event::DiskspaceStart => "Checking available diskspace".into(),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -30,7 +30,7 @@ pub fn callback(question: AnyQuestion, _: &mut ()) {
|
|||
let pkg_b = x.conflict().package2().name();
|
||||
let prompt_string = format!("Conflict between {pkg_a} and {pkg_b}; Remove {pkg_b}?");
|
||||
|
||||
if let Ok(_) = prompt("->", prompt_string, false) {
|
||||
if prompt("->", prompt_string, false) {
|
||||
x.set_remove(true);
|
||||
}
|
||||
}
|
||||
|
@ -39,7 +39,7 @@ pub fn callback(question: AnyQuestion, _: &mut ()) {
|
|||
let new = x.newpkg().name();
|
||||
let prompt_string = format!("Replace package {old} with {new}?");
|
||||
|
||||
if let Ok(_) = prompt("->", prompt_string, false) {
|
||||
if prompt("->", prompt_string, false) {
|
||||
x.set_replace(true);
|
||||
}
|
||||
}
|
||||
|
@ -49,7 +49,7 @@ pub fn callback(question: AnyQuestion, _: &mut ()) {
|
|||
let reason = x.reason();
|
||||
let prompt_string = format!("'{filename}': {reason}. Remove package?");
|
||||
|
||||
if let Ok(_) = prompt("::", prompt_string, true) {
|
||||
if prompt("::", prompt_string, true) {
|
||||
x.set_remove(true);
|
||||
}
|
||||
}
|
||||
|
@ -58,7 +58,7 @@ pub fn callback(question: AnyQuestion, _: &mut ()) {
|
|||
let name = x.uid();
|
||||
let prompt_string = format!("Import key {fingerprint}, \"{name}\" to keyring?");
|
||||
|
||||
if let Ok(_) = prompt("->", prompt_string, true) {
|
||||
if prompt("->", prompt_string, true) {
|
||||
x.set_import(true);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -63,6 +63,12 @@ enum TableColumns {
|
|||
Version,
|
||||
}
|
||||
|
||||
impl Default for Summary {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Summary {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
|
@ -233,7 +239,7 @@ impl Summary {
|
|||
pkglist.push_str(&format!("{}-{}{}{} ", pkg.0, *DIM, ver, *RESET));
|
||||
}
|
||||
|
||||
write!(fmt, "{}\n", pkglist)?;
|
||||
writeln!(fmt, "{}", pkglist)?;
|
||||
self.footer(fmt)
|
||||
}
|
||||
|
||||
|
|
|
@ -244,11 +244,11 @@ impl<'a> FilesystemSync<'a> {
|
|||
self.linked.insert(ins);
|
||||
}
|
||||
SyncMessage::SaveState(container, fs_state) => {
|
||||
if let Some(_) = self.state_map.get(&container) {
|
||||
if self.state_map.contains_key(&container) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if fs_state.files.len() == 0 {
|
||||
if fs_state.files.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
@ -295,7 +295,7 @@ impl<'a> FilesystemSync<'a> {
|
|||
err!(FilesystemSyncError::MagicMismatch(path.into(), magic))?
|
||||
} else if version != VERSION {
|
||||
let state = match version {
|
||||
1 => deserialize::<File, FileSystemState>(&instance, file)?,
|
||||
1 => deserialize::<File, FileSystemState>(instance, file)?,
|
||||
_ => err!(FilesystemSyncError::UnsupportedVersion(path.into(), version))?,
|
||||
};
|
||||
|
||||
|
@ -309,7 +309,7 @@ impl<'a> FilesystemSync<'a> {
|
|||
}
|
||||
|
||||
let buf_reader = BufReader::new(state_buffer.as_slice());
|
||||
let state = deserialize::<BufReader<&[u8]>, FileSystemState>(&instance, buf_reader)?;
|
||||
let state = deserialize::<BufReader<&[u8]>, FileSystemState>(instance, buf_reader)?;
|
||||
|
||||
self.state_map_prev.insert(instance.clone(), Some(state.clone()));
|
||||
Ok(Some(state))
|
||||
|
@ -330,14 +330,15 @@ impl<'a> FilesystemSync<'a> {
|
|||
err.warn();
|
||||
}
|
||||
|
||||
Ok(self.pool()?.spawn(move || {
|
||||
self.pool()?.spawn(move || {
|
||||
let mut state = FileSystemState::new();
|
||||
|
||||
obtain_state(root, &mut state);
|
||||
|
||||
tx.send(SyncMessage::SaveState(instance.clone(), state)).unwrap();
|
||||
tx.send(SyncMessage::LinkComplete(instance)).unwrap();
|
||||
}))
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn link_instance(&mut self, handle: &ContainerHandle, tx: Sender<SyncMessage>) -> Result<()> {
|
||||
|
@ -349,8 +350,8 @@ impl<'a> FilesystemSync<'a> {
|
|||
|
||||
for dep in handle.metadata().dependencies() {
|
||||
let dephandle = self.cache.get_instance(dep).unwrap();
|
||||
let state = self.state_map.get(dep).map_or_else(|| FileSystemState::new(), |s| s.clone());
|
||||
let dep = &Arc::from(dep.as_ref());
|
||||
let state = self.state_map.get(dep).map_or_else(FileSystemState::new, |s| s.clone());
|
||||
let dep = &Arc::from(dep);
|
||||
let prev_state = match self.previous_state(dep) {
|
||||
Ok(state) => state,
|
||||
Err(err) => {
|
||||
|
@ -363,7 +364,7 @@ impl<'a> FilesystemSync<'a> {
|
|||
map.push((dephandle.vars().root().into(), state));
|
||||
}
|
||||
|
||||
Ok(self.pool()?.spawn(move || {
|
||||
self.pool()?.spawn(move || {
|
||||
let state = filesystem_state(state, map);
|
||||
let state_prev = previous_state(prev);
|
||||
|
||||
|
@ -372,15 +373,16 @@ impl<'a> FilesystemSync<'a> {
|
|||
link_filesystem(&state, &root);
|
||||
|
||||
tx.send(SyncMessage::LinkComplete(instance)).unwrap();
|
||||
}))
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pool(&self) -> Result<&ThreadPool> {
|
||||
self.pool.as_ref().map_or_else(|| err!(ErrorKind::ThreadPoolUninitialized), |p| Ok(p))
|
||||
self.pool.as_ref().map_or_else(|| err!(ErrorKind::ThreadPoolUninitialized), Ok)
|
||||
}
|
||||
|
||||
fn lock(&self) -> Result<&Lock> {
|
||||
self.lock.map_or_else(|| err!(LockError::NotAcquired), |f| Ok(f))
|
||||
self.lock.map_or_else(|| err!(LockError::NotAcquired), Ok)
|
||||
}
|
||||
|
||||
fn signal(&mut self) -> Result<()> {
|
||||
|
@ -399,7 +401,7 @@ impl<'a> FilesystemSync<'a> {
|
|||
|
||||
fn discard_state(&mut self) -> Result<()> {
|
||||
for (data, ..) in &self.state_map {
|
||||
remove_file(&format!("{}/state/{data}.dat.new", *DATA_DIR)).ok();
|
||||
remove_file(format!("{}/state/{data}.dat.new", *DATA_DIR)).ok();
|
||||
}
|
||||
|
||||
self.lock()?.unlock()?;
|
||||
|
@ -546,18 +548,18 @@ fn serialize(path: &str, ds: FileSystemState) -> Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
fn decode_state<'a, R: Read>(mut stream: R) -> IOResult<(Vec<u8>, bool)> {
|
||||
fn decode_state<R: Read>(mut stream: R) -> IOResult<(Vec<u8>, bool)> {
|
||||
let mut header_buffer = ByteBuffer::with_capacity(10).read();
|
||||
|
||||
stream.read_exact(&mut header_buffer.as_slice_mut())?;
|
||||
stream.read_exact(header_buffer.as_slice_mut())?;
|
||||
|
||||
let hash_length = header_buffer.read_le_16();
|
||||
let state_length = header_buffer.read_le_64();
|
||||
|
||||
if state_length == 0 {
|
||||
Err(IOError::new(IOErrorKind::InvalidInput, format!("Data length provided is zero")))?;
|
||||
Err(IOError::new(IOErrorKind::InvalidInput, "Data length provided is zero".to_string()))?;
|
||||
} else if hash_length != 32 {
|
||||
Err(IOError::new(IOErrorKind::InvalidInput, format!("Hash length provided is invalid.")))?;
|
||||
Err(IOError::new(IOErrorKind::InvalidInput, "Hash length provided is invalid.".to_string()))?;
|
||||
} else if state_length >= BYTE_LIMIT {
|
||||
Err(IOError::new(IOErrorKind::InvalidInput, format!("Data length exceeded maximum {state_length} >= {BYTE_LIMIT}")))?;
|
||||
}
|
||||
|
@ -584,8 +586,8 @@ fn encode_state(path: &str, state_data: Vec<u8>, hash: Vec<u8>) -> IOResult<u64>
|
|||
header.write_le_32(VERSION);
|
||||
header.write_le_16(hash.len() as u16);
|
||||
header.write_le_64(state_data.len() as u64);
|
||||
output.write(header.as_slice())?;
|
||||
output.write(&hash)?;
|
||||
output.write_all(header.as_slice())?;
|
||||
output.write_all(&hash)?;
|
||||
copy(&mut state_data.as_slice(), &mut Encoder::new(output, 3)?.auto_finish())
|
||||
}
|
||||
|
||||
|
@ -605,10 +607,8 @@ fn check(instance: &str) -> Result<bool> {
|
|||
fn previous_state(map: Vec<Option<FileSystemState>>) -> FileSystemState {
|
||||
let mut state = FileSystemState::new();
|
||||
|
||||
for ins_state in map {
|
||||
if let Some(ins_state) = ins_state {
|
||||
state.files.extend(ins_state.files);
|
||||
}
|
||||
for ins_state in map.into_iter().flatten() {
|
||||
state.files.extend(ins_state.files);
|
||||
}
|
||||
|
||||
state
|
||||
|
@ -616,7 +616,7 @@ fn previous_state(map: Vec<Option<FileSystemState>>) -> FileSystemState {
|
|||
|
||||
fn filesystem_state(mut state: FileSystemState, map: Vec<(Arc<str>, FileSystemState)>) -> FileSystemState {
|
||||
for ins_state in map {
|
||||
if ins_state.1.files.len() == 0 {
|
||||
if ins_state.1.files.is_empty() {
|
||||
obtain_state(ins_state.0, &mut state);
|
||||
} else {
|
||||
state.files.extend(ins_state.1.files);
|
||||
|
@ -634,7 +634,7 @@ fn obtain_state(root: Arc<str>, state: &mut FileSystemState) {
|
|||
let src: Arc<str> = entry.path().to_str().unwrap().into();
|
||||
let src_tr: Arc<str> = src.split_at(len).1.into();
|
||||
|
||||
if let Some(_) = state.files.get(&src_tr) {
|
||||
if state.files.get(&src_tr).is_some() {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
@ -674,7 +674,7 @@ fn delete_files(state: &FileSystemState, state_res: &FileSystemState, root: &str
|
|||
state_res.files.par_iter().filter(|a| a.1 .0 != FileType::Directory).for_each(|file| {
|
||||
let _ = tx_clone;
|
||||
|
||||
if let None = state.files.get(file.0) {
|
||||
if state.files.get(file.0).is_none() {
|
||||
let path_str = &format!("{}{}", root, file.0);
|
||||
let path = Path::new(path_str);
|
||||
|
||||
|
@ -701,7 +701,7 @@ fn delete_directories(state: &FileSystemState, state_res: &FileSystemState, root
|
|||
state_res.files.par_iter().for_each(move |file| {
|
||||
let _ = tx_clone;
|
||||
|
||||
if let None = state.files.get(file.0) {
|
||||
if state.files.get(file.0).is_none() {
|
||||
let path: &str = &format!("{}{}", root, file.0);
|
||||
let path = Path::new(path);
|
||||
|
||||
|
@ -739,7 +739,7 @@ fn create_soft_link(src: &str, dest: &str) -> IOResult<()> {
|
|||
|
||||
if let Some(path) = dest_path.parent() {
|
||||
if !path.exists() {
|
||||
create_dir_all(&path)?;
|
||||
create_dir_all(path)?;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -757,16 +757,16 @@ pub fn create_hard_link(src: &str, dest: &str) -> IOResult<()> {
|
|||
if !dest_path.exists() {
|
||||
if let Some(path) = dest_path.parent() {
|
||||
if !path.exists() {
|
||||
remove_symlink(&path)?;
|
||||
create_dir_all(&path)?;
|
||||
remove_symlink(path)?;
|
||||
create_dir_all(path)?;
|
||||
}
|
||||
}
|
||||
|
||||
remove_symlink(dest_path)?;
|
||||
hard_link(src_path, dest_path)
|
||||
} else {
|
||||
let meta_dest = metadata(&dest_path)?;
|
||||
let meta_src = metadata(&src_path)?;
|
||||
let meta_dest = metadata(dest_path)?;
|
||||
let meta_src = metadata(src_path)?;
|
||||
|
||||
if meta_src.ino() != meta_dest.ino() {
|
||||
if meta_dest.is_dir() {
|
||||
|
@ -784,7 +784,7 @@ pub fn create_hard_link(src: &str, dest: &str) -> IOResult<()> {
|
|||
|
||||
#[inline]
|
||||
fn remove_symlink(path: &Path) -> IOResult<()> {
|
||||
if let Ok(_) = fs::read_link(path) {
|
||||
if fs::read_link(path).is_ok() {
|
||||
remove_file(path)?
|
||||
}
|
||||
|
||||
|
@ -798,7 +798,7 @@ fn queue_status(sync_type: &SyncType, queue: &HashSet<&str>, compare: &str, max_
|
|||
let mut strs: Vec<&str> = Vec::new();
|
||||
|
||||
for contrast in queue {
|
||||
let contrast: &str = contrast.as_ref();
|
||||
let contrast: &str = contrast;
|
||||
|
||||
if compare == contrast {
|
||||
continue;
|
||||
|
@ -820,7 +820,7 @@ fn queue_status(sync_type: &SyncType, queue: &HashSet<&str>, compare: &str, max_
|
|||
if idx > 0 {
|
||||
string.push_str(format!(", {str}").as_str());
|
||||
} else {
|
||||
string.push_str(format!("{str}").as_str());
|
||||
string.push_str(str.to_string().as_str());
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -828,7 +828,7 @@ fn queue_status(sync_type: &SyncType, queue: &HashSet<&str>, compare: &str, max_
|
|||
string.push_str(format!(", and {diff} more..").as_str());
|
||||
}
|
||||
|
||||
if string.len() == 0 {
|
||||
if string.is_empty() {
|
||||
string.push_str(sync_type.progress());
|
||||
}
|
||||
|
||||
|
|
|
@ -61,11 +61,11 @@ impl<'a> DependencyResolver<'a> {
|
|||
let mut synchronize: Vec<&'a str> = Vec::new();
|
||||
|
||||
for pkg in packages {
|
||||
if let Some(_) = self.resolved.get(pkg) {
|
||||
if self.resolved.contains(*pkg) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(_) = self.ignored.get(*pkg) {
|
||||
if self.ignored.contains(*pkg) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
@ -76,26 +76,23 @@ impl<'a> DependencyResolver<'a> {
|
|||
pkg.depends()
|
||||
.iter()
|
||||
.filter_map(|p| match self.handle.get_local_package(p.name()) {
|
||||
None => match self.handle.get_package(p.name()) {
|
||||
Some(dep) => Some(dep.name()),
|
||||
None => None,
|
||||
},
|
||||
None => self.handle.get_package(p.name()).map(|dep| dep.name()),
|
||||
Some(_) => None,
|
||||
})
|
||||
.collect::<Vec<&str>>(),
|
||||
);
|
||||
|
||||
if self.depth > 0 {
|
||||
self.keys.push(pkg.name().into());
|
||||
self.keys.push(pkg.name());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if synchronize.len() > 0 {
|
||||
if !synchronize.is_empty() {
|
||||
self.check_depth()?;
|
||||
self.enumerate(&synchronize)
|
||||
} else {
|
||||
let keys = if self.keys.len() > 0 {
|
||||
let keys = if !self.keys.is_empty() {
|
||||
Some(self.keys.iter().map(|a| (*a).into()).collect())
|
||||
} else {
|
||||
None
|
||||
|
|
|
@ -64,11 +64,11 @@ impl<'a> LocalDependencyResolver<'a> {
|
|||
let mut synchronize: Vec<&'a str> = Vec::new();
|
||||
|
||||
for pkg in packages {
|
||||
if let Some(_) = self.resolved.get(pkg) {
|
||||
if self.resolved.contains(*pkg) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(_) = self.ignored.get(*pkg) {
|
||||
if self.ignored.contains(*pkg) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
@ -79,7 +79,7 @@ impl<'a> LocalDependencyResolver<'a> {
|
|||
continue;
|
||||
}
|
||||
|
||||
if let Some(_) = pkg.required_by().iter().find(|p| self.resolved.get(p).is_none()) {
|
||||
if pkg.required_by().iter().any(|p| self.resolved.contains(p)) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
@ -98,14 +98,14 @@ impl<'a> LocalDependencyResolver<'a> {
|
|||
}
|
||||
|
||||
for package in self.handle.localdb().pkgs() {
|
||||
if let Some(_) = package.depends().iter().find_map(|d| self.resolved.get(d.name())) {
|
||||
if package.depends().iter().find_map(|d| self.resolved.get(d.name())).is_some() {
|
||||
synchronize.push(package.name());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if synchronize.len() > 0 && self.flags.0 {
|
||||
if !synchronize.is_empty() && self.flags.0 {
|
||||
self.check_depth()?;
|
||||
self.enumerate(&synchronize)
|
||||
} else {
|
||||
|
|
|
@ -46,8 +46,8 @@ use self::SchemaStatus::*;
|
|||
static SCHEMA_STATE: OnceLock<SchemaState> = OnceLock::new();
|
||||
|
||||
const MAGIC_NUMBER: u32 = 659933704;
|
||||
const ARCHIVE_PATH: &'static str = env!("PACWRAP_DIST_FS");
|
||||
const SCHEMA_META: &'static str = ".container_schema";
|
||||
const ARCHIVE_PATH: &str = env!("PACWRAP_DIST_FS");
|
||||
const SCHEMA_META: &str = ".container_schema";
|
||||
|
||||
pub enum SchemaStatus {
|
||||
UpToDate,
|
||||
|
@ -62,7 +62,7 @@ enum NodeType {
|
|||
Other,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct SchemaState {
|
||||
magic: u32,
|
||||
major: u32,
|
||||
|
@ -71,7 +71,7 @@ pub struct SchemaState {
|
|||
files: IndexSet<SchemaNode>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Eq, PartialEq)]
|
||||
#[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]
|
||||
pub struct SchemaNode {
|
||||
node_path: String,
|
||||
node_type: NodeType,
|
||||
|
@ -160,7 +160,7 @@ pub fn extract(inshandle: &ContainerHandle, old_schema: &Option<SchemaState>) ->
|
|||
pub fn version(inshandle: &ContainerHandle) -> Result<SchemaStatus> {
|
||||
let mut header = ByteBuffer::with_capacity(16).read();
|
||||
let schema: &str = &format!("{}/{}", inshandle.vars().root(), SCHEMA_META);
|
||||
let mut file = match File::open(&schema) {
|
||||
let mut file = match File::open(schema) {
|
||||
Ok(file) => file,
|
||||
Err(err) => {
|
||||
if err.kind() == std::io::ErrorKind::NotFound {
|
||||
|
@ -223,7 +223,7 @@ fn deserialize() -> Result<SchemaState> {
|
|||
let schema = env!("PACWRAP_DIST_META");
|
||||
let file = File::open(schema).prepend_io(|| schema.into())?;
|
||||
|
||||
Ok(bincode::deserialize_from::<&File, SchemaState>(&file).prepend(|| format!("Schema deserialization failure '{schema}'"))?)
|
||||
bincode::deserialize_from::<&File, SchemaState>(&file).prepend(|| format!("Schema deserialization failure '{schema}'"))
|
||||
}
|
||||
|
||||
fn access_archive<'a>(path: &str) -> Result<Archive<Decoder<'a, BufReader<File>>>> {
|
||||
|
@ -232,16 +232,16 @@ fn access_archive<'a>(path: &str) -> Result<Archive<Decoder<'a, BufReader<File>>
|
|||
|
||||
fn remove_file(path: &str) -> Result<()> {
|
||||
if Path::new(&format!("{}.pacnew", &path)).exists() {
|
||||
fs::remove_file(&path).prepend(|| format!("Failed to remove '{path}'"))?;
|
||||
fs::remove_file(path).prepend(|| format!("Failed to remove '{path}'"))?;
|
||||
} else {
|
||||
fs::copy(&format!("{}.pacnew", &path), &path).prepend(|| format!("Failed to copy '{path}'"))?;
|
||||
fs::copy(format!("{}.pacnew", &path), path).prepend(|| format!("Failed to copy '{path}'"))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove_symlink(path: &str) -> Result<()> {
|
||||
if let Ok(_) = fs::read_link(path) {
|
||||
if fs::read_link(path).is_ok() {
|
||||
fs::remove_file(path).prepend(|| format!("Failed to remove symlink '{path}'"))?;
|
||||
}
|
||||
|
||||
|
@ -253,7 +253,7 @@ fn remove_directory(path: &str) -> Result<()> {
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
fs::remove_dir(&path).prepend(|| format!("Failed to remove directory '{path}'"))
|
||||
fs::remove_dir(path).prepend(|| format!("Failed to remove directory '{path}'"))
|
||||
}
|
||||
|
||||
fn is_directory_occupied(path: &str) -> Result<bool> {
|
||||
|
|
|
@ -29,6 +29,7 @@ use crate::{
|
|||
config::{ContainerHandle, Global, CONFIG},
|
||||
constants::{ARROW_CYAN, BAR_CYAN, BOLD, BOLD_GREEN, BOLD_YELLOW, RESET},
|
||||
err,
|
||||
log::{Level, Logger},
|
||||
sync::{
|
||||
resolver::DependencyResolver,
|
||||
resolver_local::LocalDependencyResolver,
|
||||
|
@ -53,6 +54,7 @@ mod uptodate;
|
|||
pub type Result<T> = crate::Result<T>;
|
||||
pub static MAGIC_NUMBER: u32 = 663445956;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum TransactionState {
|
||||
Prepare,
|
||||
UpdateSchema(Option<SchemaState>),
|
||||
|
@ -72,7 +74,7 @@ pub enum TransactionType {
|
|||
Remove(bool, bool, bool),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Copy, Clone)]
|
||||
#[derive(Serialize, Deserialize, Copy, Clone, Debug)]
|
||||
pub enum TransactionMode {
|
||||
Foreign,
|
||||
Local,
|
||||
|
@ -94,6 +96,7 @@ pub trait Transaction {
|
|||
handle: &mut TransactionHandle,
|
||||
inshandle: &ContainerHandle,
|
||||
) -> Result<TransactionState>;
|
||||
fn debug(&self) -> String;
|
||||
}
|
||||
|
||||
bitflags! {
|
||||
|
@ -222,7 +225,7 @@ impl TransactionType {
|
|||
progress.set_message(format!("{}{}{} ", *BOLD, message, *RESET));
|
||||
progress.tick();
|
||||
} else {
|
||||
println!("{} {}{}{}", *BAR_CYAN, *BOLD, message, *RESET);
|
||||
println!("{}{}{}{}", *BAR_CYAN, *BOLD, message, *RESET);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -284,11 +287,11 @@ impl<'a> TransactionHandle<'a> {
|
|||
};
|
||||
|
||||
for pkg in alpm.localdb().pkgs() {
|
||||
if let Some(_) = ignored.get(pkg.name()) {
|
||||
if ignored.get(pkg.name()).is_some() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(_) = pkg.sync_new_version(alpm.syncdbs()) {
|
||||
if pkg.sync_new_version(alpm.syncdbs()).is_some() {
|
||||
return Required;
|
||||
}
|
||||
}
|
||||
|
@ -323,38 +326,50 @@ impl<'a> TransactionHandle<'a> {
|
|||
.extend(self.meta.foreign_pkgs.iter().map(|p| p.to_owned().into()).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
pub fn ignore(&mut self) {
|
||||
pub fn ignore(&mut self, log: &mut Option<&mut Logger>) {
|
||||
let alpm = self.alpm.as_mut().unwrap();
|
||||
let config = match self.config {
|
||||
Some(config) => config,
|
||||
None => &*CONFIG,
|
||||
};
|
||||
let ignore = match self.meta.mode {
|
||||
Foreign => &self.meta.resident_pkgs,
|
||||
Local => &self.meta.foreign_pkgs,
|
||||
};
|
||||
let unignore = match self.meta.mode {
|
||||
let local = match self.meta.mode {
|
||||
Local => &self.meta.resident_pkgs,
|
||||
Foreign => &self.meta.foreign_pkgs,
|
||||
};
|
||||
let foreign = match self.meta.mode {
|
||||
Foreign => &self.meta.resident_pkgs,
|
||||
Local => &self.meta.foreign_pkgs,
|
||||
};
|
||||
|
||||
for pkg in unignore {
|
||||
alpm.remove_ignorepkg(pkg.as_bytes()).unwrap();
|
||||
for pkg in local {
|
||||
alpm.remove_ignorepkg(pkg.as_bytes()).expect("Unable to unignore local pkg");
|
||||
|
||||
if let Some(logger) = log {
|
||||
logger.log(Level::Debug, &format!("Local package {}", pkg)).expect("logger");
|
||||
}
|
||||
}
|
||||
|
||||
for pkg in ignore {
|
||||
alpm.add_ignorepkg(pkg.as_bytes()).unwrap();
|
||||
for pkg in foreign {
|
||||
alpm.add_ignorepkg(pkg.as_bytes()).expect("Unable to ignore foreign pkg");
|
||||
|
||||
if let Some(logger) = log {
|
||||
logger.log(Level::Debug, &format!("Foreign package {}", pkg)).expect("logger");
|
||||
}
|
||||
}
|
||||
|
||||
for pkg in config.alpm().ignored() {
|
||||
alpm.add_ignorepkg(pkg.as_bytes()).unwrap();
|
||||
alpm.add_ignorepkg(pkg.as_bytes()).expect("Unable to ignore package");
|
||||
|
||||
if let Some(logger) = log {
|
||||
logger.log(Level::Debug, &format!("Ignored package {}", pkg)).expect("logger");
|
||||
}
|
||||
}
|
||||
|
||||
for package in alpm
|
||||
.localdb()
|
||||
.pkgs()
|
||||
.iter()
|
||||
.filter(|a| !ignore.contains(a.name()) && config.alpm().ignored().contains(&a.name()))
|
||||
.filter(|a| !foreign.contains(a.name()) && config.alpm().ignored().contains(&a.name()))
|
||||
{
|
||||
let new = match package.sync_new_version(alpm.syncdbs()) {
|
||||
Some(new) => {
|
||||
|
@ -391,7 +406,7 @@ impl<'a> TransactionHandle<'a> {
|
|||
};
|
||||
|
||||
if let Local = self.meta.mode {
|
||||
let upstream = queue.iter().map(|a| *a).find(|a| ignored.contains(*a));
|
||||
let upstream = queue.iter().copied().find(|a| ignored.contains(*a));
|
||||
let forced = flags.contains(TransactionFlags::FORCE_DATABASE);
|
||||
|
||||
if let (false, Some(upstream)) = (forced, upstream) {
|
||||
|
@ -403,59 +418,56 @@ impl<'a> TransactionHandle<'a> {
|
|||
Remove(..) => {
|
||||
if let Some(not_installed) = queue
|
||||
.iter()
|
||||
.map(|a| *a)
|
||||
.copied()
|
||||
.find(|a| !ignored.contains(*a) && alpm.get_local_package(a).is_none())
|
||||
{
|
||||
err!(SyncError::TargetNotInstalled(not_installed.into()))?
|
||||
}
|
||||
|
||||
for pkg in LocalDependencyResolver::new(alpm, &ignored, trans_type)
|
||||
for pkg in LocalDependencyResolver::new(alpm, ignored, trans_type)
|
||||
.enumerate(&queue)?
|
||||
.iter()
|
||||
.filter(|a| !self.meta.held_pkgs.contains(a.name()))
|
||||
.map(|a| *a)
|
||||
.copied()
|
||||
.collect::<Vec<&Package>>()
|
||||
{
|
||||
if !self.agent && !ignored.contains(pkg.name()) && config.alpm().held().contains(&pkg.name()) {
|
||||
if let Err(_) =
|
||||
prompt("::", format!("Target package {}{}{} is held. Remove it?", *BOLD, pkg.name(), *RESET), false)
|
||||
{
|
||||
self.meta.held_pkgs.insert(pkg.name().into());
|
||||
continue;
|
||||
}
|
||||
if !self.agent
|
||||
&& !ignored.contains(pkg.name())
|
||||
&& config.alpm().held().contains(&pkg.name())
|
||||
&& !prompt("::", format!("Target package {}{}{} is held. Remove it?", *BOLD, pkg.name(), *RESET), false)
|
||||
{
|
||||
self.meta.held_pkgs.insert(pkg.name().into());
|
||||
continue;
|
||||
}
|
||||
|
||||
alpm.trans_remove_pkg(pkg).unwrap();
|
||||
}
|
||||
}
|
||||
Upgrade(..) => {
|
||||
if let Some(not_available) = queue.iter().map(|a| *a).find(|a| alpm.get_package(a).is_none()) {
|
||||
if let Some(not_available) = queue.iter().copied().find(|a| alpm.get_package(a).is_none()) {
|
||||
err!(SyncError::TargetNotAvailable(not_available.into()))?
|
||||
}
|
||||
|
||||
let (deps, packages) = DependencyResolver::new(alpm, &ignored).enumerate(&queue)?;
|
||||
let (deps, packages) = DependencyResolver::new(alpm, ignored).enumerate(&queue)?;
|
||||
|
||||
for pkg in packages
|
||||
.iter()
|
||||
.filter(|a| !self.meta.ignored_pkgs.contains(a.name()))
|
||||
.filter_map(|a| {
|
||||
if let (None, Foreign) = (self.meta.foreign_pkgs.get(a.name()), self.meta.mode) {
|
||||
None
|
||||
} else {
|
||||
Some(*a)
|
||||
}
|
||||
(!matches!((self.meta.foreign_pkgs.get(a.name()), self.meta.mode), (None, Foreign))).then_some(*a)
|
||||
})
|
||||
.collect::<Vec<&Package>>()
|
||||
{
|
||||
if !self.agent && config.alpm().ignored().contains(&pkg.name()) {
|
||||
if let Err(_) = prompt(
|
||||
if !self.agent
|
||||
&& config.alpm().ignored().contains(&pkg.name())
|
||||
&& !prompt(
|
||||
"::",
|
||||
format!("Target package {}{}{} is ignored. Upgrade it?", *BOLD, pkg.name(), *RESET),
|
||||
false,
|
||||
) {
|
||||
self.meta.ignored_pkgs.insert(pkg.name().into());
|
||||
continue;
|
||||
}
|
||||
)
|
||||
{
|
||||
self.meta.ignored_pkgs.insert(pkg.name().into());
|
||||
continue;
|
||||
}
|
||||
|
||||
alpm.trans_add_pkg(pkg).unwrap();
|
||||
|
@ -471,20 +483,7 @@ impl<'a> TransactionHandle<'a> {
|
|||
fn apply_configuration(&mut self, instance: &ContainerHandle, create: bool) -> Result<()> {
|
||||
let depends = instance.metadata().dependencies();
|
||||
let explicit_packages: Vec<&str> = instance.metadata().explicit_packages();
|
||||
let pkgs = self
|
||||
.alpm
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.localdb()
|
||||
.pkgs()
|
||||
.iter()
|
||||
.filter(|p| {
|
||||
p.reason() == PackageReason::Explicit
|
||||
&& !p.name().starts_with("pacwrap-")
|
||||
&& !self.meta.foreign_pkgs.contains(p.name())
|
||||
})
|
||||
.map(|p| p.name())
|
||||
.collect();
|
||||
let pkgs = self.alpm.as_mut().expect("ALPM").localdb().pkgs().iter().map(|p| p.name()).collect();
|
||||
|
||||
if pkgs != explicit_packages || create {
|
||||
let mut instance = instance.clone();
|
||||
|
@ -550,7 +549,7 @@ impl<'a> TransactionHandle<'a> {
|
|||
}
|
||||
|
||||
pub fn metadata(&self) -> &TransactionMetadata {
|
||||
&self.meta
|
||||
self.meta
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -34,7 +34,7 @@ use crate::{
|
|||
error,
|
||||
exec::{fakeroot_container, ExecutionType::NonInteractive},
|
||||
lock::{Lock, LockError},
|
||||
log::Logger,
|
||||
log::{Level, Logger},
|
||||
sync::{
|
||||
self,
|
||||
filesystem::{validate_fs_states, FilesystemSync},
|
||||
|
@ -55,10 +55,10 @@ use crate::{
|
|||
};
|
||||
|
||||
lazy_static! {
|
||||
pub static ref BAR_CYAN_STYLE: ProgressStyle = ProgressStyle::with_template(&("{spinner:.bold.cyan} {msg}"))
|
||||
pub static ref BAR_CYAN_STYLE: ProgressStyle = ProgressStyle::with_template("{spinner:.bold.cyan} {msg}")
|
||||
.unwrap()
|
||||
.tick_strings(&["::", ":.", ".:", "::"]);
|
||||
pub static ref BAR_GREEN_STYLE: ProgressStyle = ProgressStyle::with_template(&("{spinner:.bold.green} {msg}"))
|
||||
pub static ref BAR_GREEN_STYLE: ProgressStyle = ProgressStyle::with_template("{spinner:.bold.green} {msg}")
|
||||
.unwrap()
|
||||
.tick_strings(&["::", ":.", ".:", "::"]);
|
||||
}
|
||||
|
@ -108,6 +108,10 @@ impl<'a> TransactionAggregator<'a> {
|
|||
}
|
||||
|
||||
pub fn flag(mut self, flags: TransactionFlags) -> Self {
|
||||
if flags.intersects(TransactionFlags::DEBUG) {
|
||||
self.logger.set_verbosity(4);
|
||||
}
|
||||
|
||||
self.flags = flags;
|
||||
self
|
||||
}
|
||||
|
@ -185,7 +189,7 @@ impl<'a> TransactionAggregator<'a> {
|
|||
}
|
||||
|
||||
if are_downstream {
|
||||
if !preview && (filesystem_sync || self.updated.len() > 0) {
|
||||
if !preview && (filesystem_sync || !self.updated.is_empty()) {
|
||||
linker.filesystem_state();
|
||||
linker.prepare(self.cache.registered().len(), self.progress.as_ref());
|
||||
linker.engage(&self.cache.registered())?;
|
||||
|
@ -203,7 +207,7 @@ impl<'a> TransactionAggregator<'a> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
pub fn transaction(&mut self, containers: &Vec<&'a str>) -> Result<()> {
|
||||
pub fn transaction(&mut self, containers: &[&'a str]) -> Result<()> {
|
||||
for ins in containers.iter() {
|
||||
if self.queried.contains(ins) {
|
||||
continue;
|
||||
|
@ -222,8 +226,8 @@ impl<'a> TransactionAggregator<'a> {
|
|||
.dependencies()
|
||||
.iter()
|
||||
.filter(|a| containers.contains(a))
|
||||
.map(|a| *a)
|
||||
.collect(),
|
||||
.copied()
|
||||
.collect::<Vec<&str>>(),
|
||||
)?;
|
||||
self.transact(inshandle)?;
|
||||
}
|
||||
|
@ -241,7 +245,7 @@ impl<'a> TransactionAggregator<'a> {
|
|||
None => Vec::new(),
|
||||
};
|
||||
|
||||
let alpm = sync::instantiate_alpm(&inshandle, &self.flags());
|
||||
let alpm = sync::instantiate_alpm(inshandle, self.flags());
|
||||
let mut meta = TransactionMetadata::new(queue);
|
||||
let mut handle = TransactionHandle::new(&mut meta).alpm_handle(alpm);
|
||||
let mut act: Box<dyn Transaction> = Prepare.from(self);
|
||||
|
@ -250,30 +254,33 @@ impl<'a> TransactionAggregator<'a> {
|
|||
self.action().begin_message(inshandle, self.progress.as_ref());
|
||||
|
||||
loop {
|
||||
self.logger().log(Level::Debug, &format!("Transaction state: {}", act.debug()))?;
|
||||
act = match act.engage(self, &mut handle, inshandle) {
|
||||
Ok(result) => {
|
||||
Ok(state) => {
|
||||
self.signal(&mut handle.alpm)?;
|
||||
|
||||
if let Skip = result {
|
||||
if let Skip = state {
|
||||
self.logger().log(Level::Debug, &format!("Transaction state: {}", act.debug()))?;
|
||||
handle.release();
|
||||
return Ok(());
|
||||
} else if let Complete(updated) = result {
|
||||
} else if let Complete(updated) = state {
|
||||
if updated {
|
||||
self.updated.insert(inshandle.vars().instance());
|
||||
|
||||
if let Some(_) = &self.progress {
|
||||
if self.progress.is_some() {
|
||||
println!();
|
||||
}
|
||||
}
|
||||
|
||||
self.logger().log(Level::Debug, &format!("Transaction state: {}", act.debug()))?;
|
||||
self.tracted = !updated;
|
||||
handle.release();
|
||||
return Ok(());
|
||||
} else if let UpdateSchema(_) = result {
|
||||
} else if let UpdateSchema(_) = state {
|
||||
self.updated.insert(inshandle.vars().instance());
|
||||
}
|
||||
|
||||
result
|
||||
state
|
||||
}
|
||||
Err(err) => {
|
||||
if let Some(progress) = self.progress.as_ref() {
|
||||
|
@ -283,8 +290,14 @@ impl<'a> TransactionAggregator<'a> {
|
|||
|
||||
handle.release();
|
||||
return match err.downcast::<SyncError>().map_err(|err| error!(SyncError::from(err)))? {
|
||||
SyncError::TransactionAgentFailure => exit(err.kind().code()),
|
||||
_ => Err(err),
|
||||
SyncError::TransactionAgentFailure => {
|
||||
self.logger().log(Level::Fatal, &format!("Transaction error: {:?}", err))?;
|
||||
exit(err.kind().code())
|
||||
}
|
||||
_ => {
|
||||
self.logger().log(Level::Error, &format!("Transaction error: {:?}", err))?;
|
||||
Err(err)
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
@ -293,25 +306,23 @@ impl<'a> TransactionAggregator<'a> {
|
|||
}
|
||||
|
||||
fn print_complete(&mut self, filesystem_sync: bool, target_amount: u64, target: Option<&&str>) {
|
||||
if let Some(_) = &self.progress {
|
||||
if self.progress.is_some() {
|
||||
let are_multiple = target_amount > 1;
|
||||
let flagged = self.flags.intersects(TransactionFlags::PREVIEW | TransactionFlags::CREATE);
|
||||
let container = if filesystem_sync && self.queried.is_empty() || flagged || self.tracted {
|
||||
None
|
||||
} else if are_multiple {
|
||||
Some("Containers")
|
||||
} else if let Some(target) = target {
|
||||
Some(*target)
|
||||
} else {
|
||||
None
|
||||
target.copied()
|
||||
};
|
||||
let message = if self.updated.is_empty() {
|
||||
container.map_or_else(
|
||||
|| format!("Transaction complete."),
|
||||
|| "Transaction complete.".to_string(),
|
||||
|c| format!("{} {} up-to-date.", c, if are_multiple { "are" } else { "is" }),
|
||||
)
|
||||
} else {
|
||||
format!("Transaction complete.")
|
||||
"Transaction complete.".to_string()
|
||||
};
|
||||
|
||||
println!("{} {}", *ARROW_GREEN, message);
|
||||
|
@ -339,11 +350,11 @@ impl<'a> TransactionAggregator<'a> {
|
|||
}
|
||||
|
||||
pub fn lock(&mut self) -> Result<&Lock> {
|
||||
self.lock.map_or_else(|| err!(LockError::NotAcquired), |f| Ok(f))
|
||||
self.lock.map_or_else(|| err!(LockError::NotAcquired), Ok)
|
||||
}
|
||||
|
||||
pub fn cache(&self) -> &ContainerCache {
|
||||
&self.cache
|
||||
self.cache
|
||||
}
|
||||
|
||||
pub fn action(&self) -> &TransactionType {
|
||||
|
@ -367,6 +378,6 @@ impl<'a> TransactionAggregator<'a> {
|
|||
}
|
||||
|
||||
pub fn logger(&mut self) -> &mut Logger {
|
||||
&mut self.logger
|
||||
self.logger
|
||||
}
|
||||
}
|
||||
|
|
|
@ -48,6 +48,7 @@ use crate::{
|
|||
|
||||
use super::SyncState;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Commit {
|
||||
state: TransactionState,
|
||||
keyring: bool,
|
||||
|
@ -72,7 +73,7 @@ impl Transaction for Commit {
|
|||
let instance = inshandle.vars().instance();
|
||||
let state = self.state.as_str();
|
||||
|
||||
if let SyncState::NotRequired = handle.trans_ready(&ag.action(), ag.flags())? {
|
||||
if let SyncState::NotRequired = handle.trans_ready(ag.action(), ag.flags())? {
|
||||
match ready_state(handle, ag.action(), &self.state) {
|
||||
Some(result) => return result,
|
||||
None => return Ok(TransactionState::Complete(false)),
|
||||
|
@ -101,11 +102,15 @@ impl Transaction for Commit {
|
|||
ag.keyring_update(inshandle)?;
|
||||
}
|
||||
|
||||
handle.set_alpm(Some(sync::instantiate_alpm(inshandle, &ag.flags())));
|
||||
handle.set_alpm(Some(sync::instantiate_alpm(inshandle, ag.flags())));
|
||||
handle.apply_configuration(inshandle, ag.flags().intersects(TransactionFlags::CREATE))?;
|
||||
ag.logger().log(Info, &format!("container {instance}'s {state} transaction complete"))?;
|
||||
next_state(handle, ag.action(), &self.state, true)
|
||||
}
|
||||
|
||||
fn debug(&self) -> String {
|
||||
format!("{self:?}")
|
||||
}
|
||||
}
|
||||
|
||||
fn confirm(
|
||||
|
@ -136,7 +141,7 @@ fn confirm(
|
|||
let action = ag.action().as_str();
|
||||
let query = format!("Proceed with {action}?");
|
||||
|
||||
if let Err(_) = prompt("::", format!("{}{query}{}", *BOLD, *RESET), true) {
|
||||
if !prompt("::", format!("{}{query}{}", *BOLD, *RESET), true) {
|
||||
Err(next_state(handle, ag.action(), state, false))?
|
||||
}
|
||||
}
|
||||
|
@ -146,7 +151,7 @@ fn confirm(
|
|||
Ok(sum.download())
|
||||
}
|
||||
|
||||
fn next_state<'a>(
|
||||
fn next_state(
|
||||
handle: &mut TransactionHandle,
|
||||
action: &TransactionType,
|
||||
state: &TransactionState,
|
||||
|
@ -168,7 +173,7 @@ fn next_state<'a>(
|
|||
}
|
||||
}
|
||||
|
||||
fn ready_state<'a>(
|
||||
fn ready_state(
|
||||
handle: &mut TransactionHandle,
|
||||
action: &TransactionType,
|
||||
state: &TransactionState,
|
||||
|
@ -202,10 +207,10 @@ fn wait_on_agent(mut agent: Child) -> Result<()> {
|
|||
_ =>
|
||||
if let Some(code) = status.code() {
|
||||
err!(SyncError::TransactionFailure(format!("General agent fault: Exit code {}", code)))
|
||||
} else if let Some(_) = status.signal() {
|
||||
} else if status.signal().is_some() {
|
||||
err!(SyncError::TransactionFailure(format!("Agent terminated with {}", status)))
|
||||
} else {
|
||||
err!(SyncError::TransactionFailure(format!("General agent fault")))
|
||||
err!(SyncError::TransactionFailure("General agent fault".to_string()))
|
||||
},
|
||||
},
|
||||
Err(error) => err!(SyncError::TransactionFailure(format!("Execution of agent failed: {}", error)))?,
|
||||
|
|
|
@ -33,6 +33,7 @@ use crate::{
|
|||
Result,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Schema {
|
||||
state: TransactionState,
|
||||
}
|
||||
|
@ -59,4 +60,8 @@ impl Transaction for Schema {
|
|||
ag.logger().log(Info, &format!("container {instance}'s filesystem schema updated.")).ok();
|
||||
Ok(TransactionState::Prepare)
|
||||
}
|
||||
|
||||
fn debug(&self) -> String {
|
||||
format!("{self:?}")
|
||||
}
|
||||
}
|
||||
|
|
|
@ -39,6 +39,7 @@ use crate::{
|
|||
Result,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Prepare {
|
||||
state: TransactionState,
|
||||
}
|
||||
|
@ -66,7 +67,7 @@ impl Transaction for Prepare {
|
|||
}
|
||||
}
|
||||
|
||||
if deps.len() > 0 {
|
||||
if !deps.is_empty() {
|
||||
for dep in deps.iter().rev() {
|
||||
match ag.cache().get_instance_option(dep) {
|
||||
Some(dep_handle) => handle.enumerate_package_lists(&sync::instantiate_alpm(dep_handle, ag.flags())),
|
||||
|
@ -126,4 +127,8 @@ impl Transaction for Prepare {
|
|||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn debug(&self) -> String {
|
||||
format!("{self:?}")
|
||||
}
|
||||
}
|
||||
|
|
|
@ -37,6 +37,7 @@ use crate::{
|
|||
Result,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Stage {
|
||||
state: TransactionState,
|
||||
mode: TransactionMode,
|
||||
|
@ -53,7 +54,7 @@ impl Transaction for Stage {
|
|||
flag = TransFlag::NO_DEP_VERSION;
|
||||
|
||||
if ag.flags().contains(TransactionFlags::DATABASE_ONLY) {
|
||||
flag = flag | TransFlag::DB_ONLY;
|
||||
flag |= TransFlag::DB_ONLY;
|
||||
}
|
||||
} else {
|
||||
modeset = Foreign;
|
||||
|
@ -74,12 +75,12 @@ impl Transaction for Stage {
|
|||
inshandle: &ContainerHandle,
|
||||
) -> Result<TransactionState> {
|
||||
if let Err(error) = handle.alpm().trans_init(self.flags) {
|
||||
err!(SyncError::InitializationFailure(error.to_string().into()))?
|
||||
err!(SyncError::InitializationFailure(error.to_string()))?
|
||||
}
|
||||
|
||||
ag.action().action_message(self.mode);
|
||||
handle.set_mode(self.mode);
|
||||
handle.ignore();
|
||||
handle.ignore(&mut ag.flags().contains(TransactionFlags::DEBUG).then_some(ag.logger()));
|
||||
handle.meta.set_flags(ag.flags(), &self.flags);
|
||||
|
||||
match ag.action() {
|
||||
|
@ -97,12 +98,16 @@ impl Transaction for Stage {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn debug(&self) -> String {
|
||||
format!("{self:?}")
|
||||
}
|
||||
}
|
||||
|
||||
fn check_keyring(ag: &TransactionAggregator, handle: &TransactionHandle, inshandle: &ContainerHandle) -> bool {
|
||||
inshandle.metadata().container_type() == &Base
|
||||
&& !ag.is_keyring_synced()
|
||||
&& handle.alpm().trans_add().iter().find(|a| a.name() == "archlinux-keyring").is_some()
|
||||
&& handle.alpm().trans_add().iter().any(|a| a.name() == "archlinux-keyring")
|
||||
}
|
||||
|
||||
fn next_state(state: &TransactionState, option: bool) -> Result<TransactionState> {
|
||||
|
|
|
@ -30,6 +30,7 @@ use crate::{
|
|||
Result,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct UpToDate;
|
||||
|
||||
impl Transaction for UpToDate {
|
||||
|
@ -54,4 +55,8 @@ impl Transaction for UpToDate {
|
|||
|
||||
Ok(Skip)
|
||||
}
|
||||
|
||||
fn debug(&self) -> String {
|
||||
format!("{self:?}")
|
||||
}
|
||||
}
|
||||
|
|
|
@ -46,14 +46,14 @@ pub trait AlpmUtils {
|
|||
}
|
||||
|
||||
impl AlpmUtils for Alpm {
|
||||
fn get_local_package<'a>(&self, pkg: &'a str) -> Option<&Package> {
|
||||
fn get_local_package(&self, pkg: &str) -> Option<&Package> {
|
||||
match self.localdb().pkg(pkg) {
|
||||
Ok(pkg) => Some(pkg),
|
||||
Err(_) => self
|
||||
.localdb()
|
||||
.pkgs()
|
||||
.iter()
|
||||
.find_map(|f| f.provides().iter().find(|d| pkg == d.name()).and_then(|_| Some(f))),
|
||||
.find_map(|f| f.provides().iter().find(|d| pkg == d.name()).map(|_| f)),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -62,12 +62,9 @@ impl AlpmUtils for Alpm {
|
|||
if let Ok(pkg) = sync.pkg(pkg) {
|
||||
return Some(pkg);
|
||||
} else {
|
||||
let package = sync
|
||||
.pkgs()
|
||||
.iter()
|
||||
.find_map(|f| f.provides().iter().find(|d| pkg == d.name()).and_then(|_| Some(f)));
|
||||
let package = sync.pkgs().iter().find_map(|f| f.provides().iter().find(|d| pkg == d.name()).map(|_| f));
|
||||
|
||||
if let None = package {
|
||||
if package.is_none() {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
@ -79,7 +76,7 @@ impl AlpmUtils for Alpm {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn erroneous_transaction<'a>(error: CommitError) -> Result<()> {
|
||||
pub fn erroneous_transaction(error: CommitError) -> Result<()> {
|
||||
/*
|
||||
* Qualify error type to ensure no segfault for error conditions of which are
|
||||
* unhandled by the upstream data function provided by the CommitError impl.
|
||||
|
@ -125,7 +122,7 @@ pub fn erroneous_transaction<'a>(error: CommitError) -> Result<()> {
|
|||
err!(SyncError::TransactionFailure(error.to_string()))
|
||||
}
|
||||
|
||||
pub fn erroneous_preparation<'a>(error: PrepareError) -> Result<()> {
|
||||
pub fn erroneous_preparation(error: PrepareError) -> Result<()> {
|
||||
/*
|
||||
* Qualify error type to ensure no segfault for error conditions of which are
|
||||
* unhandled by the upstream data function provided by the PrepareError impl.
|
||||
|
@ -193,7 +190,7 @@ pub fn signal_trap() {
|
|||
let mut count = 0;
|
||||
|
||||
Builder::new()
|
||||
.name(format!("pacwrap-signal"))
|
||||
.name("pacwrap-signal".to_string())
|
||||
.spawn(move || {
|
||||
for _ in signals.forever() {
|
||||
count += 1;
|
||||
|
|
|
@ -52,7 +52,7 @@ pub fn print_error(message: &str) {
|
|||
}
|
||||
|
||||
pub fn check_socket(socket: &String) -> bool {
|
||||
UnixStream::connect(&Path::new(socket)).is_ok()
|
||||
UnixStream::connect(Path::new(socket)).is_ok()
|
||||
}
|
||||
|
||||
pub fn unix_time_as_seconds() -> u64 {
|
||||
|
|
|
@ -67,6 +67,12 @@ impl Display for InvalidArgument {
|
|||
}
|
||||
}
|
||||
|
||||
impl<'a> Default for Arguments<'a> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Arguments<'a> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
|
@ -100,7 +106,7 @@ impl<'a> Arguments<'a> {
|
|||
_ => self.operands.push(match self.operands.last() {
|
||||
Some(last) => match last {
|
||||
Operand::Short(c) => Operand::ShortPos(*c, string),
|
||||
Operand::Long(s) => Operand::LongPos(*s, string),
|
||||
Operand::Long(s) => Operand::LongPos(s, string),
|
||||
_ => Operand::Value(string),
|
||||
},
|
||||
None => Operand::Value(string),
|
||||
|
@ -134,12 +140,16 @@ impl<'a> Arguments<'a> {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn inner(&self) -> &Vec<&'a str> {
|
||||
pub fn inner(&self) -> &[&'a str] {
|
||||
&self.inner
|
||||
}
|
||||
|
||||
pub fn into_inner(&self, skip: usize) -> Vec<&'a str> {
|
||||
self.inner.iter().map(|f| *f).skip(skip).collect()
|
||||
self.inner.iter().copied().skip(skip).collect()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.operands.is_empty()
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
|
|
|
@ -68,6 +68,12 @@ impl From<Vec<u8>> for ByteBuffer {
|
|||
}
|
||||
}
|
||||
|
||||
impl Default for ByteBuffer {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ByteBuffer {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
|
@ -133,7 +139,7 @@ impl ByteBuffer {
|
|||
pub fn write_byte(&mut self, value: u8) {
|
||||
self.check_write().unwrap();
|
||||
self.reserve_position(1);
|
||||
self.buffer.push(value as u8)
|
||||
self.buffer.push(value)
|
||||
}
|
||||
|
||||
pub fn read_byte(&mut self) -> u8 {
|
||||
|
|
|
@ -26,15 +26,11 @@ use std::io::Error;
|
|||
|
||||
use crate::constants::{BAR_RED, BOLD, RESET};
|
||||
|
||||
pub fn prompt(prefix: &str, prompt: impl Into<String>, yn_prompt: bool) -> Result<(), ()> {
|
||||
pub fn prompt(prefix: &str, prompt: impl Into<String>, yn_prompt: bool) -> bool {
|
||||
if let Ok(value) = create_prompt(prompt.into(), prefix, yn_prompt) {
|
||||
if value.to_lowercase() == "y" || (yn_prompt && value.is_empty()) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(())
|
||||
}
|
||||
value.to_lowercase() == "y" || (yn_prompt && value.is_empty())
|
||||
} else {
|
||||
Err(())
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -58,7 +54,7 @@ fn create_prompt(message: String, prefix: &str, yn_prompt: bool) -> Result<Strin
|
|||
return Input::with_theme(&theme).with_prompt(message).allow_empty(true).interact_text();
|
||||
}
|
||||
|
||||
pub fn prompt_targets(targets: &Vec<&str>, ins_prompt: &str, yn_prompt: bool) -> Result<(), ()> {
|
||||
pub fn prompt_targets(targets: &[&str], ins_prompt: &str, yn_prompt: bool) -> bool {
|
||||
eprintln!("{} {}Container{}{}\n", *BAR_RED, *BOLD, if targets.len() > 1 { "s" } else { "" }, *RESET);
|
||||
|
||||
for target in targets.iter() {
|
||||
|
|
|
@ -83,6 +83,12 @@ pub struct Table<'a> {
|
|||
built: bool,
|
||||
}
|
||||
|
||||
impl<'a> Default for Table<'a> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Table<'a> {
|
||||
pub fn new() -> Self {
|
||||
let width = Term::size(&Term::stdout()).1 as usize;
|
||||
|
@ -101,7 +107,7 @@ impl<'a> Table<'a> {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn header(mut self, vec: &'a Vec<&'a str>) -> Self {
|
||||
pub fn header(mut self, vec: &[&'a str]) -> Self {
|
||||
self.rows.push(vec.iter().map(|a| a.to_string()).collect());
|
||||
self.dimensions = (self.rows.len(), vec.len());
|
||||
|
||||
|
@ -148,7 +154,7 @@ impl<'a> Table<'a> {
|
|||
}
|
||||
|
||||
pub fn marked(&self) -> bool {
|
||||
self.marker.len() > 0
|
||||
!self.marker.is_empty()
|
||||
}
|
||||
|
||||
pub fn build(&'a mut self) -> Result<&Self, Error> {
|
||||
|
@ -267,7 +273,7 @@ impl<'a> Display for Table<'a> {
|
|||
}
|
||||
|
||||
for col in 0 .. self.dimensions.1 {
|
||||
if let None = self.columns.get(col) {
|
||||
if self.columns.get(col).is_none() {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
@ -290,8 +296,8 @@ impl<'a> Display for Table<'a> {
|
|||
mod test {
|
||||
use super::*;
|
||||
|
||||
static RESULT: &'static str = "[1mLorem ipsum dolor sit[0m\nLorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor \nLorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor \nLorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor \nLorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor \nLorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor \nLorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor \nLorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor \nLorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor \nLorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor \nLorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor \n";
|
||||
static TEST_DATA: [&'static str; 5] = [
|
||||
static RESULT: &str = "[1mLorem ipsum dolor sit[0m\nLorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor \nLorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor \nLorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor \nLorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor \nLorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor \nLorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor \nLorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor \nLorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor \nLorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor \nLorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor \n";
|
||||
static TEST_DATA: [&str; 5] = [
|
||||
"Lorem ipsum dolor",
|
||||
"sit amet",
|
||||
"consectetur adipiscing elit",
|
||||
|
|
|
@ -24,16 +24,16 @@ fn head() -> String {
|
|||
Command::new("git")
|
||||
.args(["rev-parse", "--short", "HEAD"])
|
||||
.output()
|
||||
.and_then(|output| Ok(String::from_utf8(output.stdout).expect("Invalid UTF-8 value")))
|
||||
.unwrap_or(String::new())
|
||||
.map(|output| String::from_utf8(output.stdout).expect("Invalid UTF-8 value"))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn tag() -> String {
|
||||
Command::new("git")
|
||||
.args(["tag", "--points-at"])
|
||||
.output()
|
||||
.and_then(|output| Ok(String::from_utf8(output.stdout).expect("Invalid UTF-8 value")))
|
||||
.unwrap_or(String::new())
|
||||
.map(|output| String::from_utf8(output.stdout).expect("Invalid UTF-8 value"))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn time(debug: bool) -> String {
|
||||
|
@ -41,13 +41,13 @@ fn time(debug: bool) -> String {
|
|||
false => Command::new("git")
|
||||
.args(["log", "-1", "--date=format:%d/%m/%Y", "--format=%cd"])
|
||||
.output()
|
||||
.and_then(|output| Ok(String::from_utf8(output.stdout).expect("Invalid UTF-8 value")))
|
||||
.and_then(|date| Ok(date.is_empty().then(|| mtime()).unwrap_or(date)))
|
||||
.map(|output| String::from_utf8(output.stdout).expect("Invalid UTF-8 value"))
|
||||
.map(|date| date.is_empty().then(mtime).unwrap_or(date))
|
||||
.unwrap_or(mtime()),
|
||||
true => Command::new("date")
|
||||
.args(["+%d/%m/%Y %T%:z"])
|
||||
.output()
|
||||
.and_then(|output| Ok(String::from_utf8(output.stdout).expect("Invalid UTF-8 value")))
|
||||
.map(|output| String::from_utf8(output.stdout).expect("Invalid UTF-8 value"))
|
||||
.expect("'date': executable not found in PATH"),
|
||||
}
|
||||
}
|
||||
|
@ -57,7 +57,7 @@ fn mtime() -> String {
|
|||
.args(["+%d/%m/%Y", "--utc", "--date"])
|
||||
.arg(format!("@{}", Path::new(".").metadata().expect("Metadata expected for src directory").mtime()))
|
||||
.output()
|
||||
.and_then(|output| Ok(String::from_utf8(output.stdout).expect("Invalid UTF-8 value")))
|
||||
.map(|output| String::from_utf8(output.stdout).expect("Invalid UTF-8 value"))
|
||||
.expect("'date': executable not found in PATH")
|
||||
}
|
||||
|
||||
|
|
|
@ -62,7 +62,7 @@ fn delete_containers<'a>(
|
|||
cache: &'a ContainerCache<'a>,
|
||||
lock: &'a Lock,
|
||||
logger: &mut Logger,
|
||||
delete: &Vec<&str>,
|
||||
delete: &[&str],
|
||||
flags: &TransactionFlags,
|
||||
force: bool,
|
||||
) -> Result<()> {
|
||||
|
@ -71,7 +71,7 @@ fn delete_containers<'a>(
|
|||
if flags.contains(TransactionFlags::NO_CONFIRM) {
|
||||
println!("{} {}{}...{}", *BAR_GREEN, *BOLD, &message, *RESET);
|
||||
delete_roots(cache, lock, logger, delete, force)?;
|
||||
} else if let Ok(_) = prompt_targets(&delete, &message, false) {
|
||||
} else if prompt_targets(delete, &message, false) {
|
||||
delete_roots(cache, lock, logger, delete, force)?;
|
||||
}
|
||||
|
||||
|
@ -94,7 +94,7 @@ fn compose_handles<'a>(
|
|||
err!(ErrorKind::Message("Symbolic containers require at least one dependency."))?;
|
||||
}
|
||||
} else if let Base = container_type {
|
||||
if depends.len() > 0 {
|
||||
if !depends.is_empty() {
|
||||
err!(ErrorKind::Message("Dependencies cannot be assigned to base containers."))?;
|
||||
}
|
||||
}
|
||||
|
@ -158,7 +158,7 @@ fn acquire_targets<'a>(
|
|||
Ok(())
|
||||
}
|
||||
|
||||
fn engage_aggregator<'a>(args: &mut Arguments, lock: &'a Lock) -> Result<()> {
|
||||
fn engage_aggregator(args: &mut Arguments, lock: &Lock) -> Result<()> {
|
||||
let mut cache = match args.into_iter().find(|a| *a == Op::Long("from-config")) {
|
||||
Some(_) => cache::populate_config(),
|
||||
None => cache::populate(),
|
||||
|
@ -182,9 +182,9 @@ fn engage_aggregator<'a>(args: &mut Arguments, lock: &'a Lock) -> Result<()> {
|
|||
while let Some(arg) = args.next() {
|
||||
match arg {
|
||||
Op::Long("from-config") => continue,
|
||||
Op::Long("debug") => flags = flags | TransactionFlags::DEBUG,
|
||||
Op::Long("noconfirm") => flags = flags | TransactionFlags::NO_CONFIRM,
|
||||
Op::Long("disable-sandbox") => flags = flags | TransactionFlags::NO_ALPM_SANDBOX,
|
||||
Op::Long("debug") => flags |= TransactionFlags::DEBUG,
|
||||
Op::Long("noconfirm") => flags |= TransactionFlags::NO_CONFIRM,
|
||||
Op::Long("disable-sandbox") => flags |= TransactionFlags::NO_ALPM_SANDBOX,
|
||||
Op::Long("reinitialize-all") =>
|
||||
for instance in cache.registered() {
|
||||
if let Some(handle) = cache.get_instance_option(instance) {
|
||||
|
@ -195,7 +195,7 @@ fn engage_aggregator<'a>(args: &mut Arguments, lock: &'a Lock) -> Result<()> {
|
|||
compose.insert(instance, None);
|
||||
}
|
||||
},
|
||||
Op::Short('l') | Op::Long("lazy-load") => flags = flags | TransactionFlags::LAZY_LOAD_DB,
|
||||
Op::Short('l') | Op::Long("lazy-load") => flags |= TransactionFlags::LAZY_LOAD_DB,
|
||||
Op::Short('f') | Op::Long("force") => force = true,
|
||||
Op::Short('r') | Op::Long("reinitialize") => reinitialize = true,
|
||||
Op::Short('t') | Op::Long("target") => match args.next() {
|
||||
|
@ -222,10 +222,7 @@ fn engage_aggregator<'a>(args: &mut Arguments, lock: &'a Lock) -> Result<()> {
|
|||
|
||||
Path::new(target).try_exists().prepend_io(|| target.into())?;
|
||||
|
||||
match current_target {
|
||||
Some(_) => Some(config),
|
||||
None => None,
|
||||
}
|
||||
current_target.map(|_| config)
|
||||
} else {
|
||||
Some(config)
|
||||
};
|
||||
|
@ -238,11 +235,11 @@ fn engage_aggregator<'a>(args: &mut Arguments, lock: &'a Lock) -> Result<()> {
|
|||
}
|
||||
}
|
||||
|
||||
if compose.len() == 0 {
|
||||
if compose.is_empty() {
|
||||
err!(ErrorKind::Message("Composition targets not specified."))?
|
||||
}
|
||||
|
||||
if delete.len() > 0 {
|
||||
if !delete.is_empty() {
|
||||
delete_containers(&cache, lock, &mut logger, &delete, &flags, force)?;
|
||||
}
|
||||
|
||||
|
@ -255,11 +252,11 @@ fn engage_aggregator<'a>(args: &mut Arguments, lock: &'a Lock) -> Result<()> {
|
|||
cache = instantiate(compose_handles(&cache, compose)?, cache, lock, &mut logger)?;
|
||||
acquire_targets(&cache, &mut targets, &mut queue)?;
|
||||
instantiate_trust()?;
|
||||
Ok(TransactionAggregator::new(&cache, &mut logger, TransactionType::Upgrade(true, true, false))
|
||||
TransactionAggregator::new(&cache, &mut logger, TransactionType::Upgrade(true, true, false))
|
||||
.assert_lock(lock)?
|
||||
.target(Some(targets))
|
||||
.flag(flags)
|
||||
.queue(queue)
|
||||
.progress()
|
||||
.aggregate()?)
|
||||
.aggregate()
|
||||
}
|
||||
|
|
|
@ -111,7 +111,7 @@ enum ExecParams<'a> {
|
|||
impl<'a> ExecParams<'a> {
|
||||
fn parse(args: &'a mut Arguments) -> Result<Self> {
|
||||
let mut verbosity: i8 = 0;
|
||||
let mut shell = if let Op::Value("shell") = args[0] { true } else { false };
|
||||
let mut shell = matches!(args[0], Op::Value("shell"));
|
||||
let mut root = false;
|
||||
let mut container = None;
|
||||
let mut pos = 1;
|
||||
|
@ -131,7 +131,7 @@ impl<'a> ExecParams<'a> {
|
|||
Op::Long("shell") | Op::Short('s') => shell = true,
|
||||
Op::Long("verbose") | Op::Short('v') => verbosity += 1,
|
||||
Op::LongPos(_, str) | Op::ShortPos(_, str) | Op::Value(str) =>
|
||||
if let None = container {
|
||||
if container.is_none() {
|
||||
container = Some(str);
|
||||
break;
|
||||
},
|
||||
|
@ -166,12 +166,12 @@ pub fn execute<'a>(args: &'a mut Arguments<'a>) -> Result<()> {
|
|||
}
|
||||
}
|
||||
|
||||
fn execute_container<'a>(ins: &ContainerHandle, arguments: Vec<&str>, shell: bool, verbosity: i8) -> Result<()> {
|
||||
fn execute_container(ins: &ContainerHandle, arguments: Vec<&str>, shell: bool, verbosity: i8) -> Result<()> {
|
||||
let mut exec = ExecutionArgs::new();
|
||||
let mut jobs: Vec<Child> = Vec::new();
|
||||
let cfg = ins.config();
|
||||
let vars = ins.vars();
|
||||
let dbus = cfg.dbus().len() > 0;
|
||||
let dbus = !cfg.dbus().is_empty();
|
||||
|
||||
if !cfg.allow_forking() {
|
||||
exec.push_env(Argument::DieWithParent);
|
||||
|
@ -196,12 +196,12 @@ fn execute_container<'a>(ins: &ContainerHandle, arguments: Vec<&str>, shell: boo
|
|||
jobs.push(instantiate_dbus_proxy(cfg.dbus(), &mut exec)?);
|
||||
}
|
||||
|
||||
exec.env("XDG_RUNTIME_DIR", &*XDG_RUNTIME_DIR);
|
||||
register_filesystems(cfg.filesystem(), &vars, &mut exec)?;
|
||||
exec.env("XDG_RUNTIME_DIR", &XDG_RUNTIME_DIR);
|
||||
register_filesystems(cfg.filesystem(), vars, &mut exec)?;
|
||||
register_permissions(cfg.permissions(), &mut exec)?;
|
||||
|
||||
let path = match exec.obtain_env("PATH") {
|
||||
Some(var) => &var,
|
||||
Some(var) => var,
|
||||
None => {
|
||||
exec.env("PATH", DEFAULT_PATH);
|
||||
DEFAULT_PATH
|
||||
|
@ -250,10 +250,10 @@ fn execute_container<'a>(ins: &ContainerHandle, arguments: Vec<&str>, shell: boo
|
|||
.unwrap()
|
||||
};
|
||||
|
||||
if verbosity == 1 {
|
||||
eprintln!("Arguments:\t {arguments:?}\n{ins:?}");
|
||||
} else if verbosity > 1 {
|
||||
eprintln!("Arguments:\t {arguments:?}\n{ins:?}\n{exec:?}");
|
||||
match verbosity {
|
||||
0 => (),
|
||||
1 => eprintln!("Arguments:\t {arguments:?}\n{ins:?}"),
|
||||
_ => eprintln!("Arguments:\t {arguments:?}\n{ins:?}\n{exec:?}"),
|
||||
}
|
||||
|
||||
check_path(ins, &arguments, path_vec)?;
|
||||
|
@ -264,7 +264,7 @@ fn execute_container<'a>(ins: &ContainerHandle, arguments: Vec<&str>, shell: boo
|
|||
term_control,
|
||||
decode_info_json(info_pipe)?,
|
||||
*cfg.allow_forking(),
|
||||
match jobs.len() > 0 {
|
||||
match !jobs.is_empty() {
|
||||
true => Some(jobs),
|
||||
false => None,
|
||||
},
|
||||
|
@ -293,7 +293,7 @@ fn signal_trap(bwrap_pid: i32) {
|
|||
let mut signals = Signals::new(*SIGNAL_LIST).unwrap();
|
||||
|
||||
thread::Builder::new()
|
||||
.name(format!("pacwrap-signal"))
|
||||
.name("pacwrap-signal".to_string())
|
||||
.spawn(move || {
|
||||
let proc: &str = &format!("/proc/{}/", bwrap_pid);
|
||||
let proc = Path::new(proc);
|
||||
|
@ -307,12 +307,12 @@ fn signal_trap(bwrap_pid: i32) {
|
|||
.unwrap();
|
||||
}
|
||||
|
||||
fn instantiate_dbus_proxy(per: &Vec<Box<dyn Dbus>>, args: &mut ExecutionArgs) -> Result<Child> {
|
||||
fn instantiate_dbus_proxy(per: &[Box<dyn Dbus>], args: &mut ExecutionArgs) -> Result<Child> {
|
||||
let dbus_socket_path = format!("/run/user/{}/bus", nix::unistd::geteuid());
|
||||
let dbus_session = env_var("DBUS_SESSION_BUS_ADDRESS")?;
|
||||
|
||||
register_dbus(per, args)?;
|
||||
create_placeholder(&*DBUS_SOCKET)?;
|
||||
create_placeholder(&DBUS_SOCKET)?;
|
||||
|
||||
match Command::new(DBUS_PROXY_EXECUTABLE)
|
||||
.arg(dbus_session)
|
||||
|
@ -323,7 +323,7 @@ fn instantiate_dbus_proxy(per: &Vec<Box<dyn Dbus>>, args: &mut ExecutionArgs) ->
|
|||
Ok(mut child) => {
|
||||
let mut increment: u8 = 0;
|
||||
|
||||
args.robind(&*DBUS_SOCKET, &dbus_socket_path);
|
||||
args.robind(&DBUS_SOCKET, &dbus_socket_path);
|
||||
args.symlink(&dbus_socket_path, "/run/dbus/system_bus_socket");
|
||||
args.env("DBUS_SESSION_BUS_ADDRESS", &format!("unix:path={dbus_socket_path}"));
|
||||
|
||||
|
@ -338,7 +338,7 @@ fn instantiate_dbus_proxy(per: &Vec<Box<dyn Dbus>>, args: &mut ExecutionArgs) ->
|
|||
* to wait on a FD prior to instantiating the filesystem bindings.
|
||||
*/
|
||||
|
||||
while !check_socket(&*DBUS_SOCKET, &increment, &mut child)? {
|
||||
while !check_socket(&DBUS_SOCKET, &increment, &mut child)? {
|
||||
increment += 1;
|
||||
}
|
||||
|
||||
|
@ -361,7 +361,10 @@ fn check_socket(socket: &String, increment: &u8, process_child: &mut Child) -> R
|
|||
|
||||
fn create_placeholder(path: &str) -> Result<()> {
|
||||
match File::create(path) {
|
||||
Ok(file) => Ok(drop(file)),
|
||||
Ok(file) => {
|
||||
drop(file);
|
||||
Ok(())
|
||||
}
|
||||
Err(error) => err!(ErrorKind::IOError(path.into(), error.kind())),
|
||||
}
|
||||
}
|
||||
|
|
|
@ -68,8 +68,8 @@ impl Display for ErrorKind {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn help(mut args: &mut Arguments) -> Result<()> {
|
||||
let help = ascertain_help(&mut args)?;
|
||||
pub fn help(args: &mut Arguments) -> Result<()> {
|
||||
let help = ascertain_help(args)?;
|
||||
let mut buffer = String::new();
|
||||
|
||||
for topic in help.0 {
|
||||
|
|
|
@ -31,10 +31,10 @@ fn minimal(args: &mut Arguments) -> bool {
|
|||
.is_some()
|
||||
}
|
||||
|
||||
pub fn print_version(mut args: &mut Arguments) -> Result<()> {
|
||||
pub fn print_version(args: &mut Arguments) -> Result<()> {
|
||||
let version = format!("{} v{}", env!("CARGO_PKG_NAME"), version_string());
|
||||
|
||||
if !minimal(&mut args) && is_truecolor_terminal() {
|
||||
if !minimal(args) && is_truecolor_terminal() {
|
||||
println!("\x1b[?7l\n [0m[38;2;8;7;6m [0m[38;2;59;52;34mP[0m[38;2;62;56;41mP[0m[38;2;90;81;58mA[0m[38;2;117;105;76mA[0m[38;2;146;131;94mC[0m[38;2;174;156;111mW[0m[38;2;204;182;130mW[0m[38;2;225;200;142mR[0m[38;2;196;173;120mR[0m[38;2;149;130;91mA[0m[38;2;101;88;62mA[0m[38;2;53;46;33mP[0m[38;2;10;8;6m [0m
|
||||
[0m[38;2;14;12;10m [0m[38;2;67;60;43mR[0m[38;2;67;60;43mA[0m[38;2;93;83;60mP[0m[38;2;120;107;77mP[0m[38;2;147;132;95mP[0m[38;2;175;157;112mA[0m[38;2;201;180;129mC[0m[38;2;225;202;144mC[0m[38;2;230;206;146mC[0m[38;2;230;206;146mC[0m[38;2;230;206;146mC[0m[38;2;230;206;146mC[0m[38;2;230;206;146mC[0m[38;2;230;206;146mC[0m[38;2;230;206;146mC[0m[38;2;230;205;144mC[0m[38;2;230;202;139mC[0m[38;2;230;202;139mC[0m[38;2;230;202;139mC[0m[38;2;230;202;139mC[0m[38;2;221;195;135mC[0m[38;2;180;158;110mA[0m[38;2;134;118;82mP[0m[38;2;86;76;53mA[0[38;2;59;52;34mR[0m[38;2;3;3;2m [0m
|
||||
[0m[38;2;9;8;6m [0m[38;2;38;34;25mR[0m[38;2;66;59;43mA[0m[38;2;94;84;60mP[0m[38;2;123;109;79mP[0m[38;2;151;135;97mP[0m[38;2;180;161;114mA[0m[38;2;209;190;115mC[0m[38;2;234;216;110m#[0m[38;2;238;221;100m#[0m[38;2;238;222;99m#[0m[38;2;237;219;106m#[0m[38;2;234;214;123m#[0m[38;2;230;207;143mC[0m[38;2;230;206;146mC[0m[38;2;230;206;146mC[0m[38;2;230;206;146mC[0m[38;2;230;206;146mC[0m[38;2;230;206;146mC[0m[38;2;230;206;146mC[0m[38;2;230;206;146mC[0m[38;2;230;206;146mC[0m[38;2;230;206;146mC[0m[38;2;230;206;146mC[0m[38;2;230;205;144mC[0m[38;2;230;202;139mC[0m[38;2;230;202;139mC[0m[38;2;230;202;139mC[0m[38;2;230;202;139mC[0m[38;2;230;202;139mC[0m[38;2;230;202;139mC[0m[38;2;230;202;139mC[0m[38;2;230;202;139mC[0m[38;2;230;202;139mC[0m[38;2;211;186;129mC[0m[38;2;165;145;101mA[0m[38;2;117;103;72mP[0m[38;2;69;61;43mA[0m[38;2;59;52;34mR [0m
|
||||
|
|
|
@ -117,7 +117,7 @@ fn summary(args: &mut Arguments) -> Result<()> {
|
|||
let col = (exec > 0, exec > 1 || cmd > 0, (exec > 0) as usize);
|
||||
let cache = cache::populate()?;
|
||||
let list = process::list(&cache)?;
|
||||
let list: Vec<_> = match instances.len() > 0 {
|
||||
let list: Vec<_> = match !instances.is_empty() {
|
||||
true => list
|
||||
.list()
|
||||
.iter()
|
||||
|
@ -126,10 +126,10 @@ fn summary(args: &mut Arguments) -> Result<()> {
|
|||
false => None,
|
||||
})
|
||||
.collect(),
|
||||
false => list.list().iter().filter(|a| a.depth() <= max_depth || all).map(|a| *a).collect(),
|
||||
false => list.list().iter().filter(|a| a.depth() <= max_depth || all).copied().collect(),
|
||||
};
|
||||
|
||||
if list.len() == 0 {
|
||||
if list.is_empty() {
|
||||
err!(ProcError::NotEnumerable)?
|
||||
}
|
||||
|
||||
|
@ -141,13 +141,13 @@ fn summary(args: &mut Arguments) -> Result<()> {
|
|||
};
|
||||
let mut table = if let (true, false, _) | (true, true, _) = col {
|
||||
Table::new()
|
||||
.header(&table_header)
|
||||
.header(table_header)
|
||||
.col_attribute(0, ColumnAttribute::AlignRight)
|
||||
.col_attribute(1, ColumnAttribute::AlignLeftMax(15))
|
||||
.col_attribute(2, ColumnAttribute::AlignLeftMax(15))
|
||||
} else {
|
||||
Table::new()
|
||||
.header(&table_header)
|
||||
.header(table_header)
|
||||
.col_attribute(0, ColumnAttribute::AlignRight)
|
||||
.col_attribute(1, ColumnAttribute::AlignLeftMax(15))
|
||||
};
|
||||
|
@ -188,18 +188,18 @@ fn process_id(args: &mut Arguments) -> Result<()> {
|
|||
}
|
||||
}
|
||||
|
||||
if instance.len() == 0 && !all {
|
||||
if instance.is_empty() && !all {
|
||||
err!(InvalidArgument::TargetUnspecified)?
|
||||
}
|
||||
|
||||
let cache = cache::populate()?;
|
||||
let list = process::list(&cache)?;
|
||||
let list: Vec<_> = match all {
|
||||
false => list.list().iter().filter(|a| instance.contains(&a.instance())).map(|a| *a).collect(),
|
||||
false => list.list().iter().filter(|a| instance.contains(&a.instance())).copied().collect(),
|
||||
true => list.list(),
|
||||
};
|
||||
|
||||
if list.len() == 0 {
|
||||
if list.is_empty() {
|
||||
err!(ProcError::NotEnumerable)?
|
||||
}
|
||||
|
||||
|
@ -260,7 +260,7 @@ fn process_kill(args: &mut Arguments) -> Result<()> {
|
|||
true => list.list(),
|
||||
};
|
||||
|
||||
if list.len() == 0 {
|
||||
if list.is_empty() {
|
||||
err!(ProcError::SpecifiedNotEnumerable)?
|
||||
}
|
||||
|
||||
|
@ -276,9 +276,9 @@ fn process_kill(args: &mut Arguments) -> Result<()> {
|
|||
}
|
||||
|
||||
let instances: Vec<String> = instances.iter().map(|a| format!("{} ({}{}{})", a.0, *DIM, a.1, *RESET)).collect();
|
||||
let instances = &instances.iter().map(|a| a.as_ref()).collect();
|
||||
let instances: Vec<&str> = instances.iter().map(|a| a.as_ref()).collect();
|
||||
|
||||
match no_confirm || prompt_targets(instances, "Kill container processes?", false).is_ok() {
|
||||
match no_confirm || prompt_targets(&instances, "Kill container processes?", false) {
|
||||
true => kill_processes(&list, sigint),
|
||||
false => Ok(()),
|
||||
}
|
||||
|
|
|
@ -41,7 +41,7 @@ pub fn query(arguments: &mut Arguments) -> Result<()> {
|
|||
|
||||
while let Some(arg) = arguments.next() {
|
||||
match arg {
|
||||
Operand::Long("debug") => flags = flags | TransactionFlags::DEBUG,
|
||||
Operand::Long("debug") => flags |= TransactionFlags::DEBUG,
|
||||
Operand::Long("target") | Operand::Short('t') => continue,
|
||||
Operand::Short('e') | Operand::Long("explicit") => explicit = true,
|
||||
Operand::Short('q') | Operand::Long("quiet") => quiet = true,
|
||||
|
|
|
@ -35,7 +35,7 @@ use pacwrap_core::{
|
|||
|
||||
use crate::utils::delete::remove_containers;
|
||||
|
||||
pub fn remove(mut args: &mut Arguments) -> Result<()> {
|
||||
pub fn remove(args: &mut Arguments) -> Result<()> {
|
||||
check_root()?;
|
||||
init()?;
|
||||
|
||||
|
@ -46,7 +46,7 @@ pub fn remove(mut args: &mut Arguments) -> Result<()> {
|
|||
let mut logger = Logger::new("pacwrap-sync").init().unwrap();
|
||||
let action = action(args);
|
||||
let lock = Lock::new().lock()?;
|
||||
let result = engage_aggregator(action, &mut args, &mut logger, &lock);
|
||||
let result = engage_aggregator(action, args, &mut logger, &lock);
|
||||
|
||||
if let Err(error) = lock.unlock() {
|
||||
error.error();
|
||||
|
@ -59,7 +59,7 @@ fn action(args: &mut Arguments) -> TransactionType {
|
|||
let mut recursive = 0;
|
||||
let mut cascade = false;
|
||||
|
||||
while let Some(arg) = args.next() {
|
||||
for arg in args.by_ref() {
|
||||
match arg {
|
||||
Op::Short('s') | Op::Long("recursive") => recursive += 1,
|
||||
Op::Short('c') | Op::Long("cascade") => cascade = true,
|
||||
|
@ -94,13 +94,13 @@ fn engage_aggregator<'a>(
|
|||
| Op::Short('R')
|
||||
| Op::Short('c')
|
||||
| Op::Short('s') => continue,
|
||||
Op::Long("debug") => flags = flags | TransactionFlags::DEBUG,
|
||||
Op::Long("dbonly") => flags = flags | TransactionFlags::DATABASE_ONLY,
|
||||
Op::Long("noconfirm") => flags = flags | TransactionFlags::NO_CONFIRM,
|
||||
Op::Long("force-foreign") => flags = flags | TransactionFlags::FORCE_DATABASE,
|
||||
Op::Long("disable-sandbox") => flags = flags | TransactionFlags::NO_ALPM_SANDBOX,
|
||||
Op::Short('p') | Op::Long("preview") => flags = flags | TransactionFlags::PREVIEW,
|
||||
Op::Short('f') | Op::Long("filesystem") => flags = flags | TransactionFlags::FILESYSTEM_SYNC,
|
||||
Op::Long("debug") => flags |= TransactionFlags::DEBUG,
|
||||
Op::Long("dbonly") => flags |= TransactionFlags::DATABASE_ONLY,
|
||||
Op::Long("noconfirm") => flags |= TransactionFlags::NO_CONFIRM,
|
||||
Op::Long("force-foreign") => flags |= TransactionFlags::FORCE_DATABASE,
|
||||
Op::Long("disable-sandbox") => flags |= TransactionFlags::NO_ALPM_SANDBOX,
|
||||
Op::Short('p') | Op::Long("preview") => flags |= TransactionFlags::PREVIEW,
|
||||
Op::Short('f') | Op::Long("filesystem") => flags |= TransactionFlags::FILESYSTEM_SYNC,
|
||||
Op::Short('t') | Op::Long("target") => match args.next() {
|
||||
Some(arg) => match arg {
|
||||
Op::ShortPos('t', target) | Op::LongPos("target", target) => {
|
||||
|
@ -128,14 +128,14 @@ fn engage_aggregator<'a>(
|
|||
}
|
||||
}
|
||||
|
||||
if let None = current_target {
|
||||
if current_target.is_none() {
|
||||
err!(TargetUnspecified)?
|
||||
}
|
||||
|
||||
Ok(TransactionAggregator::new(&cache, log, action_type)
|
||||
TransactionAggregator::new(&cache, log, action_type)
|
||||
.assert_lock(lock)?
|
||||
.target(Some(targets))
|
||||
.flag(flags)
|
||||
.queue(queue)
|
||||
.aggregate()?)
|
||||
.aggregate()
|
||||
}
|
||||
|
|
|
@ -64,7 +64,7 @@ fn action(args: &mut Arguments) -> (TransactionType, bool) {
|
|||
(y, u, i) = (1, 1, true);
|
||||
}
|
||||
|
||||
while let Some(arg) = args.next() {
|
||||
for arg in args.by_ref() {
|
||||
match arg {
|
||||
Op::Short('y') | Op::Long("refresh") => y += 1,
|
||||
Op::Short('u') | Op::Long("upgrade") => u += 1,
|
||||
|
@ -95,11 +95,11 @@ fn instantiate<'a>(
|
|||
}
|
||||
|
||||
for (container, (container_type, deps)) in targets.iter() {
|
||||
if let (ContainerType::Base, true) = (container_type, deps.len() > 0) {
|
||||
if let (ContainerType::Base, true) = (container_type, !deps.is_empty()) {
|
||||
err!(ErrorKind::Message("Dependencies cannot be assigned to base containers."))?
|
||||
} else if let (ContainerType::Aggregate | ContainerType::Slice, true) = (container_type, deps.is_empty()) {
|
||||
err!(ErrorKind::Message("Dependencies not specified."))?
|
||||
} else if let Some(_) = cache.get_instance_option(container) {
|
||||
} else if cache.get_instance_option(container).is_some() {
|
||||
err!(AlreadyExists(container.to_string()))?;
|
||||
}
|
||||
}
|
||||
|
@ -145,7 +145,7 @@ fn acquire_targets<'a>(
|
|||
}
|
||||
|
||||
fn engage_aggregator<'a>(
|
||||
mut cache: &mut ContainerCache<'a>,
|
||||
cache: &mut ContainerCache<'a>,
|
||||
log: &'a mut Logger,
|
||||
args: &'a mut Arguments,
|
||||
lock: &'a Lock,
|
||||
|
@ -167,15 +167,15 @@ fn engage_aggregator<'a>(
|
|||
while let Some(arg) = args.next() {
|
||||
match arg {
|
||||
Op::Short('y') | Op::Short('u') | Op::Long("refresh") | Op::Long("upgrade") => continue,
|
||||
Op::Long("debug") => flags = flags | TransactionFlags::DEBUG,
|
||||
Op::Long("dbonly") => flags = flags | TransactionFlags::DATABASE_ONLY,
|
||||
Op::Long("noconfirm") => flags = flags | TransactionFlags::NO_CONFIRM,
|
||||
Op::Long("force-foreign") => flags = flags | TransactionFlags::FORCE_DATABASE,
|
||||
Op::Long("disable-sandbox") => flags = flags | TransactionFlags::NO_ALPM_SANDBOX,
|
||||
Op::Short('l') | Op::Long("lazy-load") => flags = flags | TransactionFlags::LAZY_LOAD_DB,
|
||||
Op::Short('o') | Op::Long("target-only") => flags = flags | TransactionFlags::TARGET_ONLY,
|
||||
Op::Short('f') | Op::Long("filesystem") => flags = flags | TransactionFlags::FILESYSTEM_SYNC,
|
||||
Op::Short('p') | Op::Long("preview") => flags = flags | TransactionFlags::PREVIEW,
|
||||
Op::Long("debug") => flags |= TransactionFlags::DEBUG,
|
||||
Op::Long("dbonly") => flags |= TransactionFlags::DATABASE_ONLY,
|
||||
Op::Long("noconfirm") => flags |= TransactionFlags::NO_CONFIRM,
|
||||
Op::Long("force-foreign") => flags |= TransactionFlags::FORCE_DATABASE,
|
||||
Op::Long("disable-sandbox") => flags |= TransactionFlags::NO_ALPM_SANDBOX,
|
||||
Op::Short('l') | Op::Long("lazy-load") => flags |= TransactionFlags::LAZY_LOAD_DB,
|
||||
Op::Short('o') | Op::Long("target-only") => flags |= TransactionFlags::TARGET_ONLY,
|
||||
Op::Short('f') | Op::Long("filesystem") => flags |= TransactionFlags::FILESYSTEM_SYNC,
|
||||
Op::Short('p') | Op::Long("preview") => flags |= TransactionFlags::PREVIEW,
|
||||
Op::Short('b') | Op::Long("base") => container_type = Some(ContainerType::Base),
|
||||
Op::Short('s') | Op::Long("slice") => container_type = Some(ContainerType::Slice),
|
||||
Op::Short('a') | Op::Long("aggregate") => container_type = Some(ContainerType::Aggregate),
|
||||
|
@ -215,7 +215,7 @@ fn engage_aggregator<'a>(
|
|||
|
||||
if let (true, Some(container_type)) = (create, container_type) {
|
||||
if let ContainerType::Base = container_type {
|
||||
queue.insert(target.into(), vec!["base"]);
|
||||
queue.insert(target, vec!["base"]);
|
||||
}
|
||||
|
||||
create_targets.insert(target, (container_type, vec![]));
|
||||
|
@ -233,7 +233,7 @@ fn engage_aggregator<'a>(
|
|||
Op::LongPos(_, package) | Op::ShortPos(_, package) | Op::Value(package) =>
|
||||
if let Some(current_target) = current_target {
|
||||
if let Some(vec) = queue.get_mut(current_target) {
|
||||
vec.push(package.into());
|
||||
vec.push(package);
|
||||
} else {
|
||||
queue.insert(current_target, vec![package]);
|
||||
}
|
||||
|
@ -248,21 +248,21 @@ fn engage_aggregator<'a>(
|
|||
print_warning("See `--help sync` or the pacwrap(1) man page for further information.");
|
||||
}
|
||||
|
||||
if create_targets.len() > 0 || init {
|
||||
if !create_targets.is_empty() || init {
|
||||
if flags.intersects(TransactionFlags::PREVIEW) {
|
||||
err!(ErrorKind::Message("Container creation cannot be previewed."))?;
|
||||
}
|
||||
|
||||
flags = flags | TransactionFlags::CREATE | TransactionFlags::FORCE_DATABASE;
|
||||
instantiate_trust()?;
|
||||
instantiate(&mut cache, lock, log, &action_type, create_targets)?;
|
||||
instantiate(cache, lock, log, &action_type, create_targets)?;
|
||||
}
|
||||
|
||||
Ok(TransactionAggregator::new(cache, log, action_type)
|
||||
TransactionAggregator::new(cache, log, action_type)
|
||||
.assert_lock(lock)?
|
||||
.target(acquire_targets(cache, &flags, targets)?)
|
||||
.queue(queue)
|
||||
.flag(flags)
|
||||
.progress()
|
||||
.aggregate()?)
|
||||
.aggregate()
|
||||
}
|
||||
|
|
|
@ -38,7 +38,7 @@ pub mod list;
|
|||
mod edit;
|
||||
mod symlink;
|
||||
|
||||
const GIO: &'static str = "gio";
|
||||
const GIO: &str = "gio";
|
||||
|
||||
pub fn engage_utility(args: &mut Arguments) -> Result<()> {
|
||||
match args.next().unwrap_or_default() {
|
||||
|
|
|
@ -83,7 +83,7 @@ pub fn remove_containers(args: &mut Arguments) -> Result<()> {
|
|||
|
||||
if instances.len() != targets.len() {
|
||||
for target in &targets {
|
||||
if !instances.contains(&target) {
|
||||
if !instances.contains(target) {
|
||||
err!(ErrorKind::InstanceNotFound(target.to_string()))?;
|
||||
}
|
||||
}
|
||||
|
@ -91,7 +91,7 @@ pub fn remove_containers(args: &mut Arguments) -> Result<()> {
|
|||
|
||||
let lock = Lock::new().lock()?;
|
||||
|
||||
if let (true, _) | (_, Ok(_)) = (no_confirm, prompt_targets(&instances, "Delete containers?", false)) {
|
||||
if let (true, _) | (_, true) = (no_confirm, prompt_targets(&instances, "Delete containers?", false)) {
|
||||
if let Err(err) = delete_roots(&cache, &lock, &mut logger, &instances, force) {
|
||||
err.error();
|
||||
}
|
||||
|
@ -100,18 +100,12 @@ pub fn remove_containers(args: &mut Arguments) -> Result<()> {
|
|||
lock.unlock()
|
||||
}
|
||||
|
||||
pub fn delete_roots(
|
||||
cache: &ContainerCache<'_>,
|
||||
lock: &Lock,
|
||||
logger: &mut Logger,
|
||||
targets: &Vec<&str>,
|
||||
force: bool,
|
||||
) -> Result<()> {
|
||||
let process = process::list(&cache)?;
|
||||
let processes = process.filter_by_target(&targets);
|
||||
let containers = cache.filter_target_handle(&targets, vec![]);
|
||||
pub fn delete_roots(cache: &ContainerCache<'_>, lock: &Lock, logger: &mut Logger, targets: &[&str], force: bool) -> Result<()> {
|
||||
let process = process::list(cache)?;
|
||||
let processes = process.filter_by_target(targets);
|
||||
let containers = cache.filter_target_handle(targets, vec![]);
|
||||
|
||||
if processes.len() > 0 && !force {
|
||||
if !processes.is_empty() && !force {
|
||||
for process in processes {
|
||||
err!(DeleteError::ContainerRunning(process.instance().to_string()))?;
|
||||
}
|
||||
|
|
|
@ -39,7 +39,7 @@ pub fn file(args: &mut Arguments) -> Result<()> {
|
|||
Operand::Short('l') | Operand::Long("list") | Operand::Value("ls") => list_desktop_entries(args),
|
||||
Operand::Short('r') | Operand::Long("remove") | Operand::Value("rm") => remove_desktop_entry(args),
|
||||
Operand::Short('c') | Operand::Long("create") | Operand::Value("create") => create_desktop_entry(args),
|
||||
_ => return args.invalid_operand(),
|
||||
_ => args.invalid_operand(),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -50,7 +50,7 @@ fn list_desktop_entries(args: &mut Arguments) -> Result<()> {
|
|||
Ok(instance) => (false, format!("{}/usr/share/applications", provide_handle(instance)?.vars().root())),
|
||||
Err(_) => (true, format!("{}/.local/share/applications", *HOME)),
|
||||
};
|
||||
let dir = read_dir(&app_dir).prepend_io(|| app_dir.into())?;
|
||||
let dir = read_dir(app_dir).prepend_io(|| app_dir.into())?;
|
||||
|
||||
for entry in dir {
|
||||
if let Some(file) = entry.prepend(|| format!("Failure acquiring entry in '{app_dir}'"))?.file_name().to_str() {
|
||||
|
@ -69,7 +69,7 @@ fn list_desktop_entries(args: &mut Arguments) -> Result<()> {
|
|||
fn create_desktop_entry(args: &mut Arguments) -> Result<()> {
|
||||
let target = args.target()?;
|
||||
let app_dir = &format!("{}/usr/share/applications", provide_handle(target)?.vars().root());
|
||||
let dir = read_dir(&app_dir).prepend_io(|| app_dir.into())?;
|
||||
let dir = read_dir(app_dir).prepend_io(|| app_dir.into())?;
|
||||
let name = &match args.next().unwrap_or_default() {
|
||||
Operand::Value(val) | Operand::ShortPos(_, val) | Operand::LongPos(_, val) => val,
|
||||
_ => return args.invalid_operand(),
|
||||
|
@ -102,11 +102,11 @@ fn create_desktop_entry(args: &mut Arguments) -> Result<()> {
|
|||
.prepend_io(|| desktop_file.into())?;
|
||||
contents = Regex::new("Exec=*")
|
||||
.unwrap()
|
||||
.replace_all(&mut contents, format!("Exec=pacwrap run {} ", target))
|
||||
.replace_all(&contents, format!("Exec=pacwrap run {} ", target))
|
||||
.to_string();
|
||||
|
||||
let desktop_file = &format!("{}/.local/share/applications/pacwrap.{}", *HOME, file_name);
|
||||
let mut output = File::create(&desktop_file).prepend_io(|| desktop_file.into())?;
|
||||
let mut output = File::create(desktop_file).prepend_io(|| desktop_file.into())?;
|
||||
|
||||
write!(output, "{}", contents).prepend_io(|| desktop_file.into())?;
|
||||
eprintln!("{} Created '{}'.", *ARROW_GREEN, file_name);
|
||||
|
@ -115,7 +115,7 @@ fn create_desktop_entry(args: &mut Arguments) -> Result<()> {
|
|||
|
||||
fn remove_desktop_entry(args: &mut Arguments) -> Result<()> {
|
||||
let app_dir = &format!("{}/.local/share/applications", *HOME);
|
||||
let dir = read_dir(&app_dir).prepend_io(|| app_dir.into())?;
|
||||
let dir = read_dir(app_dir).prepend_io(|| app_dir.into())?;
|
||||
let name = &match args.next().unwrap_or_default() {
|
||||
Operand::Value(val) | Operand::ShortPos(_, val) | Operand::LongPos(_, val) => val,
|
||||
_ => return args.invalid_operand(),
|
||||
|
@ -141,7 +141,7 @@ fn remove_desktop_entry(args: &mut Arguments) -> Result<()> {
|
|||
};
|
||||
let desktop_file = &format!("{}/.local/share/applications/{}", *HOME, file_name);
|
||||
|
||||
remove_file(&desktop_file).prepend_io(|| desktop_file.into())?;
|
||||
remove_file(desktop_file).prepend_io(|| desktop_file.into())?;
|
||||
eprintln!("{} Removed '{file_name}'.", *ARROW_GREEN);
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
@ -146,7 +146,7 @@ fn edit_file(file: &str, temporary_file: &str, lock: Option<&Lock>, edit: bool)
|
|||
}
|
||||
|
||||
fn hash_file(file_path: &str) -> Result<Vec<u8>> {
|
||||
let mut file = File::open(&file_path).prepend_io(|| file_path.into())?;
|
||||
let mut file = File::open(file_path).prepend_io(|| file_path.into())?;
|
||||
let mut hasher = Sha256::new();
|
||||
|
||||
copy_io(&mut file, &mut hasher).prepend_io(|| file_path.into())?;
|
||||
|
|
|
@ -65,14 +65,14 @@ impl Hash for Display {
|
|||
|
||||
impl PartialEq for Display {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
match (self, other) {
|
||||
(Self::Summary(_), Self::Summary(_)) => true,
|
||||
(Self::Total(_), Self::Total(_)) => true,
|
||||
(Self::Organic(_), Self::Organic(_)) => true,
|
||||
(Self::Name, Self::Name) => true,
|
||||
(Self::Type, Self::Type) => true,
|
||||
_ => false,
|
||||
}
|
||||
matches!(
|
||||
(self, other),
|
||||
(Self::Summary(_), Self::Summary(_))
|
||||
| (Self::Total(_), Self::Total(_))
|
||||
| (Self::Organic(_), Self::Organic(_))
|
||||
| (Self::Name, Self::Name)
|
||||
| (Self::Type, Self::Type)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -101,7 +101,7 @@ fn parse_arguments(args: &mut Arguments) -> Result<(bool, IndexSet<Display>)> {
|
|||
}
|
||||
}
|
||||
|
||||
Ok((vec.len() > 2, IndexSet::from_iter(vec.into_iter())))
|
||||
Ok((vec.len() > 2, IndexSet::from_iter(vec)))
|
||||
}
|
||||
|
||||
pub fn list_containers(args: &mut Arguments) -> Result<()> {
|
||||
|
@ -179,7 +179,7 @@ pub fn list_containers(args: &mut Arguments) -> Result<()> {
|
|||
table.insert(row);
|
||||
}
|
||||
|
||||
Ok(if let Some(sum) = table_type.get(&Display::Summary(None)) {
|
||||
if let Some(sum) = table_type.get(&Display::Summary(None)) {
|
||||
let mut max_len = 0;
|
||||
let difference = total_size - actual_size;
|
||||
let equation = match sum.bytes() {
|
||||
|
@ -213,7 +213,8 @@ pub fn list_containers(args: &mut Arguments) -> Result<()> {
|
|||
)
|
||||
} else {
|
||||
println!("{}", table.build()?)
|
||||
})
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
//There might be some value in threading this routine in future.
|
||||
|
@ -222,7 +223,7 @@ fn directory_size(dir: &str) -> Result<(i64, i64, i64)> {
|
|||
let mut total = 0;
|
||||
let mut unique = 0;
|
||||
|
||||
for entry in read_dir(&dir).prepend_io(|| dir.into())? {
|
||||
for entry in read_dir(dir).prepend_io(|| dir.into())? {
|
||||
let entry = entry.prepend(|| format!("Failure acquiring entry in '{dir}'"))?;
|
||||
let name = entry.file_name().to_str().unwrap().to_string();
|
||||
let meta = entry.metadata().prepend(|| format!("Failure to acquire metadata in '{dir}/{name}'"))?;
|
||||
|
@ -237,13 +238,11 @@ fn directory_size(dir: &str) -> Result<(i64, i64, i64)> {
|
|||
len += l;
|
||||
unique += u;
|
||||
total += t;
|
||||
} else if meta.nlink() == 1 {
|
||||
unique += meta.len() as i64;
|
||||
} else {
|
||||
if meta.nlink() == 1 {
|
||||
unique += meta.len() as i64;
|
||||
} else {
|
||||
len += (meta.len() / meta.nlink()) as i64;
|
||||
total += meta.len() as i64;
|
||||
}
|
||||
len += (meta.len() / meta.nlink()) as i64;
|
||||
total += meta.len() as i64;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -36,9 +36,9 @@ pub fn link(args: &mut Arguments) -> Result<()> {
|
|||
while let Some(arg) = args.next() {
|
||||
match arg {
|
||||
Operand::Value(val) | Operand::ShortPos(_, val) | Operand::LongPos(_, val) =>
|
||||
if let None = dest {
|
||||
if dest.is_none() {
|
||||
dest = Some(val);
|
||||
} else if let None = src {
|
||||
} else if src.is_none() {
|
||||
src = Some(val);
|
||||
} else {
|
||||
args.invalid_operand()?;
|
||||
|
|
Loading…
Add table
Reference in a new issue