redox/programs/init/src/main.rs

80 lines
3 KiB
Rust
Raw Normal View History

use std::env;
2016-09-11 06:06:09 +02:00
use std::fs::File;
2016-10-15 05:11:29 +02:00
use std::io::{BufRead, BufReader, Result};
use std::process::Command;
2016-10-15 05:11:29 +02:00
pub fn run(file: &str) -> Result<()> {
let file = File::open(file)?;
2016-09-11 23:56:48 +02:00
let reader = BufReader::new(file);
2016-09-11 06:06:09 +02:00
for line_result in reader.lines() {
2016-10-15 05:11:29 +02:00
let line = line_result?;
let line = line.trim();
if ! line.is_empty() && ! line.starts_with('#') {
let mut args = line.split(' ');
if let Some(cmd) = args.next() {
match cmd {
2016-10-15 05:11:29 +02:00
"cd" => if let Some(dir) = args.next() {
if let Err(err) = env::set_current_dir(dir) {
println!("init: failed to cd to '{}': {}", dir, err);
}
} else {
println!("init: failed to cd: no argument");
},
"echo" => {
if let Some(arg) = args.next() {
print!("{}", arg);
}
for arg in args {
print!(" {}", arg);
}
print!("\n");
},
2016-10-15 05:11:29 +02:00
"export" => if let Some(var) = args.next() {
let mut value = String::new();
if let Some(arg) = args.next() {
value.push_str(&arg);
}
2016-10-15 05:11:29 +02:00
for arg in args {
value.push(' ');
value.push_str(&arg);
}
env::set_var(var, value);
} else {
2016-10-15 05:11:29 +02:00
println!("init: failed to export: no argument");
},
"run" => if let Some(new_file) = args.next() {
if let Err(err) = run(&new_file) {
println!("init: failed to run '{}': {}", new_file, err);
}
} else {
println!("init: failed to run: no argument");
},
_ => {
let mut command = Command::new(cmd);
for arg in args {
command.arg(arg);
}
match command.spawn() {
Ok(mut child) => match child.wait() {
Ok(_status) => (), //println!("init: waited for {}: {:?}", line, status.code()),
Err(err) => println!("init: failed to wait for '{}': {}", line, err)
},
Err(err) => println!("init: failed to execute '{}': {}", line, err)
}
}
}
}
}
2016-09-11 06:06:09 +02:00
}
2016-10-15 05:11:29 +02:00
Ok(())
}
pub fn main() {
if let Err(err) = run("initfs:etc/init.rc") {
println!("init: failed to run initfs:etc/init.rc: {}", err);
}
}