This commit is contained in:
Sebastian Moser
2026-02-20 11:28:45 +01:00
parent 48e691f163
commit f2e73e677a
124 changed files with 2800 additions and 2443 deletions

View File

@@ -0,0 +1,8 @@
use clap::ArgMatches;
use crate::error::VicResult;
pub fn main(matches: &ArgMatches) -> VicResult<()> {
println!("This subcommand is not yet implemented");
Ok(())
}

View File

@@ -0,0 +1,15 @@
use clap::ArgMatches;
use crate::error::VicResult;
pub fn main(matches: &ArgMatches) -> VicResult<()> {
println!("This subcommand is not yet implemented");
Ok(())
}
pub fn get(matches: &ArgMatches) -> VicResult<()> {
println!("system: {}", current_platform::CURRENT_PLATFORM);
Ok(())
}

View File

@@ -0,0 +1,8 @@
use clap::ArgMatches;
use crate::error::VicResult;
pub fn main(matches: &ArgMatches) -> VicResult<()> {
println!("This subcommand is not yet implemented");
Ok(())
}

View File

@@ -0,0 +1,8 @@
use clap::ArgMatches;
use crate::error::VicResult;
pub fn main(matches: &ArgMatches) -> VicResult<()> {
println!("This subcommand is not yet implemented");
Ok(())
}

View File

@@ -0,0 +1,8 @@
use clap::ArgMatches;
use crate::error::VicResult;
pub fn main(matches: &ArgMatches) -> VicResult<()> {
println!("This subcommand is not yet implemented");
Ok(())
}

View File

@@ -0,0 +1,34 @@
use clap::ArgMatches;
use crate::victor::Victor;
use crate::error::VicResult;
pub fn main(matches: &ArgMatches) -> VicResult<()> {
println!("hiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii");
let mut victor = Victor::new()?;
let item_to_run = match matches.get_one::<String>("runnable") {
Some(val) => val,
None => "default",
};
let sub_args = matches.get_many::<String>("runnable").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>();
// check if the item to run is a nix flake url
if item_to_run.contains("#") {
victor.run_flake_url(item_to_run)?;
}
// check if we have something like vic:rpi
if item_to_run.contains(":") {
victor.run_from_resource(item_to_run)?;
}
// if we have no '#' or ':' look for the thing in the vicPkgs
victor.run_from_vic_pkgs(item_to_run, sub_args)?;
Ok(())
}

View File

@@ -0,0 +1,236 @@
use clap::ArgMatches;
use tokio::runtime::Runtime;
use crate::{error::{VicError, VicResult}, vic_err, victor::Victor};
use snix_cli::AllowIncomplete;
use snix_cli::args::Args;
use clap::Parser;
use snix_eval::{
ErrorKind, EvalIO, EvalMode, GlobalsMap, SourceCode, Value,
builtins::impure_builtins,
observer::{DisassemblingObserver, TracingObserver},
};
use snix_glue::{
builtins::{add_derivation_builtins, add_fetcher_builtins, add_import_builtins},
configure_nix_path,
snix_io::SnixIO,
snix_store_io::{self, SnixStoreIO},
};
use tracing::{Span, info_span};
use snix_build::buildservice;
use core::{convert::From, option::Option::None};
use std::fmt::Write;
use tracing_indicatif::span_ext::IndicatifSpanExt;
use snix_cli::EvalResult;
use std::rc::Rc;
use std::path::Path;
use std::path::PathBuf;
use snix_cli::IncompleteInput;
use std::sync::Arc;
use snix_castore::blobservice::BlobService;
use snix_castore::directoryservice::DirectoryService;
use snix_store::pathinfoservice::PathInfoService;
use snix_store::nar::NarCalculationService;
use snix_build::buildservice::BuildService;
use tracing::info;
use snix_store::pathinfoservice::make_fs;
use snix_castore::fs::fuse::FuseDaemon;
use crate::eval::VicEvalResult;
pub fn main(matches: &ArgMatches) -> VicResult<()> {
let mut tokio_runtime = tokio::runtime::Runtime::new().expect("failed to setup tokio runtime");
match matches.subcommand() {
Some(("build", matches)) => run_build(matches),
Some(("mount", matches)) => tokio_runtime.block_on(run_mount(matches)),
Some(("dev", matches)) => run_dev(matches),
Some((_, _)) => Err(vic_err!("unknown subcommand...")),
None => Err(vic_err!("need subcommand...")),
}
}
pub fn run_snix_test(matches: &ArgMatches) -> VicResult<()> {
let mut vic = Victor::new()?;
//println!("test: {}", vic.eval("5 + vic.testing")?);
println!("test: {}", vic.eval(r#"let vic = import /home/me/work/pkgsvic {}; in vic.testing"#)?);
Ok(())
}
pub fn run_mount_blocking(matches: &ArgMatches) -> VicResult<()> {
let mut tokio_runtime = tokio::runtime::Runtime::new().expect("failed to setup tokio runtime");
tokio_runtime.block_on(run_mount(matches));
Ok(())
}
pub fn run_dev(matches: &ArgMatches) -> VicResult<()> {
/*
let mut tokio_runtime = tokio::runtime::Runtime::new().expect("failed to setup tokio runtime");
let nix_path = "nixpkgs=/nix/store/1pwi0971a1j83l325xswpc2y019zkxiz-source".to_owned();
let tracing_handle = snix_tracing::TracingBuilder::default()
.enable_progressbar()
.build()
.expect("unable to set up tracing subscriber");
let mut stdout = tracing_handle.get_stdout_writer();
let mut stderr = tracing_handle.get_stderr_writer();
let (blob_service, directory_service, path_info_service, nar_calculation_service, build_service) = tokio_runtime.block_on(my_construct_services());
let snix_store_io = Rc::new(SnixStoreIO::new(
blob_service.clone(),
directory_service.clone(),
path_info_service,
nar_calculation_service.into(),
build_service.into(),
tokio_runtime.handle().clone()
));
let bundle_name = Uuid::new_v4();
let bundle_path = PathBuf::from("/home/me/work/tori-victorinix/gitignore/building/snix/buildservice").join(bundle_name.to_string());
let oci_process = oci_spec::runtime::ProcessBuilder::default()
.terminal(true)
.user(
oci_spec::runtime::UserBuilder::default()
.uid(1000u32)
.gid(100u32)
.build()?,
)
.cwd(Path::new("/"))
.capabilities(
HashSet::from([
Capability::AuditWrite,
Capability::Chown,
Capability::DacOverride,
Capability::Fowner,
Capability::Fsetid,
Capability::Kill,
Capability::Mknod,
Capability::NetBindService,
Capability::NetRaw,
Capability::Setfcap,
Capability::Setgid,
Capability::Setpcap,
Capability::Setuid,
Capability::SysChroot,
])
)
.build().expect("failed to build oci_process");
;
let spec_builder = oci_spec::runtime::SpecBuilder::default()
.process(
oci_process
)
.root(
oci_spec::runtime::RootBuilder::default()
.path("root")
.readonly(true)
.build()
.map_err(SpecError::OciError)?,
)
.hostname("localhost")
.mounts(
configure_mounts(
rootless,
allow_network,
request.scratch_paths.iter().map(|e| e.as_path()),
request.inputs.iter(),
&request.inputs_dir,
ro_host_mounts,
)
.map_err(SpecError::OciError)?,
);
println!("before builder.build()");
let spec = builder.build().expect("failed to build spec_builder");
////////////// create all the paths for the bundle
fs::create_dir_all(bundle_path).expect("failed to create bundle path");
fs::create_dir_all(bundle_path.join("root").join("etc")).expect("failed to create bundle path");
////// write config.json
let spec_json = serde_json::to_string(spec).expect("failed to render spec to json")?;
fs::write(bundle_path.join("config.json"), spec_json).expect("failed to write config.json")?;
*/
Ok(())
}
pub async fn run_mount(matches: &ArgMatches) -> VicResult<()> {
let mut vic = Victor::new()?;
let mnt_string_ref = matches.get_one::<String>("mnt-path").unwrap();
let mnt_path: String = format!("{}", mnt_string_ref);
let (blob_service, directory_service, path_info_service, nar_calculation_service, build_service) = crate::eval::vic_construct_services(&mut vic).await?;
let fuse_daemon = tokio::task::spawn_blocking(move || {
let fs = make_fs(
blob_service,
directory_service,
path_info_service,
true,
true,
);
FuseDaemon::new(fs, PathBuf::from(mnt_path), 4, true)
})
.await??;
// Wait for a ctrl_c and then call fuse_daemon.unmount().
tokio::spawn({
let fuse_daemon = fuse_daemon.clone();
async move {
tokio::signal::ctrl_c().await.unwrap();
info!("interrupt received, unmounting…");
tokio::task::spawn_blocking(move || fuse_daemon.unmount()).await??;
info!("unmount occured, terminating…");
Ok::<_, std::io::Error>(())
}
});
// Wait for the server to finish, which can either happen through it
// being unmounted externally, or receiving a signal invoking the
// handler above.
tokio::task::spawn_blocking(move || fuse_daemon.wait()).await?;
Ok(())
}
pub fn run_build(matches: &ArgMatches) -> VicResult<()> {
let mut vic = Victor::new()?;
let expr = r#"
let
a = builtins.trace "hooooooooooo" "hello world";
pkgs = import <nixpkgs> {};
b = builtins.readFile "${pkgs.hello}/share/info/hello.info";
in ''
a: ${a}
b: ${b}
''
"#;
let result = vic.eval(expr)?;
println!("result: {}", result);
Ok(())
}

View File

@@ -0,0 +1,8 @@
use clap::ArgMatches;
use crate::error::VicResult;
pub fn main(matches: &ArgMatches) -> VicResult<()> {
println!("This subcommand is not yet implemented");
Ok(())
}

113
packages/vic/src/error.rs Normal file
View File

@@ -0,0 +1,113 @@
use std::ffi::NulError;
use std::fmt::Display;
use log::{error, info, debug};
use colored::Colorize;
pub type VicResult<T> = Result<T, VicError>;
#[macro_export]
macro_rules! vic_err {
($($arg:tt)*) => { VicError::new().msg(format!( $($arg)*)) };
}
#[derive(Debug)]
pub struct VicError {
pub msg: Vec<String>,
pub code_location: Option<VicCodeLocation>,
}
pub trait IntoVicResult<T, S> {
fn vic_result(self) -> VicResult<T>;
fn vic_result_msg(self, msg: S) -> VicResult<T> where S: std::fmt::Display ;
}
#[derive(Debug, Clone)]
pub struct VicCodeLocation {
file: String,
line: u32,
column: u32,
}
impl VicError {
#[track_caller]
pub fn new() -> VicError {
let caller_location = std::panic::Location::caller();
let mut err = VicError { msg: Vec::new(), code_location: None };
err.location(caller_location.into())
}
fn location(mut self, location: VicCodeLocation) -> VicError {
self.code_location = Some(location);
self
}
pub fn msg<T: Into<String>>(mut self, msg: T) -> VicError {
self.msg.push(msg.into());
self
}
pub fn log(self) -> VicError {
error!("VicError envountered!");
if let Some(ref location) = self.code_location {
error!("[ {} ] {}", "LOCATION".yellow(), location);
};
for msg in &self.msg {
error!("[ {} ] {}", "MSG".yellow(), msg);
debug!("[ {} ] {:?}", "MSG".yellow(), msg);
}
self
}
}
////////////////// trait implementations
impl<T: Display> From<T> for VicError {
#[track_caller]
fn from(value: T) -> Self {
let caller_location = std::panic::Location::caller();
VicError::new()
.msg(format!("From {}: {}", std::any::type_name_of_val(&value), value))
.location(caller_location.into())
}
}
impl<T, E, S> IntoVicResult<T, S> for Result<T, E> where E: std::fmt::Display + std::fmt::Debug {
#[track_caller]
fn vic_result(self) -> VicResult<T> {
let caller_location = std::panic::Location::caller();
match self {
Ok(val) => VicResult::Ok(val),
Err(err) => VicResult::Err(VicError::new()
.msg(format!("From {}: {}", std::any::type_name_of_val(&err), err))
.msg(format!("LONG msg: {:?}", err))
.location(caller_location.into())),
}
}
#[track_caller]
fn vic_result_msg(self, msg: S) -> VicResult<T> where S: std::fmt::Display {
let caller_location = std::panic::Location::caller();
match self {
Ok(val) => VicResult::Ok(val),
Err(err) => VicResult::Err(VicError::new()
.msg(format!("{}", msg))
.msg(format!("From {}: {}", std::any::type_name_of_val(&err), err))
.msg(format!("LONG msg: {:?}", err))
.location(caller_location.into())),
}
}
}
impl Display for VicCodeLocation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "file: {} line: {} column: {}", self.file, self.line, self.column)
}
}
impl From<&std::panic::Location <'_>> for VicCodeLocation {
fn from(panic_location: &std::panic::Location) -> VicCodeLocation {
let file = panic_location.file().to_string();
let line = panic_location.line();
let column = panic_location.column();
VicCodeLocation {file, line, column}
}
}

203
packages/vic/src/eval.rs Normal file
View File

@@ -0,0 +1,203 @@
use crate::{error::{VicError, VicResult}, vic_err, victor::Victor};
use std::fs;
use nix_compat::flakeref::FlakeRefOutput;
use snix_eval::{Builtin, Evaluation};
use snix_cli::AllowIncomplete;
use snix_cli::args::Args;
use clap::Parser;
use snix_eval::{
ErrorKind, EvalIO, EvalMode, GlobalsMap, SourceCode, Value,
builtins::impure_builtins,
observer::{DisassemblingObserver, TracingObserver},
};
use snix_glue::{
builtins::{add_derivation_builtins, add_fetcher_builtins, add_import_builtins},
configure_nix_path,
snix_io::SnixIO,
snix_store_io::{self, SnixStoreIO},
};
use tracing::{Span, info_span};
use snix_build::buildservice;
use core::{convert::From, option::Option::None, todo, unimplemented};
use std::fmt::Write;
use tracing_indicatif::span_ext::IndicatifSpanExt;
use snix_cli::EvalResult;
use std::rc::Rc;
use std::path::Path;
use std::path::PathBuf;
use snix_cli::IncompleteInput;
use std::sync::Arc;
use snix_castore::blobservice::BlobService;
use snix_castore::directoryservice::DirectoryService;
use snix_store::pathinfoservice::PathInfoService;
use snix_store::nar::NarCalculationService;
use snix_build::buildservice::BuildService;
use tracing::info;
use snix_store::pathinfoservice::make_fs;
use snix_castore::fs::fuse::FuseDaemon;
pub type VicEvalResult = Result<Value, VicError>;
pub fn build_snix_evaluator<'a>(vic: &mut Victor) -> VicResult<Evaluation<'a, 'a, 'a, Box<dyn EvalIO>>> {
let mut tokio_runtime = tokio::runtime::Runtime::new().expect("failed to setup tokio runtime");
let nix_path = "nixpkgs=/nix/store/1pwi0971a1j83l325xswpc2y019zkxiz-source".to_owned();
let tracing_handle = snix_tracing::TracingBuilder::default()
.enable_progressbar()
.build()
.expect("unable to set up tracing subscriber");
let mut stdout = tracing_handle.get_stdout_writer();
let mut stderr = tracing_handle.get_stderr_writer();
let (blob_service, directory_service, path_info_service, nar_calculation_service, build_service) = tokio_runtime.block_on(vic_construct_services(vic))?;
let snix_store_io = Rc::new(SnixStoreIO::new(
blob_service.clone(),
directory_service.clone(),
path_info_service,
nar_calculation_service.into(),
build_service.into(),
tokio_runtime.handle().clone()
));
let mut eval_builder = snix_eval::Evaluation::builder(Box::new(SnixIO::new(snix_store_io.clone() as Rc<dyn EvalIO>,)) as Box<dyn EvalIO>)
.enable_import();
eval_builder = eval_builder.add_builtins(impure_builtins());
eval_builder = add_derivation_builtins(eval_builder, Rc::clone(&snix_store_io));
eval_builder = add_fetcher_builtins(eval_builder, Rc::clone(&snix_store_io));
eval_builder = add_import_builtins(eval_builder, Rc::clone(&snix_store_io));
//eval_builder = add_get_flake_builtins(eval_builder, Rc::clone(&snix_store_io));
eval_builder = configure_nix_path(eval_builder, &Some(nix_path));
//if let Some(source_map) = source_map {
//eval_builder = eval_builder.with_source_map(source_map);
//}
let source_map = eval_builder.source_map().clone();
let mut compiler_observer = DisassemblingObserver::new(source_map.clone(), stderr.clone());
//if args.dump_bytecode {
//eval_builder.set_compiler_observer(Some(&mut compiler_observer));
//}
let mut runtime_observer = TracingObserver::new(stderr.clone());
//if args.trace_runtime {
//if args.trace_runtime_timing {
//runtime_observer.enable_timing()
//}
//eval_builder.set_runtime_observer(Some(&mut runtime_observer));
//}
let eval = eval_builder.build();
return Ok(eval);
}
pub async fn vic_construct_services(vic: &mut Victor) ->
VicResult<(
Arc<dyn BlobService>,
Arc<dyn DirectoryService>,
Arc<dyn PathInfoService>,
Box<dyn NarCalculationService>,
Box<dyn BuildService>,
)> {
let vic_snix_path = PathBuf::from(vic.config_get("vic_dir")?).join("snix");
// create the dirs
{
// the snix folder
if !vic_snix_path.exists() {
fs::create_dir(&vic_snix_path);
}
// the blobservice folder
if !vic_snix_path.join("blobservice").exists() {
fs::create_dir(&vic_snix_path.join("blobservice"));
}
// the blobservice folder
if !vic_snix_path.join("buildservice").exists() {
fs::create_dir(&vic_snix_path.join("buildservice"));
}
}
let castore_service_addrs = snix_castore::utils::ServiceUrls {
blob_service_addr: format!("objectstore+file://{}/blobservice", vic_snix_path.display()),
directory_service_addr: format!("redb://{}/directoryservice.redb", vic_snix_path.display()),
experimental_store_composition: None,
};
let path_info_service_addr = format!("redb://{}/pathinfo.redb", vic_snix_path.display());
let service_urls = snix_store::utils::ServiceUrls { castore_service_addrs, path_info_service_addr, experimental_store_composition: None, };
let build_service_addr = format!("oci://{}/buildservice", vic_snix_path.display());
let (
blob_service,
directory_service,
path_info_service,
nar_calculation_service,
) = snix_store::utils::construct_services(service_urls)
.await
.expect("unable to setup {blob|directory|pathinfo}service before interpreter setup");
let build_service = {
let blob_service = blob_service.clone();
let directory_service = directory_service.clone();
async move {
buildservice::from_addr(
&build_service_addr,
blob_service.clone(),
directory_service.clone(),
).await
}.await
}.expect("unable to setup buildservice before interpreter setup");
return Ok((blob_service, directory_service, path_info_service, nar_calculation_service, build_service));
}
/*
pub fn add_get_flake_builtins<'co, 'ro, 'env, IO>(
eval_builder: snix_eval::EvaluationBuilder<'co, 'ro, 'env, IO>,
io: Rc<SnixStoreIO>,
) -> snix_eval::EvaluationBuilder<'co, 'ro, 'env, IO> {
let getflake_builtin = Builtin::new("getFlake", Some("see: https://nix.dev/manual/nix/2.18/language/builtins#builtins-getFlake"), 1, getflake_builtin_fn);
todo!()
}
fn getflake_builtin_fn(url: Vec<Value>) -> Value {
use nix_compat::flakeref::FlakeRef;
/*
let flake_ref: FlakeRef = url.into();
match flake_ref {
FlakeRef::GitHub { owner, repo, host, keytype, public_key, public_keys, r#ref, rev } => {
},
_ => unimplemented!()
}
*/
todo!()
}
*/

316
packages/vic/src/main.rs Normal file
View File

@@ -0,0 +1,316 @@
#![ allow( warnings ) ]
use std::env;
use clap::{ArgAction, ArgMatches};
use clap::{Arg, crate_version, Command};
use log::Level;
use log::LevelFilter;
use env_logger::Builder;
use std::io::Write;
use colored::Colorize;
use log::{trace, debug, info, warn, error};
use std::ffi::{c_char, CStr};
mod error;
mod utils;
mod victor;
mod eval;
mod commands {
pub mod info;
pub mod stat;
pub mod run;
pub mod build;
pub mod list;
pub mod gui;
pub mod env;
pub mod snix_testing;
}
static APPNAME: &str = "vic";
static DEFAULT_LOG_LEVEL: LevelFilter = LevelFilter::Warn;
fn main() {
let cli_matches = cli_matches();
//init_logger(&cli_matches);
// log a message of every level, to test loging
// test_logger();
// match the subcommands
let result = match cli_matches.subcommand() {
Some(("info", sub_matches)) => commands::info::main(&sub_matches),
Some(("stat", sub_matches)) => commands::stat::main(&sub_matches),
Some(("run", sub_matches)) => commands::run::main(&sub_matches),
Some(("build", sub_matches)) => commands::build::main(&sub_matches),
Some(("list", sub_matches)) => commands::list::main(&sub_matches),
Some(("gui", sub_matches)) => commands::gui::main(&sub_matches),
Some(("env", sub_matches)) => commands::env::main(&sub_matches),
Some(("env-get", sub_matches)) => commands::env::get(&sub_matches),
Some(("snix-mount", sub_matches)) => commands::snix_testing::run_mount_blocking(&sub_matches),
Some(("snix-test", sub_matches)) => commands::snix_testing::run_snix_test(&sub_matches),
Some(("snix-build", sub_matches)) => commands::snix_testing::run_build(&sub_matches),
None => { println!("Hi, this is victorinix (also known as victor or vic). \nrun 'vic help' for a list of subcommands."); Ok(())},
Some((unknown_subcommand, _)) => { println!("The subcommand '{}' is not known to victorinix", unknown_subcommand); Ok(()) },
};
if let Err(vic_err) = result {
vic_err.log();
}
}
fn test() {
let c_buf: *const c_char = unsafe { libelf::raw::elf_errmsg(-1) };
let c_str: &CStr = unsafe { CStr::from_ptr(c_buf) };
let str_slice: &str = c_str.to_str().unwrap();
println!("ERROR: {}", str_slice);
}
fn init_logger(cli_matches: &ArgMatches) {
// to save log messages, before the logger is setup
let mut log_messages: Vec<(Level, String)> = Vec::new();
log_messages.push((Level::Trace, "Starting victorinix".to_owned()));
// builder with DEFAULT_LOG_LEVEL
let mut builder = Builder::new();
builder.format_indent(Some(8));
// set loglevel
let mut log_level = DEFAULT_LOG_LEVEL;
log_messages.push((Level::Trace, format!("set log level to {} as specified by DEFAULT_LOG_LEVEL in the src/main.rs", DEFAULT_LOG_LEVEL)));
// check env RUST_LOG
let mut val_rust_log = level_from_env("RUST_LOG", log_level);
log_level = if let Some(level_rust_log) = val_rust_log.0 {
log_messages.push((Level::Trace, format!("set log level from the Variable RUST_LOG to {}", level_rust_log)));
level_rust_log
} else {log_level};
log_messages.append(&mut val_rust_log.1);
// check env VICTORINIX_LOG
let mut val_victorinix_log = level_from_env("VICTORINIX_LOG", log_level);
log_level = if let Some(level_victorinix_log) = val_victorinix_log.0 {
log_messages.push((Level::Trace, format!("set log level from the Variable VICTORINIX_LOG to {}", level_victorinix_log)));
level_victorinix_log
} else {log_level};
log_messages.append(&mut val_victorinix_log.1);
// check -vvvvv flags
let v_flag_count = cli_matches.get_count("verbose");
let old_log_level_as_num = match log_level {
LevelFilter::Off => 0,
LevelFilter::Error => 1,
LevelFilter::Warn => 2,
LevelFilter::Info => 3,
LevelFilter::Debug => 4,
LevelFilter::Trace => 5,
};
let new_log_level_num = old_log_level_as_num + v_flag_count;
log_level = match new_log_level_num {
0 => LevelFilter::Off,
1 => LevelFilter::Error,
2 => LevelFilter::Warn,
3 => LevelFilter::Info,
4 => LevelFilter::Debug,
5 => LevelFilter::Trace,
_ => {
log_messages.push((Level::Trace, format!("the number of verbose (-v) flags passed ({}) exeeds the maximumg log_level", v_flag_count)));
LevelFilter::Trace
},
};
log_messages.push((Level::Trace, format!("set log level from the verbose flags to {}", log_level)));
// check --log-level arg
if let Some(log_level_arg_string) = cli_matches.get_one::<String>("log-level") {
let log_level_from_arg = match log_level_arg_string.to_lowercase().as_str() {
"none" => LevelFilter::Off,
"trace" => LevelFilter::Trace,
"all" => LevelFilter::Trace,
"debug" => LevelFilter::Debug,
"info" => LevelFilter::Info,
"warn" => LevelFilter::Warn,
"error" => LevelFilter::Error,
_ => {
log_messages.push((Level::Warn, format!(
"The argument to --log-level \"{}\" is not a valid log-level. loglevel stays at: {}"
, log_level_arg_string
, log_level
)));
log_level
}
};
log_level = log_level_from_arg;
log_messages.push((Level::Trace, format!("set log level from the --log-level arg to {}", log_level_from_arg)));
}
// check --silent flag
if cli_matches.get_flag("silent") {
if log_level != DEFAULT_LOG_LEVEL {
log_messages.push((Level::Warn, format!(
"The loglevel was set by some method (it's not the DEFAULT_LOG_LEVEL) and is now overwritten by the --siltne to be OFF"
)))
}
log_level = LevelFilter::Off;
}
// actually set the log_level on the builder
builder.filter_level(log_level);
log_messages.push((Level::Info, format!("loglevel is now {}", log_level)));
// set format
builder.format(|buf, record| {
match record.level() {
Level::Trace => writeln!(buf, "[ {} ] {}", format!("{}", record.level()).yellow(), record.args()),
Level::Debug => writeln!(buf, "[ {} ] {}", format!("{}", record.level()).green(), record.args()),
Level::Info => writeln!(buf, "[ {} ] {}", format!("{}", record.level()).blue(), record.args()),
Level::Warn => writeln!(buf, "[ {} ] {}", format!("{}", record.level()).truecolor(245, 164, 66), record.args()),
Level::Error => writeln!(buf, "[ {} ] {}", format!("{}", record.level()).red(), record.args()),
}
});
builder.init();
// write out all log messages from log_messages
for (level, msg) in log_messages {
match level {
Level::Error => error!("{}", msg),
Level::Warn => warn!("{}", msg),
Level::Info => info!("{}", msg),
Level::Debug => debug!("{}", msg),
Level::Trace => trace!("{}", msg),
}
}
}
fn test_logger() {
error!("hi from error");
warn!("hi from warn");
info!("hi from info");
debug!("hi from debug");
trace!("hi from trace");
}
fn level_from_env(var_name: &str, log_level: LevelFilter) -> (Option<log::LevelFilter>, Vec<(Level, String)>) {
let mut log_messages: Vec<(Level, String)> = Vec::new();
let var_value = env::var(var_name);
match var_value {
Ok(val) => {
// set loglevel acording to RUST_LOG
let level = match val.to_lowercase().as_str() {
"none" => LevelFilter::Off,
"trace" => LevelFilter::Trace,
"debug" => LevelFilter::Debug,
"info" => LevelFilter::Info,
"warn" => LevelFilter::Warn,
"error" => LevelFilter::Error,
_ => {
log_messages.push((Level::Warn, format!(
"The value of Environment Variable {}: \"{}\" is not a valid log-level. loglevel stays at: {}"
, var_name
, val
, log_level
)));
log_level
}
};
return (Some(level), log_messages)
},
Err(env::VarError::NotPresent) => {},
Err(env::VarError::NotUnicode(os_string)) => {
let os_string_as_hex : String = os_string.clone().into_encoded_bytes().iter()
.map(|b| format!("{:02x}", b).to_string())
.collect::<Vec<String>>()
.join("");
log_messages.push((Level::Debug, format!(
"value of Environment Variable {} was not a unicode valid string. Therefore ignoring it.
\n value with replacement char U+FFFD: {}
\n the WTF-8 raw bytes as hex: {}"
, var_name
, os_string.to_string_lossy(), os_string_as_hex
)));
},
};
return (None, log_messages);
}
fn cli_matches() -> clap::ArgMatches {
let main = Command::new(APPNAME)
.version(crate_version!())
.author("Sebastian Moser (c2vi)")
.about("Victorinix: Friendly and usefull box of portable computer tools. Powered by Nix and MiZe")
.arg_required_else_help(true)
.arg(Arg::new("verbose")
.long("verbose")
.short('v')
.action(ArgAction::Count)
)
.arg(Arg::new("log-level")
.long("log-level")
.value_name("LOGLEVEL")
.help("set the log-level to one of OFF, ERROR, WARN, INFO, DEBUG, TRACE")
)
.arg(Arg::new("silent")
.long("silent")
.action(ArgAction::SetTrue)
.help("set the log-level to OFF")
)
.subcommand(Command::new("info")
)
.subcommand(Command::new("stat")
)
.subcommand(Command::new("run")
.arg(Arg::new("runnable")
.help("The item to be run")
.action(clap::ArgAction::Append)
.trailing_var_arg(true)
)
//.arg(Arg::new("rest")
//.help("args to pass down to the runnable command")
//)
)
.subcommand(Command::new("build")
)
.subcommand(Command::new("list")
)
.subcommand(Command::new("gui")
)
.subcommand(Command::new("env")
)
.subcommand(Command::new("env-get")
.alias("eg")
)
.subcommand(Command::new("snix-mount")
.alias("sm")
)
.subcommand(Command::new("snix-test")
.alias("st")
)
.subcommand(Command::new("snix-build")
.alias("sb")
)
;
return main.get_matches();
}

View File

394
packages/vic/src/victor.rs Normal file
View File

@@ -0,0 +1,394 @@
use core::fmt::Display;
use std::collections::HashMap;
use std::io;
use std::os::unix::fs::FileExt;
use log::info;
use serde_json::Value as JsonValue;
use serde_json::Map as JsonMap;
use snix_eval::Evaluation;
use snix_eval::Value;
use std::{fs::File, io::copy};
use anyhow::Result;
use log::{debug, trace};
use flate2::read::GzDecoder;
use tar::Archive;
use std::path::Path;
use std::fs;
use std::io::{SeekFrom, Seek};
use std::process::{Command, Stdio};
use crate::error::{VicResult, VicError, IntoVicResult};
use crate::vic_err;
use crate::eval::VicEvalResult;
use crate::eval::build_snix_evaluator;
pub static BUILD_CONFIG: &str = include_str!(std::env!("VIC_BUILD_CONFIG"));
// a struct for state
pub struct Victor {
pub config: VictorConfig,
}
impl Victor {
pub fn eval(&mut self, expr: impl AsRef<str> + Display) -> VicResult<Value> {
let evaluator = build_snix_evaluator(self)?;
let vicpkgs_url = self.config_get("vicpkgs_url")?;
let expr = format!(r#" let
vicpkgs_url = "{vicpkgs_url}";
src = if (builtins.substring 0 7 vicpkgs_url) == "github:"
then builtins.fetchGit {{
url = "git@github.com:c2vi/nixpkgs";
}}
else {vicpkgs_url};
vic = import src {{}};
in ({})
"#, expr);
let result = evaluator.evaluate(expr, None);
if let Some(value) = result.value {
return Ok(value);
} else {
let mut err = vic_err!("error during evaluation....");
for error in result.errors {
err = err.msg(format!("SnixEvalError: {:?}", error));
}
for warning in result.warnings {
err = err.msg(format!("SnixEvalWarning: {:?}", warning));
}
return Err(err);
}
}
pub fn new() -> VicResult<Victor> {
let mut victor = Victor {
config: VictorConfig::empty(),
};
//victor.pre_build_config_init()?;
victor.config.read_build_config()?;
victor.pre_folder_config_init()?;
victor.config.read_folder_config()?;
//victor.post_config_init()?;
Ok(victor)
}
fn pre_folder_config_init(&mut self) -> VicResult<()> {
//////////// on android $HOME points to / which is not readable
// so set vic_dir to /sdcard/.victorinix
if are_we_on_android()? {
self.config_set("vic_dir", "/data/local/.victorinix")?;
}
Ok(())
}
pub fn config_get<P: IntoVecString>(&self, path: P) -> VicResult<String> {
self.config.get(path.to_vec_string())
}
pub fn config_set<P: IntoVecString, V: Into<String>>(&mut self, path: P, value: V) -> VicResult<()> {
self.config.set(path.to_vec_string(), value.into());
Ok(())
}
pub fn config_exists<P: IntoVecString>(&self, path: P) -> bool {
self.config.exists(path.to_vec_string())
}
fn fetch_tarball(&mut self) -> VicResult<()> {
if self.config_exists("internal.tarball_is_fetched") && self.config_get("internal.tarball_is_fetched")? == "true" {
// tarball is already fetched
return Ok(());
}
if Path::new(&self.config_get("vic_dir")?).join("nix").exists() {
//vic $VIC_DIR/nix exists the tarball should also be fetched
return Ok(());
}
// create_folder if it doesn't already
self.create_folder()?;
// determine arch
let mut arch_cmd = Command::new("uname");
arch_cmd.arg("-m");
let arch_output = arch_cmd.output()
.vic_result_msg("can't get output of 'uname -m'")?;
let mut arch_iter = arch_output.stdout.clone().into_iter();
arch_iter.next_back();
let arch = String::from_utf8(arch_iter.collect())
.vic_result_msg("not able to turn the output of 'uname -m' into a string")?;
debug!("found arch: '{}'", arch);
let mut url = format!("{}/tars/{}-linux.tar.gz", self.config_get("url")?, arch);
let vic_dir = self.config_get("vic_dir")?;
let tmp_file_path_gz = vic_dir.clone() + "/tmp.tar.gz";
info!("fetching tarball from: {}", url);
let mut response = reqwest::blocking::get(url)?;
let mut tmp_file_gz = File::create(&tmp_file_path_gz)?;
copy(&mut response, &mut tmp_file_gz)?;
let tar_gz = File::open(&tmp_file_path_gz)?;
let tar = GzDecoder::new(tar_gz);
let mut archive = Archive::new(tar);
//archive.set_mask(umask::Mode::parse("rwxrwxrwx")?.into());
archive.unpack(&vic_dir)?;
fs::remove_file(&tmp_file_path_gz)?;
self.config_set("internal.tarball_is_fetched", "true");
Ok(())
}
fn create_folder(&self) -> VicResult<()> {
let path = self.config_get("vic_dir")?;
info!("creating vic_dir at: {}", path);
if !Path::new(&path).exists() {
fs::create_dir(path);
}
Ok(())
}
pub fn run_from_vic_pkgs(&mut self, runnable: &str, sub_args: Vec<&str>) -> VicResult<()> {
debug!("running '{}' from vic pkgs", runnable);
self.fetch_tarball()?;
self.nix_run(runnable, sub_args)?;
Ok(())
}
pub fn nix_run(&mut self, runnable: &str, sub_args: Vec<&str>) -> VicResult<()> {
let tmp_binding = self.config_get("vic_dir")?;
let vic_dir_path = Path::new(&tmp_binding);
let proot_path = vic_dir_path.join("nix").join("proot");
let nix_path = fs::read_to_string(vic_dir_path.join("nix").join("nix-path"))?;
let busybox_path = fs::read_to_string(vic_dir_path.join("nix").join("busybox-path"))?;
let cacert_path = fs::read_to_string(vic_dir_path.join("nix").join("cacert-path"))?;
println!("nix_path: {}", nix_path);
println!("runnable: {}", runnable);
if runnable == "default" {
let mut proot = Command::new(&proot_path);
proot.env_clear();
proot.env("PATH", format!("{}:{}", busybox_path, nix_path));
proot.env("HISTFILE", "/history");
proot.env("SSL_CERT_FILE", cacert_path);
proot.arg("-r").arg(vic_dir_path);
proot.arg("-b").arg("/:/out");
proot.arg("-w").arg("/");
proot.arg("-i").arg("0:0");
proot.arg(busybox_path.clone() + "/sh");
let mut child_handle = proot.spawn()?;
child_handle.wait();;
return Ok(());
}
let mut proot = Command::new(&proot_path);
proot.env_clear();
proot.env("PATH", format!("{}:{}", busybox_path, nix_path));
proot.env("HISTFILE", "/history");
proot.env("TERM", "xterm-color");
proot.env("SSL_CERT_FILE", cacert_path);
proot.arg("-r").arg(vic_dir_path);
proot.arg("-b").arg("/:/out");
proot.arg("-w").arg("/");
//proot.arg("-0");
proot.arg("-i").arg("0:0");
proot.arg(busybox_path.clone() + "/sh");
proot.arg("/run");
proot.env("VIC_TO_RUN", format!("nix --extra-experimental-features nix-command --extra-experimental-features flakes run nixpkgs#{}", runnable));
//proot.arg(nix_path.clone() + "nix");
//proot.arg("--extra-experimental-features nix-command");
//proot.arg("--extra-experimental-features flakes");
//proot.arg("run");
//proot.arg(format!("nixpkgs#{}", runnable));
//proot.arg(nix_path);
//for sub_arg in sub_args {
//proot.arg(sub_arg);
//};
let mut child_handle = proot.spawn()?;
child_handle.wait();;
Ok(())
}
pub fn run_from_resource(&self, runnable: &str) -> VicResult<()> {
println!("running from resource: {}", runnable);
Ok(())
}
pub fn run_flake_url(&self, runnable: &str) -> VicResult<()> {
println!("running flake url: {}", runnable);
Ok(())
}
}
struct VictorConfig {
inner: HashMap<String, String>,
}
impl VictorConfig {
pub fn new() -> VicResult<VictorConfig> {
let mut config = VictorConfig::empty();
config.read_build_config()?;
config.read_folder_config()?;
Ok(config)
}
pub fn empty() -> VictorConfig {
VictorConfig { inner: HashMap::new() }
}
fn read_folder_config(&mut self) -> VicResult<()> {
debug!("reading config from vic_dir");
trace!("read folder config ... VictorConfig is now: {:?}", self.inner);
self.fix_vic_dir()?;
Ok(())
}
// this fn replaces a leading '~' in the vic_dir conf var with an absolute path to a users
// home dir
fn fix_vic_dir(&mut self) -> VicResult<()> {
let old_vic_dir = self.get(vec!["vic_dir".to_owned()])?;
let first_char = old_vic_dir.chars().nth(0)
.ok_or(vic_err!("vic_dir config path is an empty string, should not be possible"))?;
if first_char == '~' {
debug!("substituting ~ with val from $HOME in vic_dir");
let home_path = std::env::var("HOME").vic_result_msg("Could not get $HOME")?;
let new_vic_dir = old_vic_dir.replace("~", &home_path);
self.set(vec!["vic_dir".to_owned()], new_vic_dir)?;
}
Ok(())
}
fn read_build_config(&mut self) -> VicResult<()> {
debug!("reading config that was set at build time");
let mut json_val: JsonValue = serde_json::from_str(BUILD_CONFIG)
.vic_result_msg("Error parsing string from BUILD_CONFIG")
.map_err(|e| e.msg("which is read at build time from a file specified in the VIC_BUILD_CONFIG env var"))?;
if let JsonValue::Object(ref mut map) = json_val {
let vec = json_map_to_vec(map, Vec::new(), Vec::new())?;
for (key, val) in vec {
self.inner.insert(key, val);
}
} else {
return Err(vic_err!("root of json string from BUILD_CONFIG is not a map"));
}
self.fix_vic_dir()?;
trace!("read build config ... VictorConfig is now: {:?}", self.inner);
Ok(())
}
pub fn get(&self, path: Vec<String>) -> VicResult<String> {
let val = self.inner.get(&path.join("."))
.ok_or(vic_err!("Could not get config path '{}'", path.join(".")))?;
return Ok(val.to_owned());
}
pub fn set(&mut self, path: Vec<String>, val: String) -> VicResult<()> {
self.inner.insert(path.join("."), val);
Ok(())
}
pub fn exists(&self, path: Vec<String>) -> bool {
self.inner.contains_key(&path.join("."))
}
}
fn json_map_to_vec(map: &mut JsonMap<String, JsonValue>, cur_path: Vec<String>, mut out_vec: Vec<(String, String)>) -> VicResult<Vec<(String, String)>> {
for (key, value) in map.iter_mut() {
trace!("json_map_to_vec loop - key: {}", key);
trace!("json_map_to_vec loop - value: {}", value);
let mut inner_path = cur_path.clone();
inner_path.push(key.to_owned());
match value {
JsonValue::Object(ref mut inner_map) => {
return json_map_to_vec(inner_map, inner_path, out_vec);
},
JsonValue::String(string) => {
out_vec.push((inner_path.join("."), string.to_owned()));
}
val => {
out_vec.push((inner_path.join("."), format!("{}", val)));
}
}
};
Ok(out_vec)
}
trait IntoVecString {
fn to_vec_string(self) -> Vec<String>;
}
impl IntoVecString for &str {
fn to_vec_string(self) -> Vec<String> {
self.to_owned().split(".").map(|v| v.to_owned()).collect()
}
}
fn are_we_on_android() -> VicResult<bool> {
// fn to check if we are on android
let mut check_for_getprop = Command::new("sh");
check_for_getprop.arg("-c").arg("command -v getprop");
check_for_getprop.stdout(Stdio::null());
check_for_getprop.stderr(Stdio::null());
let status = check_for_getprop.status();
if status.is_ok() {
trace!("getprop command found");
// we could be on android, check further by getting the ro.build.version.release prop
let mut get_prop = Command::new("getprop");
get_prop.arg("ro.build.version.release");
get_prop.stdout(Stdio::null());
get_prop.stderr(Stdio::null());
if get_prop.status().is_ok() {
// we are on android
debug!("ANDROID platform found");
return Ok(true);
}
}
// no android found
return Ok(false);
}