Compare commits

..
3 Commits
34 changed files with 560 additions and 1198 deletions
+5
View File
@@ -0,0 +1,5 @@
[registry]
default = "gitea"
[registries.gitea]
index = "sparse+https://git.tcraft.me/api/packages/neo/cargo/" # sparse index
Generated
+49 -4
View File
@@ -2,6 +2,15 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "aho-corasick"
version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
dependencies = [
"memchr",
]
[[package]]
name = "anstream"
version = "1.0.0"
@@ -54,9 +63,9 @@ dependencies = [
[[package]]
name = "clap"
version = "4.6.4"
version = "4.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d91e0c145792ef73a6ad36d27c75ac09f1832222a3c209689d90f534685ee5b7"
checksum = "301b56658598e48f3648647ac6fc887be7e7108eddfa4e9b63fcf3ec58c0cadf"
dependencies = [
"clap_builder",
"clap_derive",
@@ -64,9 +73,9 @@ dependencies = [
[[package]]
name = "clap_builder"
version = "4.6.2"
version = "4.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f09628afdcc538b57f3c6341e9c8e9970f18e4a481690a64974d7023bd33548b"
checksum = "94a65403d1a1bd28f7dc68eb8506e8874808ee5eecb59298de588e2e1407a078"
dependencies = [
"anstream",
"anstyle",
@@ -116,6 +125,12 @@ version = "0.4.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
@@ -140,12 +155,42 @@ dependencies = [
"proc-macro2",
]
[[package]]
name = "regex"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fcfdb36bda0c880c5931cdc7a2bcdc8ba4556847b9d912bca70bc94708711ad"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "ruport"
version = "0.1.0"
dependencies = [
"clap",
"log",
"regex",
]
[[package]]
+84 -12
View File
@@ -4,39 +4,111 @@ version = "0.1.0"
edition = "2024"
[features]
default = []
drop-in = []
default = []
[lib]
name = "portage"
path = "libportage/lib.rs"
crate-type = ["rlib"]
[[bin]]
name = "ruport"
path = "src/main.rs"
[[bin]]
name = "ebuild"
path = "src/ebuild.rs"
required-features = ["drop-in"]
[[bin]]
name = "egencache"
path = "src/egencache.rs"
required-features = ["drop-in"]
[[bin]]
name = "emerge"
path = "src/emerge.rs"
required-features = ["drop-in"]
[[bin]]
name = "emerge-webrsync"
path = "src/emerge-webrsync.rs"
required-features = ["drop-in"]
[[bin]]
name = "emirrordist"
path = "src/emirrordist"
required-features = ["drop-in"]
[[bin]]
name = "glsa-check"
path = "src/glsa-check.rs"
required-features = ["drop-in"]
[[bin]]
name = "gpkg-sign"
path = "src/gpkg-sign"
required-features = ["drop-in"]
[[bin]]
name = "portageq"
path = "src/portageq.rs"
required-features = ["drop-in"]
[[bin]]
name = "quickpkg"
path = "src/quickpkg.rs"
required-features = ["drop-in"]
[lib]
name = "portage"
path = "libportage/lib.rs"
crate-type = ["rlib"]
# gehen nach ${PREFIX}/sbin
[[bin]]
name = "archive-conf"
path = "src/archive-conf.rs"
required-features = ["drop-in"]
[[bin]]
name = "dispatch-conf"
path = "src/dispatch-conf.rs"
required-features = ["drop-in"]
[[bin]]
name = "emaint"
path = "src/emaint.rs"
required-features = ["drop-in"]
[[bin]]
name = "ruport"
path = "src/main.rs"
name = "env-update"
path = "src/env-update.rs"
required-features = ["drop-in"]
[[bin]]
name = "etc-update"
path = "src/etc-update.rs"
required-features = ["drop-in"]
[[bin]]
name = "fixpackages"
path = "src/fixpackages.rs"
required-features = ["drop-in"]
[[bin]]
name = "regenworld"
path = "src/regendworld.rs"
required-features = ["drop-in"]
[dependencies]
clap = {version="4.6", features=["derive"]}
clap = { version="4.6", features=["derive"] }
log = "0.4.33"
regex = { version="1.13" }
[profile.dev]
opt-level = "s"
debug = true
strip = false
lto = false
[profile.release]
opt-level = 'z'
lto = true
strip = true
panic = "abort"
opt-level = "z"
lto = "full"
strip = true
-21
View File
@@ -1,21 +0,0 @@
use std::io::Result;
use std::process::exit;
use portage::util::logger::logger_init;
use portage::config::PortageConfig;
fn main() -> Result<()> {
match logger_init(log::LevelFilter::Debug) {
Ok(_) => {},
Err(e) => {
eprintln!("{e}");
exit(-1);
}
}
let cfg = PortageConfig::new()?;
cfg.display_config();
Ok(())
}
-16
View File
@@ -1,16 +0,0 @@
use std::io::Result;
use portage::repository::RepoConfig;
fn main() -> Result<()> {
// the repo configuration
let mut repos = RepoConfig::new()?;
// read the config
repos.read_config()?;
// print repo config
repos.print_repos()?;
Ok(())
}
+50
View File
@@ -0,0 +1,50 @@
use std::fs::File;
use std::io::{Result,BufReader,Read,Seek,SeekFrom};
use std::os::unix::ffi::OsStrExt;
use std::path::PathBuf;
use log::warn;
use crate::consts::GentooBinpkgFormats;
fn get_binpkg_format(binpkg: PathBuf, check_file: Option<bool>, remote: Option<bool>) -> Option<GentooBinpkgFormats> {
let check_file = check_file.unwrap_or(false);
let remote = remote.unwrap_or(false);
let extension = &binpkg.extension().ok_or(0).unwrap();
let extension = extension.to_str().unwrap();
let file_ext_format = if GentooBinpkgFormats::XPAK.get_extension().unwrap().contains(&extension) {
Some(GentooBinpkgFormats::XPAK)
} else if GentooBinpkgFormats::GPKG.get_extension().unwrap().contains(&extension) {
Some(GentooBinpkgFormats::GPKG)
} else {
None
};
let mut file_format: Option<GentooBinpkgFormats> = if file_ext_format.is_some() && !check_file {
file_ext_format
} else {
let binpkg_file = File::open(&binpkg).expect(format!("unable to open binary file {}", &binpkg.display()).as_str());
let mut reader = BufReader::new(binpkg_file);
let mut buf = [0;100];
let _ = reader.read(&mut buf).expect(format!("cannot read file: {}", &binpkg.display()).as_str());
if buf.starts_with(b"/gpkg-1\x00") {
Some(GentooBinpkgFormats::GPKG)
} else {
reader.seek(SeekFrom::End(-16));
let mut tail = [0;16];
reader.read_exact(&mut tail);
if tail[0..8].starts_with(b"XPAKSTOP") && tail[12..16].ends_with(b"STOP") {
Some(GentooBinpkgFormats::XPAK)
} else {
None
}
}
};
if file_format.is_some() && file_ext_format.unwrap() != file_format.unwrap() {
warn!("File {} binpkg format mismatch, actial format: {}", binpkg.display(), file_format.unwrap());
}
return file_format;
}
-139
View File
@@ -1,139 +0,0 @@
use std::{fmt, path::{Path, PathBuf}};
mod ruport;
mod portage;
use ruport::RuportConfigProvider;
use portage::PortageConfigProvider;
use crate::features::Features;
trait ConfigProvider {
fn new() -> Result<Self, ConfigError> where Self: Sized;
fn parse_global(&mut self) -> Result<(), std::io::Error>;
// getter
fn get_elog(&self) -> ELog;
fn get_features(&self) -> Vec<Features>;
// display functions
fn display_cflags(&self);
}
#[derive(Debug)]
enum ConfigError {
PortageConfigNotFound,
RuportConfigNotFound,
}
impl fmt::Display for ConfigError {
fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
todo!()
}
}
// portage paths
pub(crate) struct PortagePaths {
distdir: PathBuf,
pkgdir: PathBuf,
rpmdir: PathBuf,
tmpdir: PathBuf,
}
// elog classes
#[derive(Debug,Clone)]
enum ELogClasses {
Log,
Warn,
Error,
}
impl ELogClasses {
pub fn from(line: String) -> Vec<Self> {
let mut ret = Vec::new();
let line = line.trim_matches('"')
.split_whitespace()
.collect::<Vec<_>>();
for v in line {
match v {
"log" => ret.push(ELogClasses::Log),
"warn" => ret.push(ELogClasses::Warn),
"error" => ret.push(ELogClasses::Error),
_ => eprintln!("unknown ELog Class: {v}"),
}
}
ret
}
}
#[derive(Debug,Clone)]
pub(crate) struct ELog {
classes: Vec<ELogClasses>,
system: String,
mail_uri: String,
mail_subject: String,
mail_from: String,
}
impl ELog {
pub fn default() -> Self {
Self {
classes: vec![ELogClasses::Log, ELogClasses::Warn, ELogClasses::Error],
system: "save_summary:log,warn,error,qa echo".to_string(),
mail_uri: "root".to_string(),
mail_subject: "[portage] ebuild log for {pkg} on {host}".to_string(),
mail_from: "portage@localhost".to_string(),
}
}
}
/// This struct holds the current configuration.
pub struct PortageConfig {
provider: Box<dyn ConfigProvider>,
elog: ELog,
features: Vec<Features>,
}
impl PortageConfig {
pub fn new() -> Result<Self, std::io::Error> {
let mut p: Box<dyn ConfigProvider> = match PortageConfigProvider::new() {
Ok(prov) => Box::new(prov),
Err(_) => {
match RuportConfigProvider::new() {
Ok(prov) => Box::new(prov),
Err(_) => Box::new(RuportConfigProvider::default()),
}
}
};
match p.parse_global() {
Ok(r) => {},
Err(e) => {},
};
let elog = p.get_elog();
let features = p.get_features();
Ok(Self {
provider: p,
elog: elog,
features: features,
})
}
pub fn display_config(&self) {
self.provider.display_cflags();
// display active features
println!("Active Features: {:?}", self.features);
// print elog information
println!("ELOG: ");
println!("\tClasses: {:?}", self.elog.classes);
println!("\tSystem: {}", self.elog.system);
println!("\tMail Subject: {}", self.elog.mail_subject);
println!("\tMail From: ({}) {}", self.elog.mail_uri, self.elog.mail_from);
}
}
-314
View File
@@ -1,314 +0,0 @@
use std::{collections::HashMap, fs::File, io::{BufRead, BufReader, Error, ErrorKind}, path::{Path, PathBuf}};
use log::debug;
use crate::features::Features;
use super::ConfigProvider;
use super::ConfigError;
use super::PortagePaths;
use super::{ELog,ELogClasses};
/// The Portage config provider.
///
/// It is the default configuration in "normal" gentoo system. Per default,
/// Ruport try to read this configuration first.
pub(crate) struct PortageConfigProvider{
global_path: PathBuf,
compile_flags: HashMap<String, String>,
features: Vec<Features>,
mirrors: Vec<String>,
paths: PortagePaths,
elog: ELog,
}
impl PortageConfigProvider {
fn validate_data(&mut self, data: Vec<(String,String)>) -> std::io::Result<()> {
for (key,value) in data {
match key.as_str() {
"CFLAGS" => self.compile_flags.insert("CFLAGS".to_string(), value),
"CXXFLAGS" => self.compile_flags.insert("CXXFLAGS".to_string(), value),
"FFLAGS" => self.compile_flags.insert("FFLAGS".to_string(), value),
"FCFLAGS" => self.compile_flags.insert("FCFLAGS".to_string(), value),
"LDFLAGS" => self.compile_flags.insert("LDFLAGS".to_string(), value),
"GENTOO_MIRRORS" => {
let mirrors: Vec<&str> = value.split_whitespace().collect();
for mirror in mirrors {
self.mirrors.push(mirror.to_string());
}
},
"FEATURES" => {
let features: Vec<&str> = value.split_whitespace().collect();
for feature in features {
let f = Features::from(feature);
if f.is_some(){
self.features.push(f.unwrap());
}
}
},
"DISTDIR" => {
let dir = value.trim_matches('"');
self.paths.distdir = PathBuf::from(dir);
},
"PKGDIR" => {
let dir = value.trim_matches('"');
self.paths.pkgdir = PathBuf::from(dir);
},
"RPMDIR" => {
let dir = value.trim_matches('"');
self.paths.rpmdir = PathBuf::from(dir);
},
"PORTAGE_TMPDIR" => {
let dir = value.trim_matches('"');
self.paths.tmpdir = PathBuf::from(dir);
},
// ELog configuration
"PORTAGE_ELOG_CLASSES" => {
let classes = value.trim_matches('"')
.split_whitespace()
.collect::<Vec<_>>();
for class in classes {
let c = match class {
"log" => ELogClasses::Log,
"warn" => ELogClasses::Warn,
"error" => ELogClasses::Error,
};
self.elog.classes.push(c);
}
},
"PORTAGE_ELOG_SYSTEM" => self.elog.system = value,
"PORTAGE_ELOG_MAILURI" => self.elog.mail_uri = value,
"PORTAGE_ELOG_MAILSUBJECT" => {
let subject = value
.replace("\\${PACKAGE", "{pkg}")
.replace("\\${HOST}", "{host}");
self.elog.mail_subject = subject;
},
"PORTAGE_ELOG_MAILFROM" => self.elog.mail_from = value,
&_ => todo!(),
};
}
Ok(())
}
}
impl ConfigProvider for PortageConfigProvider {
fn new() -> Result<Self, ConfigError> {
let global_path = Path::new("/usr/share/portage/config/make.globals");
if !global_path.exists() {
return Err(ConfigError::PortageConfigNotFound);
}
log::debug!("using portage config");
Ok(Self{
global_path: global_path.to_path_buf(),
compile_flags: HashMap::new(),
features: Vec::new(),
mirrors: Vec::new(),
paths: PortagePaths {
distdir: PathBuf::new(),
pkgdir: PathBuf::new(),
rpmdir: PathBuf::new(),
tmpdir: PathBuf::new(),
},
elog: ELog::default(),
})
}
fn parse_global(&mut self) -> Result<(), std::io::Error> {
let file = File::open(self.global_path.clone())?;
let reader = BufReader::new(file);
let mut data: Vec<(String, String)> = Vec::new();
let mut current_key: Option<String> = None;
let mut current_value = String::new();
for line in reader.lines() {
let line = line?;
let line = line.trim();
// ignore empty line or comments
if line.is_empty() || line.starts_with('#') {
continue;
}
// multiple line
if current_key.is_some() {
current_value.push(' ');
current_value.push_str(&line.to_string());
}
if let Some(index) = line.find('=') {
let key = line[..index].trim().to_string();
let value = line[index+1..].trim();
if value.starts_with('"') && !value.ends_with('"') {
current_key = Some(key);
current_value = value.to_string();
} else {
data.push((key, current_value.to_string()));
current_value.clear();
}
}
}
self.validate_data(data)?;
Ok(())
}
// fn eparse_global(&mut self) -> std::io::Result<()> {
// let file = File::open(self.global_path.clone())?;
// let reader = BufReader::new(file);
// let mut data: HashMap<String, String> = HashMap::new();
// let mut current_key: Option<String> = None;
// let mut current_value = String::new();
// for line in reader.lines() {
// let line = line.unwrap();
// let line = line.trim();
// // ignore empty line or comments
// if line.is_empty() || line.starts_with('#') {
// continue;
// }
// // multiline option
// if current_key.is_some() {
// current_value.push(' ');
// current_value.push_str(line);
// if line.ends_with('"') {
// data.insert(
// current_key.take().unwrap(),
// current_value.clone(),
// );
// current_value.clear();
// }
// continue;
// }
// if let Some(index) = line.find('=') {
// let key = line[..index].trim().to_string();
// let value = line[index+1..].trim();
// if value.starts_with('"') && ! value.ends_with('"') {
// current_key = Some(key);
// current_value = value.to_string();
// } else {
// if current_value.contains("${*}") {
// }
// data.insert(key, value.to_string());
// }
// // data.insert(
// // key.to_string(),
// // value.to_string()
// // );
// }
// }
// // now get the values from the buffer
// let cflags = data.get("CFLAGS");
// if cflags.is_some() {
// self.compile_flags.insert("CFLAGS".to_string(), cflags.unwrap().to_string());
// }
// let cxxflags = data.get("CXXFLAGS");
// if cxxflags.is_some() {
// self.compile_flags.insert("CXXFLAGS".to_string(), cxxflags.unwrap().to_string());
// }
// let ldflags = data.get("LDFLAGS");
// if ldflags.is_some() {
// self.compile_flags.insert("LDFLAGS".to_string(), ldflags.unwrap().to_string());
// }
// let fflags = data.get("FFLAGS");
// if fflags.is_some() {
// self.compile_flags.insert("FFLAGS".to_string(), fflags.unwrap().to_string());
// }
// let fcflags = data.get("FCFLAGS");
// if fcflags.is_some() {
// self.compile_flags.insert("FCFLAGS".to_string(), fcflags.unwrap().to_string());
// }
// let mirrors = data.get("GENTOO_MIRRORS");
// let mirrors: Vec<&str> = mirrors.unwrap().split_whitespace().collect();
// for mirror in mirrors {
// self.mirrors.push(mirror.to_string());
// }
// let features = data.get("FEATURES");
// if features.is_some() {
// self.features = Features::from_line(features.unwrap().to_string())
// }
// let distdir = data.get("DISTDIR");
// let pkgdir = data.get("PKGDIR");
// let rpmdir = data.get("RPMDIR");
// let tmpdir = data.get("PORTAGE_TMPDIR");
// if distdir.is_some() {
// self.paths.distdir = PathBuf::from(distdir.unwrap().to_string());
// }
// if pkgdir.is_some() {
// self.paths.pkgdir = PathBuf::from(pkgdir.unwrap().to_string());
// }
// if rpmdir.is_some() {
// self.paths.rpmdir = PathBuf::from(rpmdir.unwrap().to_string());
// }
// if tmpdir.is_some() {
// self.paths.tmpdir = PathBuf::from(tmpdir.unwrap().to_string())
// }
// // elog settings
// let elog_classes = data.get("PORTAGE_ELOG_CLASSES");
// let elog_system = data.get("PORTAGE_ELOG_SYSTEM");
// let elog_mailuri = data.get("PORTAGE_ELOG_MAILURI");
// let elog_mailsubject = data.get("PORTAGE_ELOG_MAILSUBJECT");
// let elog_mailfrom = data.get("PORTAGE_ELOG_MAILFROM");
// if elog_classes.is_some() {
// self.elog.classes = ELogClasses::from(elog_classes.unwrap().to_string());
// }
// if elog_system.is_some() {
// self.elog.system = elog_system.unwrap().to_string();
// }
// if elog_mailuri.is_some() {
// self.elog.mail_uri = elog_mailuri.unwrap().to_string();
// }
// if elog_mailsubject.is_some() {
// let subject = elog_mailsubject.unwrap().to_string();
// let _ = subject.replace("\\${PACKAGE}", "{pkg}")
// .replace("\\${HOST}", "{host}");
// self.elog.mail_subject = subject;
// }
// if elog_mailfrom.is_some() {
// self.elog.mail_from = elog_mailfrom.unwrap().to_string();
// }
// Ok(())
// }
fn get_elog(&self) -> ELog {
self.elog.clone()
}
fn get_features(&self) -> Vec<Features> {
self.features.clone()
}
fn display_cflags(&self) {
println!("Compiler Flags:");
for (k,v) in self.compile_flags.clone() {
let v = v.trim_matches('"');
println!("\t{k} = {v}");
}
}
}
-61
View File
@@ -1,61 +0,0 @@
use std::path::Path;
use std::path::PathBuf;
use crate::features::Features;
use super::ConfigProvider;
use super::ConfigError;
use super::{ELog,ELogClasses};
/// The Ruport config provider.
///
/// It is used, then there is no current portage configuration available.
/// It is also capable of, creating default configs, useful for embedded
/// systems.
pub(crate) struct RuportConfigProvider{
global_path: PathBuf,
elog: ELog,
features: Vec<Features>,
}
impl RuportConfigProvider {
pub fn default() -> Self {
let elog = ELog::default();
Self {
global_path: PathBuf::from("/usr/share/ruport/config.ini"),
elog,
features: Vec::new(),
}
}
}
impl ConfigProvider for RuportConfigProvider {
fn new() -> Result<Self, ConfigError> {
let global_path = Path::new("/usr/share/ruport/config.ini");
if !global_path.exists() {
return Err(ConfigError::RuportConfigNotFound);
}
log::debug!("using ruport config.");
Ok(Self{
global_path: global_path.to_path_buf(),
elog: ELog::default(),
features: Vec::new(),
})
}
fn parse_global(&mut self) -> std::io::Result<()> {
Ok(())
}
fn get_elog(&self) -> ELog {
self.elog.clone()
}
fn get_features(&self) -> Vec<crate::features::Features> {
self.features.clone()
}
fn display_cflags(&self) {
}
}
+273
View File
@@ -0,0 +1,273 @@
use std::ffi::OsStr;
use std::path::PathBuf;
use std::sync::LazyLock;
use std::io::Result;
use crate::types::Atom;
/**
* There are two types of variables here whcih can easily be confused,
* resulting in arbitrary bugs, mainly exposed with an offset
* installation (Prefix). The two types relate to the useage of
* config_root or target_root.
* The first, config_root (PORTAGE_CONFIGROOT), can be a path somewhere,
* from which all derived paths need to be relative (e.g. USER_CONFIG_PATH)
* without EPREFIX prepended in Prefix. This means
* config_root cann for instance be set to "$HOME/my/config". Obviously,
* in such case it is not appropriate to prepend EPREFIX to derived
* constants. The default value of config_root is EPREFIX (in non-Prefix
* the empty String) -- overriding the value loses the EPREFXXI as one
* would expect.
* Second here is target_root (ROOT) which is used to install somewhere
* completely else, in Prefix of limited use. Because this is an offset
* always given, the EPREFIX should always be applied in it, hence the
* code always prefixes them with ERROT.
* The variables in this file are grouped by config_root, target_root.
*/
// variables used with config_root (these need to be relative)
static USER_CONFIG_PATH: LazyLock<PathBuf> =
LazyLock::new(|| PathBuf::from("etc/portage"));
static BINREPOS_CONF_FILE: LazyLock<PathBuf> =
LazyLock::new(|| USER_CONFIG_PATH.join("binrepos.conf"));
static MAKE_CONF_FILE: LazyLock<PathBuf> =
LazyLock::new(|| USER_CONFIG_PATH.join("make.conf"));
static MODULES_FILE_PATH: LazyLock<PathBuf> =
LazyLock::new(|| USER_CONFIG_PATH.join("modules"));
static CUSTOM_PROFILE_PATH: LazyLock<PathBuf> =
LazyLock::new(|| USER_CONFIG_PATH.join("profile"));
static USER_VIRTUAL_FILE: LazyLock<PathBuf> =
LazyLock::new(|| USER_CONFIG_PATH.join("virtuals"));
static EBUILD_SH_ENV_FILE: LazyLock<PathBuf> =
LazyLock::new(|| USER_CONFIG_PATH.join("bashrc"));
static EBUILD_SH_ENV_DIR: LazyLock<PathBuf> =
LazyLock::new(|| USER_CONFIG_PATH.join("env"));
static CUSTOM_MIRRORS_FILE: LazyLock<PathBuf> =
LazyLock::new(|| USER_CONFIG_PATH.join("mirrors"));
static COLOR_MAP_FILE: LazyLock<PathBuf> =
LazyLock::new(|| USER_CONFIG_PATH.join("color.map"));
static PROFILE_PATH: LazyLock<PathBuf> =
LazyLock::new(|| USER_CONFIG_PATH.join("make.profile"));
static MAKE_DEFAULTS_FILE: LazyLock<PathBuf> =
LazyLock::new(|| PROFILE_PATH.join("make.defaults"));
static DEPRECATED_PROFILE_FILE: LazyLock<PathBuf> =
LazyLock::new(|| PROFILE_PATH.join("deprecated"));
// variables used with targetroot (these need to be absolute, but not
// have a leading '/' since they are used directly with path.join on EROOT)
static VDB_PATH: LazyLock<PathBuf> =
LazyLock::new(|| PathBuf::from("var/db/pkg"));
static CACHE_PATH: LazyLock<PathBuf> =
LazyLock::new(|| PathBuf::from("var/cache/edb"));
static PRIVATE_PATH: LazyLock<PathBuf> =
LazyLock::new(|| PathBuf::from("var/lib/portage"));
static WORLD_FILE: LazyLock<PathBuf> =
LazyLock::new(|| PRIVATE_PATH.join("world"));
static WORLD_SETS_FILE: LazyLock<PathBuf> =
LazyLock::new(|| PRIVATE_PATH.join("world_sets"));
static CONFIG_MEMORY_FILE: LazyLock<PathBuf> =
LazyLock::new(|| PRIVATE_PATH.join("config"));
static REPO_REVISIONS: LazyLock<PathBuf> =
LazyLock::new(|| PRIVATE_PATH.join("repo_revisions"));
static NEWS_LIB_PATH: LazyLock<PathBuf> =
LazyLock::new(|| PathBuf::from("var/lib/gentoo"));
/* these variables get EPREFIX prepended automagically when they are
* translated into their lowercase variants */
static DEPCACHE_PATH: LazyLock<PathBuf> =
LazyLock::new(|| CACHE_PATH.join("dep"));
static PORTAGE_PACKAGE_ATOM: LazyLock<Atom> = LazyLock::new(|| Atom::new("sys-apps/portage"));
static LIBC_PACKAGE_ATOM: LazyLock<Atom> = LazyLock::new(|| Atom::new("virtual/libc"));
static OS_HEADERS_PACKAGE_ATOM: LazyLock<Atom> = LazyLock::new(|| Atom::new("virtual/os-headers"));
static CVS_PACKAGE_ATOM: LazyLock<Atom> = LazyLock::new(|| Atom::new("dev-vcs/cvs"));
static GIT_PACKAGE_ATOM: LazyLock<Atom> = LazyLock::new(|| Atom::new("dev-vcs/git"));
static HG_PACKAGE_ATOM: LazyLock<Atom> = LazyLock::new(|| Atom::new("dev-vcs/mercurial"));
static RSYNC_PACKAGE_ATOM: LazyLock<Atom> = LazyLock::new(|| Atom::new("net-misc/rsync"));
const INCREMENTALS: &'static [&'static str] = &[
"ACCEPT_KEYWORDS",
"CONFIG_PROTECT",
"CONFIG_PROTECT_MASK",
"ENV_UNSET",
"FEATURES",
"IUSE_IMPLICIT",
"PRELINK_PATH",
"PRELINK_PATH_MASK",
"PROFILE_ONLY_VARIABLES",
"USE",
"USE_EXPAND",
"USE_EXPAND_HIDDEN",
"USE_EXPAND_IMPLICIT",
"USE_EXPAND_UNPREFIXED",
];
const SUPPORTED_FEATURES: &'static [&'static str] = &[
"assume-digest",
"binpkg-docompress",
"binpkg-dostrip",
"binpkg-ignore-signature",
"binpkg-logs",
"binpkg-multi-instance",
"binpkg-request-signature",
"binpkg-signing",
"buildpkg",
"buildpkg-live",
"buildpkg-proactive",
"buildsyspkg",
"candy",
"case-insensitive-fs",
"ccache",
"chflags",
"clean-logs",
"collision-protect",
"compress-build-logs",
"compressdebug",
"compress-index",
"config-protect-if-modified",
"dedupdebug",
"digest",
"distcc",
"distlocks",
"downgrade-backup",
"ebuild-locks",
"fail-clean",
"fakeroot",
"fixlafiles",
"force-mirror",
"getbinpkg",
"gpg-keepalive",
"home-dir-template-copy",
"icecream",
"installsources",
"ipc-sandbox",
"jobserver-token",
"keeptemp",
"keepwork",
"lmirror",
"merge-sync",
"merge-wait",
"metadata-transfer",
"mirror",
"mount-sandbox",
"multilib-strict",
"network-sandbox",
"network-sandbox-proxy",
"news",
"noauto",
"noclean",
"nodoc",
"noinfo",
"noman",
"nostrip",
"notitles",
"packdebug",
"parallel-fetch",
"parallel-install",
"pid-sandbox",
"pkgdir-index-trusted",
"prelink-checksums",
"preserve-libs",
"protect-owned",
"python-trace",
"qa-unresolved-soname-deps",
"sandbox",
"selinux",
"sesandbox",
"sfperms",
"sign",
"skiprocheck",
"splitdebug",
"split-elog",
"split-log",
"strict",
"strict-keepdir",
"stricter",
"suidctl",
"test",
"test-fail-continue",
"unknown-features-filter",
"unknown-features-warn",
"unmerge-backup",
"unmerge-logs",
"unmerge-orphans",
"unprivileged",
"userfetch",
"userpriv",
"usersandbox",
"usersync",
"warn-on-large-env",
"webrsync-gpg",
"xattr",
];
const EAPI: usize = 9;
const HASHING_BLOCKSIZE: usize = 32768;
#[derive(Default)]
enum Manifest2HashDefaults {
#[default]
Blake2B,
SHA512,
}
const VCS_DIRS: &'static [&'static str] = &[
"CVS",
"RCS",
"SCCS",
".bzr",
".git",
".hg",
".svn"
];
const LIVE_ECLASS: &'static [&'static str] = &[
"bzr",
"cvs",
"darcs",
"git-2",
"git-r3",
"golang-vcs",
"mercurial",
"subversion",
];
enum BinpkgFormats {
Tar,
Rpm,
}
#[derive(Debug,Clone,Copy,Eq,PartialEq)]
pub(crate) enum GentooBinpkgFormats {
XPAK,
GPKG,
}
impl GentooBinpkgFormats {
pub fn to_str(self) -> &'static str {
match self {
Self::XPAK => "xpak",
Self::GPKG => "gpkg",
}
}
pub fn get_extension(&self) -> Result<Vec<&str>> {
match self {
Self::XPAK => return Ok(vec![".tbz2", ".xpak"]),
Self::GPKG => return Ok(vec![".gpkg.tar"]),
}
}
pub fn contains(&self, pat: &str) -> bool {
let extensions= self.get_extension().unwrap();
if extensions.contains(&pat) {
true
} else {
false
}
}
}
impl std::fmt::Display for GentooBinpkgFormats {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.to_str())
}
}
-230
View File
@@ -1,230 +0,0 @@
#[derive(Debug,Clone,Copy)]
pub enum Features {
AssumeDigests,
BinPkgDoCompress,
BinPkgDoStrip,
BinPkgIgnoreSignature,
BinPkgLogs,
BinPkgMultiInstance,
BinPkgRequestSignature,
BinPkgSigning,
BuildPkg,
BuildPkgLive,
BuildPkgProactive,
BuildSysPkg,
Candy,
CaseInsensistiveFs,
Ccache,
Chflags,
CleanLogs,
CollisionProtect,
CompressBuildLogs,
CompressDebug,
CompressIndex,
ConfigProtectIfModified,
DeDupDebug,
Digest,
DistCC,
DistLocks,
DowngradeBackup,
EbuildLocks,
FailClean,
FakeRoot,
FixLaFiles,
ForceMirror,
GetBinPkg,
GpgKeepAlive,
HomeDirTemplateCopy,
IceCream,
InstallSources,
IpcSandbox,
JobServerToken,
KeepTemp,
KeepWork,
LMirror,
MergeSync,
MergeWait,
MetadataTransfer,
Mirror,
MountSandbox,
MultilibStrict,
NetworkSandbox,
NetworkSandboxProxy,
News,
NoAuto,
NoClean,
NoDoc,
NoInfo,
NoMan,
NoStrip,
NoTitles,
PackDebug,
ParallelFetch,
ParallelInstall,
PidSandbox,
PkgdirIndexTrusted,
PrelinkChecksums,
PreserveLibs,
ProtectOwned,
PythonTrace,
QAUnresolvedSonameDeps,
Sandbox,
SeLinux,
SeSandbox,
SFPerms,
Sign,
SkipRoCheck,
SplitDebug,
SplitElog,
SplitLog,
Strict,
StrictKeepDir,
Stricter,
Suidctl,
Test,
TestFailContinue,
UnknownFeaturesFilter,
UnknownFeaturesWarn,
UnmergeBackup,
UnmergeLogs,
UnmergeOrphans,
Unprivileged,
UserFetch,
UserPriv,
UserSandbox,
UserSync,
WarnOnLargeEnv,
WebRsyncGpg,
XATTR,
}
impl Features {
pub fn from(val: &str) -> Option<Self> {
log::debug!("features val line: {val}");
match val {
"assume-digests" => Some(Self::AssumeDigests),
"binpkg-docompress" => Some(Self::BinPkgDoCompress),
"binpkg-dostrip" => Some(Self::BinPkgDoStrip),
"binpkg-ignore-signature" => Some(Self::BinPkgIgnoreSignature),
"binpkg-logs" => Some(Self::BinPkgLogs),
"binpkg-multi-instance" => Some(Self::BinPkgMultiInstance),
"binpkg-request-signature" => Some(Self::BinPkgRequestSignature),
"binpkg-signing" => Some(Self::BinPkgSigning),
"buildpkg" => Some(Self::BuildPkg),
"buildpkg-live" => Some(Self::BuildPkgLive),
"buildpkg-proactive" => Some(Self::BuildPkgProactive),
"buildsyspkg" => Some(Self::BuildSysPkg),
"candy" => Some(Self::Candy),
"case-insensistive-fs" => Some(Self::CaseInsensistiveFs),
"ccache" => Some(Self::Ccache),
"chflags" => Some(Self::Chflags),
"clean-logs" => Some(Self::CleanLogs),
"collision-protect" => Some(Self::CollisionProtect),
"compress-build-logs" => Some(Self::CompressBuildLogs),
"compressdebug" => Some(Self::CompressDebug),
"compress-index" => Some(Self::CompressIndex),
"config-protect-if-modified" => Some(Self::ConfigProtectIfModified),
"dedupdebug" => Some(Self::DeDupDebug),
"digest" => Some(Self::Digest),
"distcc" => Some(Self::DistCC),
"distlocks" => Some(Self::DistLocks),
"downgrade-backup" => Some(Self::DowngradeBackup),
"ebuild-locks" => Some(Self::EbuildLocks),
"fail-clean" => Some(Self::FailClean),
"fakeroot" => Some(Self::FakeRoot),
"fixlafiles" => Some(Self::FixLaFiles),
"force-mirror" => Some(Self::ForceMirror),
"getbinpkg" => Some(Self::GetBinPkg),
"gpg-keepalive" => Some(Self::GpgKeepAlive),
"home-dir-template-copy" => Some(Self::HomeDirTemplateCopy),
"icecream" => Some(Self::IceCream),
"installsources" => Some(Self::InstallSources),
"ipc-sandbox" => Some(Self::IpcSandbox),
"jobserver-token" => Some(Self::JobServerToken),
"keeptemp" => Some(Self::KeepTemp),
"keepwork" => Some(Self::KeepWork),
"lmirror" => Some(Self::LMirror),
"merge-sync" => Some(Self::MergeSync),
"merge-wait" => Some(Self::MergeWait),
"metadata-transfer" => Some(Self::MetadataTransfer),
"mirror" => Some(Self::Mirror),
"mount-sandbox" => Some(Self::MountSandbox),
"multilib-strict" => Some(Self::MultilibStrict),
"network-sandbox" => Some(Self::NetworkSandbox),
"network-sandbox-proxy" => Some(Self::NetworkSandboxProxy),
"news" => Some(Self::News),
"noauto" => Some(Self::NoAuto),
"noclean" => Some(Self::NoClean),
"nodoc" => Some(Self::NoDoc),
"noinfo" => Some(Self::NoInfo),
"noman" => Some(Self::NoMan),
"nostrip" => Some(Self::NoStrip),
"notitles" => Some(Self::NoTitles),
"packdebug" => Some(Self::PackDebug),
"parallel-fetch" => Some(Self::ParallelFetch),
"parallel-install" => Some(Self::ParallelInstall),
"pid-sandbox" => Some(Self::PidSandbox),
"pkgdir-index-trusted" => Some(Self::PkgdirIndexTrusted),
"prelink-checksums" => Some(Self::PrelinkChecksums),
"preserve-libs" => Some(Self::PreserveLibs),
"protect-owned" => Some(Self::ProtectOwned),
"python-trace" => Some(Self::PythonTrace),
"qa-unresolved-soname-deps" => Some(Self::QAUnresolvedSonameDeps),
"sandbox" => Some(Self::Sandbox),
"selinux" => Some(Self::SeLinux),
"sesandbox" => Some(Self::SeSandbox),
"sfperms" => Some(Self::SFPerms),
"sign" => Some(Self::Sign),
"skiprocheck" => Some(Self::SkipRoCheck),
"splitdebug" => Some(Self::SplitDebug),
"split-elog" => Some(Self::SplitElog),
"split-log" => Some(Self::SplitLog),
"strict" => Some(Self::Strict),
"strict-keepdir" => Some(Self::StrictKeepDir),
"stricter" => Some(Self::Stricter),
"suidctl" => Some(Self::Suidctl),
"test" => Some(Self::Test),
"test-fail-continue" => Some(Self::TestFailContinue),
"unknown-features-filter" => Some(Self::UnknownFeaturesFilter),
"unknown-features-warn" => Some(Self::UnknownFeaturesWarn),
"unmerge-backup" => Some(Self::UnmergeBackup),
"unmerge-logs" => Some(Self::UnmergeLogs),
"unmerge-orphans" => Some(Self::UnmergeOrphans),
"unprivileged" => Some(Self::Unprivileged),
"userfetch" => Some(Self::UserFetch),
"userpriv" => Some(Self::UserPriv),
"usersandbox" => Some(Self::UserSandbox),
"usersync" => Some(Self::UserSync),
"warn-on-large-env" => Some(Self::WarnOnLargeEnv),
"webrsync-gpg" => Some(Self::WebRsyncGpg),
"xattr" => Some(Self::XATTR),
_ => None,
}
}
pub fn from_line(line: String) -> Vec<Self> {
let mut ret = Vec::new();
for v in line.split_whitespace() {
let f = Self::from(v);
if f.is_some() {
ret.push(f.unwrap())
}
}
ret
}
}
+28 -30
View File
@@ -1,38 +1,36 @@
#![allow(unused)]
use std::{env, path::{Path,PathBuf}};
use std::io::Result;
use clap::ValueEnum;
use crate::repository::RepoConfig;
mod binpkg;
mod consts;
pub mod config;
pub mod util;
pub mod repository;
pub(crate) mod features;
mod types;
fn getwcd() -> Result<PathBuf> {
let cwd = match env::current_dir() {
Ok(p) => p,
Err(_) => {
env::set_current_dir("/")?;
PathBuf::from("/")
}
};
#[derive(Debug,Clone,ValueEnum)]
pub enum Action {
Search,
Update,
Remove,
Sync,
Depclean,
Install,
Ok(cwd)
}
/// PortageContext
///
/// holds the system and repository configuration.
/// It is the first thing, you need to create, to have full access to this library.
pub struct PortageContext {
repo_config: RepoConfig,
}
impl PortageContext {
pub fn new() -> Result<Self> {
let mut repo_config = RepoConfig::new()?;
repo_config.read_config()?;
Ok(Self {
repo_config
})
fn abssymlink(symlink: &Path, target: Option<PathBuf>) -> Result<PathBuf> {
let mut mylink = if target.is_some() {
target.unwrap()
} else {
std::fs::read_link(symlink)?
};
if !mylink.has_root() {
let mydir = mylink.parent().unwrap();
let link_name = mylink.clone();
mylink = Path::new(mydir).join(link_name);
}
}
Ok(mylink)
}
-187
View File
@@ -1,187 +0,0 @@
use std::env::current_exe;
use std::fmt::Display;
use std::fs::self;
use std::io::{BufRead, BufReader, Result};
use std::{fs::File, path::{Path,PathBuf}};
use std::collections::HashMap;
#[derive(Clone, Default)]
enum SyncType {
#[default]
None,
Rsync(String),
Git(String),
}
impl SyncType {
pub fn get_uri(&self) -> String {
match self {
Self::Git(uri) => uri.to_string(),
Self::Rsync(uri) => uri.to_string(),
Self::None => String::new()
}
}
}
impl Display for SyncType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let (typ, uri) = match self {
Self::Git(uri) => ("git", uri.as_str()),
Self::Rsync(uri) => ("rsync", uri.as_str()),
Self::None => ("none",""),
};
write!(f, "{typ} uri: {uri}")
}
}
#[derive(Clone, Default)]
struct RepositoryConfig {
pub name: String,
pub location: PathBuf,
sync_type: SyncType,
auto_sync: bool,
}
pub struct RepoConfig {
main_repo: String,
repos: Vec<RepositoryConfig>,
initialized: bool,
}
impl RepoConfig {
pub fn new() -> Result<Self> {
Ok(Self {
main_repo: String::new(),
repos: Vec::new(),
initialized: false,
})
}
pub fn read_config(&mut self) -> Result<()> {
// test portage internal config
if PathBuf::from("/usr/share/portage/config/repos.conf").exists() {
let configs = self.read_file(PathBuf::from("/usr/share/portage/config/repos.conf"))?;
self.main_repo = String::from(configs[0].name.clone());
self.repos.push(configs[0].clone());
}
// test the portage config directory: /etc/portage/repos.conf
let dir = Path::new("/etc/portage/repos.conf");
// check if directory exists...
if dir.is_dir() {
let entries = fs::read_dir(dir)?
.map(|res| res.map(|e| e.path()))
.collect::<Result<Vec<_>>>()?;
for entry in entries {
let configs = self.read_file(entry)?;
for config in configs {
self.repos.push(config);
}
}
}
self.initialized = true;
Ok(())
}
fn read_file(&mut self, path: PathBuf) -> Result<Vec<RepositoryConfig>> {
let file = File::open(path)?;
let mut reader = BufReader::new(file);
let mut repos = Vec::new();
let mut data = HashMap::<String,HashMap<String,String>>::new();
let mut current_repo = String::new();
for line in reader.lines() {
let line = line.unwrap();
let line = line.trim();
// ignore empty lines
if line.is_empty() {
continue;
}
// ignore comments
if line.starts_with(';') || line.starts_with('#') {
continue;
}
if line.starts_with('[') && line.ends_with(']') {
current_repo = line[1..line.len() -1].to_string();
} else if let Some(index) = line.find('=') {
let key = line[..index].trim().to_string();
let value = line[index +1 ..].trim().to_string();
if !current_repo.is_empty() {
let repo = data.entry(current_repo.clone()).or_insert(HashMap::new());
repo.insert(key, value);
}
}
}
// parse hashmap
println!("data: {:#?}", data);
for d in data {
if d.0 == "DEFAULT" {
let main_repo = d.1.get("main_repo");
if main_repo.is_some() {
self.main_repo = main_repo.unwrap().clone();
}
} else {
let mut repo = RepositoryConfig::default();
// get repo name
repo.name = d.0;
// get repo sync type & uri
let sync_type = d.1.get("sync-type");
let sync_uri = d.1.get("sync-uri");
if sync_type.is_some() && sync_uri.is_some() {
let sync_type = sync_type.unwrap();
let sync_uri = sync_uri.unwrap();
let sync = match sync_type.to_ascii_lowercase().as_str() {
"rsync" => SyncType::Rsync(sync_uri.to_string()),
"git" => SyncType::Git(sync_uri.to_string()),
_ => SyncType::None,
};
repo.sync_type = sync;
}
// get auto-sync option
let auto_sync = d.1.get("auto-sync");
if auto_sync.is_some() {
match auto_sync.unwrap().to_ascii_lowercase().as_str() {
"true" => repo.auto_sync = true,
_ => repo.auto_sync = false,
}
} else {
repo.auto_sync = false;
}
// get repository location
let location = d.1.get("location");
if location.is_some() {
let location = location.unwrap();
let path = PathBuf::from(location.clone());
repo.location = path;
}
// parsed all relevant data, so push the repo config
repos.push(repo);
}
}
Ok(repos)
}
pub fn print_repos(&self) -> Result<()> {
println!("Main Repository: {}", self.main_repo);
println!();
for repo in self.repos.clone().into_iter() {
println!("Repository: {}", repo.name);
println!("\tlocation: {}", repo.location.display());
println!("\tsync-type: {}", repo.sync_type);
println!();
}
Ok(())
}
}
+17
View File
@@ -0,0 +1,17 @@
pub(crate) struct Atom {
category: String,
packet: String
}
impl Atom {
pub fn new(atom: &str) -> Self {
let parts: Vec<&str> = atom.split('/').collect();
Self {
category: String::from(parts[0]),
packet: String::from(parts[1]),
}
}
}
-29
View File
@@ -1,29 +0,0 @@
use log::{Record, Level, Metadata, SetLoggerError, LevelFilter};
struct SimpleLogger;
impl log::Log for SimpleLogger {
#[cfg(debug_assertions)]
fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() <= Level::Debug
}
#[cfg(not(debug_assertions))]
fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() <= Level::Info
}
fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
println!("{} - {}" , record.level(), record.args());
}
}
fn flush(&self) { }
}
static LOGGER: SimpleLogger = SimpleLogger;
pub fn logger_init(level: LevelFilter) -> Result<(), SetLoggerError> {
log::set_logger(&LOGGER)
.map(|()| log::set_max_level(level))
}
-2
View File
@@ -1,2 +0,0 @@
pub mod logger;
+52
View File
@@ -0,0 +1,52 @@
EAPI=8
DESCRIPTION="Rust port of the portage package manager system"
HOMEPAGE="https://tcraft.me/?topic=ruport"
SRC_URI="https://git.tcraft.me/neo/ruport.git"
IUSE="drop-in"
RUPORT_DROP-IN_BINS=(
target/release/ebuild
target/release/egencache
target/release/emerge
target/release/emerge-webrsync
target/release/emirrordist
target/release/glsa-check
target/release/gpkg-sign
target/release/portageq
target/release/quickpkg
)
RUPORT_DROP-IN_SBINS=(
target/release/archive-conf
target/release/dispatch-conf
target/release/emaint
target/release/env-update
target/release/etc-update
target/release/fixpackages
target/release/regendworld
)
src_compile() {
local cargo_flags=""
if use drop-in ; then
cargo_flags="--features=drop-in"
fi
cargo build --release ${cargo_flags}
}
src_install() {
dobin target/release/ruport
if use drop-in ; then
for pkg in RUPORT_DROP-IN_BINS ; do
dobin $pkg
done
for pkg in RUPORT_DROP-IN_SBINS ; do
dosbin $pkg
done
fi
}
View File
View File
View File
View File
View File
View File
-108
View File
@@ -1,108 +0,0 @@
use clap::{CommandFactory, Parser};
use signal_hook::{consts::SIGINT, iterator::Signals};
use std::{collections::HashMap, error::Error, path::PathBuf, thread};
use portage::Action;
#[derive(Parser)]
#[command(
name = "emerge",
about = "command-line interface to the Portage system"
)]
struct Cli {
/// Pretend mode
#[arg(short = 'p', long)]
pub pretend: bool,
/// Ask before executing
#[arg(short = 'a', long)]
pub ask: bool,
/// Update package
#[arg(short = 'u',long,action)]
pub update: bool,
/// Clean unused packages
#[arg(short='c',long,action)]
pub depclean: bool,
/// Synchronize repositories
#[arg(long,action)]
pub sync: bool,
/// search for matches of the supplied string in the ebuild repository.
#[arg(short = 's',long,action)]
pub search: bool,
/// Number of jobs
#[arg(short = 'j', long)]
pub jobs: Option<u32>,
/// Set the PORTAGE_CONFIGROOT environment variable
#[arg(long,default_value="/")]
pub config_root: PathBuf,
/// Set the ROOT environment variable
#[arg(long)]
pub root: PathBuf,
/// Set the SYSROOT environment variable
#[arg(long)]
pub sysroot: PathBuf,
/// Set the EPREFIX environment variable
#[arg(long)]
pub prefix: PathBuf,
/// Package or sets
#[arg()]
pub targets: Vec<String>,
}
impl Cli {
pub fn get_action(&self) -> Action {
if self.sync {
Action::Sync
} else if self.depclean {
Action::Depclean
} else if self.update {
Action::Update
} else if self.search {
Action::Search(self.targets.clone())
} else {
Action::Install(self.targets.clone())
}
}
pub fn get_paths(&self) -> HashMap<&str, PathBuf> {
let mut paths = HashMap::new();
paths.insert("PORTAGE_CONFIGROOT", self.config_root.clone());
paths.insert("SYSROOT", self.sysroot.clone());
paths.insert("ROOT", self.root.clone());
paths.insert("EPREFIX", self.prefix.clone());
paths
}
}
pub fn main() -> Result<(), Box<dyn Error>> {
if std::env::args_os().len() == 1 {
Cli::command().print_help()?;
return Ok(());
}
let cli = Cli::parse();
let mut signals = Signals::new([SIGINT])?;
thread::spawn(move || {
for sig in signals.forever() {
println!("Received signal {:?}", sig);
}
});
portage::perform_action(cli.get_action(), cli.get_paths())?;
Ok(())
}
View File
View File
View File
View File
View File
View File
+2 -45
View File
@@ -1,46 +1,3 @@
use std::io::Result;
use clap::{Args, CommandFactory, Parser};
use portage::{Action, PortageContext};
use portage::util::logger::logger_init;
#[derive(Parser)]
struct Cli {
/// ask before doing anything
#[arg(short='a', long)]
pub ask: bool,
/// be verbose on the output
#[arg(short='v', long)]
pub verbose: bool,
/// show debug messages
#[arg(short='d', long, default_value="false")]
pub debug: bool,
/// action to perform
#[arg(value_enum)]
pub action: Action,
/// package atoms/names to perform actions against
#[arg()]
pub targets: Vec<String>,
}
fn main() -> std::io::Result<()>{
if std::env::args_os().len() == 1 {
Cli::command().print_help().unwrap();
println!();
return Ok(());
}
let _cli = Cli::parse();
if _cli.debug {
logger_init(log::LevelFilter::Debug)
.expect("unable to setup logger");
} else {
logger_init(log::LevelFilter::Info)
.expect("unable to setup logger");
}
let _ctx = PortageContext::new()?;
Ok(())
fn main() {
println!("Hello, world!");
}
View File
View File
View File