Skip to content

Commit

Permalink
Run cargo fmt on the repo
Browse files Browse the repository at this point in the history
  • Loading branch information
nixpulvis committed Feb 19, 2024
1 parent 7bd8170 commit b7ad509
Show file tree
Hide file tree
Showing 31 changed files with 574 additions and 652 deletions.
22 changes: 5 additions & 17 deletions benches/compare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,22 @@ extern crate criterion;

use criterion::Criterion;

#[path="../tests/common/mod.rs"]
#[path = "../tests/common/mod.rs"]
mod common;

fn compare_script_benchmark(s: &str, c: &mut Criterion) {
let mut group = c.benchmark_group("hello world");

group.bench_function("oursh", |b| {
b.iter(|| {
oursh_release!(> s)
})
});
group.bench_function("oursh", |b| b.iter(|| oursh_release!(> s)));

group.bench_function("sh", |b| {
b.iter(|| {
shell!(> "/bin/sh", [] as [&str; 0], s)
})
});
group.bench_function("sh", |b| b.iter(|| shell!(> "/bin/sh", [] as [&str; 0], s)));

group.bench_function("zsh", |b| {
b.iter(|| {
shell!(> "/usr/bin/zsh", [] as [&str; 0], s)
})
b.iter(|| shell!(> "/usr/bin/zsh", [] as [&str; 0], s))
});

group.bench_function("fish", |b| {
b.iter(|| {
shell!(> "/usr/bin/fish", [] as [&str; 0], s)
});
b.iter(|| shell!(> "/usr/bin/fish", [] as [&str; 0], s));
});

group.finish();
Expand Down
8 changes: 2 additions & 6 deletions benches/piped.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,13 @@ extern crate criterion;

use criterion::Criterion;

#[path="../tests/common/mod.rs"]
#[path = "../tests/common/mod.rs"]
mod common;

fn piped_benchmark(c: &mut Criterion) {
let mut group = c.benchmark_group("oursh");

group.bench_function("empty", |b| {
b.iter(|| {
oursh_release!("")
})
});
group.bench_function("empty", |b| b.iter(|| oursh_release!("")));

group.bench_function("parse_error", |b| {
b.iter(|| {
Expand Down
4 changes: 2 additions & 2 deletions src/invocation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
//!
//!
//!
use std::ffi::CString;
use crate::program::{
Runtime,
posix::builtin::{self, Builtin},
Runtime,
};
use std::ffi::CString;

/// Sourcing profile startup scripts
///
Expand Down
3 changes: 1 addition & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,6 @@ pub mod program;

pub mod repl;


#[macro_use]
#[cfg(test)]
extern crate assert_matches;
Expand All @@ -119,7 +118,7 @@ mod tests {
debug!(1);
debug!(1 + 2);
debug!("addition: {}", 1 + 2);
debug!("{}", vec![1,2,3,4][2]);
debug!("{}", vec![1, 2, 3, 4][2]);
debug!("{} = {} * {}", 15, 3, 5);
}
}
43 changes: 21 additions & 22 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,28 @@
#![feature(exclusive_range_pattern)]

extern crate dirs;
extern crate docopt;
extern crate nix;
extern crate oursh;
extern crate termion;
extern crate dirs;

use docopt::{Docopt, Value};
use nix::sys::wait::WaitStatus;
use oursh::{
invocation::source_profile,
process::{Jobs, IO},
program::{parse_and_run, Error, Result, Runtime},
repl, VERSION,
};
use std::{
cell::RefCell,
env,
process::{Termination, ExitCode},
fs::File,
io::{self, Read},
cell::RefCell,
process::{ExitCode, Termination},
rc::Rc,
};
use nix::sys::wait::WaitStatus;
use docopt::{Docopt, Value};
use termion::is_tty;
use oursh::{
VERSION,
repl,
invocation::source_profile,
program::{parse_and_run, Runtime, Result, Error},
process::{Jobs, IO},
};

#[cfg(feature = "history")]
use oursh::repl::history::History;
Expand Down Expand Up @@ -77,11 +76,12 @@ fn main() -> MainResult {
// "with an extension for support of a
// leading <plus-sign> ('+') as noted below."
let mut args = Docopt::new(USAGE)
.and_then(|d|
d.version(Some(VERSION.into()))
.argv(env::args().into_iter())
.parse())
.unwrap_or_else(|e| e.exit());
.and_then(|d| {
d.version(Some(VERSION.into()))
.argv(env::args().into_iter())
.parse()
})
.unwrap_or_else(|e| e.exit());

// Elementary job management.
let mut jobs: Jobs = Rc::new(RefCell::new(vec![]));
Expand Down Expand Up @@ -112,13 +112,12 @@ fn main() -> MainResult {
if let Some(Value::Plain(Some(ref c))) = args.find("<command_string>") {
MainResult(parse_and_run(c, &mut runtime))
} else if let Some(Value::Plain(Some(ref filename))) = args.find("<command_file>") {
let mut file = File::open(filename)
.unwrap_or_else(|_| panic!("error opening file: {}", filename));
let mut file =
File::open(filename).unwrap_or_else(|_| panic!("error opening file: {}", filename));

// Fill a string buffer from the file.
let mut text = String::new();
file.read_to_string(&mut text)
.expect("error reading file");
file.read_to_string(&mut text).expect("error reading file");

// Run the program.
MainResult(parse_and_run(&text, &mut runtime))
Expand Down Expand Up @@ -161,7 +160,7 @@ impl Termination for MainResult {
match self.0 {
Ok(WaitStatus::Exited(_pid, code)) => ExitCode::from(code as u8),
Ok(WaitStatus::Signaled(_pid, _signal, _coredump)) => ExitCode::from(128),
Ok(_) => ExitCode::from(0), // TODO: Is this even remotely correct?
Ok(_) => ExitCode::from(0), // TODO: Is this even remotely correct?
Err(Error::Read) => ExitCode::from(1),
Err(Error::Parse) => ExitCode::from(2),
Err(Error::Runtime) => ExitCode::from(127),
Expand Down
4 changes: 1 addition & 3 deletions src/process/io.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
use nix::unistd::{close, dup2};
use std::os::unix::io::RawFd;
use nix::{
unistd::{dup2, close},
};

/// File descriptors for use in processes and threads
#[derive(Debug, Copy, Clone)]
Expand Down
17 changes: 6 additions & 11 deletions src/process/jobs.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
use std::{
rc::Rc,
cell::RefCell,
};
use crate::process::{ProcessGroup, Wait};
use nix::sys::wait::WaitStatus;
use crate::process::{Wait, ProcessGroup};
use std::{cell::RefCell, rc::Rc};

/// Shared job handling structure
///
Expand All @@ -17,21 +14,19 @@ pub fn retain_alive(jobs: &mut Jobs) {
let id = job.0.clone();
let body = job.1.leader().body();
match job.1.leader().status() {
Ok(WaitStatus::StillAlive) => {
true
},
Ok(WaitStatus::StillAlive) => true,
Ok(WaitStatus::Exited(pid, code)) => {
println!("[{}]+\tExit({})\t{}\t{}", id, code, pid, body);
false
},
}
Ok(WaitStatus::Signaled(pid, signal, _)) => {
println!("[{}]+\t{}\t{}\t{}", id, signal, pid, body);
false
},
}
Ok(_) => {
println!("unhandled");
true
},
}
Err(e) => {
if nix::errno::Errno::ECHILD != e {
println!("err: {:?}", e);
Expand Down
39 changes: 16 additions & 23 deletions src/process/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,12 @@
//! More resources from the source at:
//! [www.win.tue.nl/~aeb/linux/lk/lk-10](https://www.win.tue.nl/~aeb/linux/lk/lk-10.html).

use std::{
borrow::Cow,
process::exit,
ffi::CString,
};
use nix::{
errno::Errno,
unistd::{self, execvp, getpid, Pid, ForkResult},
sys::wait::{waitpid, WaitStatus, WaitPidFlag},
sys::wait::{waitpid, WaitPidFlag, WaitStatus},
unistd::{self, execvp, getpid, ForkResult, Pid},
};
use std::{borrow::Cow, ffi::CString, process::exit};

mod io;
pub use self::io::IO;
Expand All @@ -31,7 +27,6 @@ mod session;
mod signal;
mod thread;


/// A process to be executed by various means
///
/// The shell's main job is to run commands. Each job has various arguments, and rules about what
Expand All @@ -57,9 +52,11 @@ impl Process {
}

pub fn body(&self) -> String {
self.argv.iter().map(|a| {
a.to_string_lossy()
}).collect::<Vec<Cow<str>>>().join(" ")
self.argv
.iter()
.map(|a| a.to_string_lossy())
.collect::<Vec<Cow<str>>>()
.join(" ")
}

pub fn pid(&self) -> Pid {
Expand All @@ -69,12 +66,7 @@ impl Process {
/// Run a shell job in the background.
pub fn fork(argv: Vec<CString>, io: IO) -> Result<Self, nix::Error> {
match unsafe { unistd::fork() } {
Ok(ForkResult::Parent { child }) => {
Ok(Process {
argv,
pid: child,
})
},
Ok(ForkResult::Parent { child }) => Ok(Process { argv, pid: child }),
Ok(ForkResult::Child) => {
let process = Process {
argv,
Expand All @@ -87,21 +79,23 @@ impl Process {
let name = process.argv[0].to_string_lossy();
eprintln!("oursh: {}: command not found", name);
exit(127);
},
}
_ => exit(128),
}
} else {
unreachable!()
}
},
}
Err(e) => Err(e),
}
}

fn exec(&self) -> Result<(), nix::Error> {
execvp(&self.argv[0], &self.argv.iter()
.map(|a| a.as_c_str())
.collect::<Vec<_>>()[..]).map(|_| ())
execvp(
&self.argv[0],
&self.argv.iter().map(|a| a.as_c_str()).collect::<Vec<_>>()[..],
)
.map(|_| ())
}
}

Expand Down Expand Up @@ -130,7 +124,6 @@ impl Wait for Process {
}
}


/// Processes groups are used for things like pipelines and background jobs
///
/// The system call `int setpgid(pid_t pid, pid_t pgid)` is used to set.
Expand Down
30 changes: 14 additions & 16 deletions src/program/basic.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
//! Single command programs with no features.
use std::{
io::BufRead,
ffi::CString,
};
use nix::sys::wait::WaitStatus;
use crate::{
process::{ProcessGroup, Process, Wait},
program::{Runtime, Result, Error},
process::{Process, ProcessGroup, Wait},
program::{Error, Result, Runtime},
};

use nix::sys::wait::WaitStatus;
use std::{ffi::CString, io::BufRead};

/// A basic program with only a single command.
#[derive(Debug)]
Expand Down Expand Up @@ -38,7 +34,6 @@ impl super::Program for Program {
}
}


/// A single poorly parsed command.
#[derive(Debug)]
pub struct Command(String);
Expand All @@ -47,23 +42,26 @@ impl super::Command for Command {}

impl super::Run for Command {
fn run(&self, runtime: &mut Runtime) -> Result<WaitStatus> {
let argv = self.0.split_whitespace().map(|a| {
CString::new(a).expect("error reading argument")
}).collect();
let argv = self
.0
.split_whitespace()
.map(|a| CString::new(a).expect("error reading argument"))
.collect();

let status = if runtime.background {
let job = Process::fork(argv, runtime.io).map_err(|_| Error::Runtime)?;
let status = job.status();
runtime.jobs.borrow_mut().push(("???".into(), ProcessGroup(job)));
runtime
.jobs
.borrow_mut()
.push(("???".into(), ProcessGroup(job)));
status
} else {
let job = Process::fork(argv, runtime.io).map_err(|_| Error::Runtime)?;
job.wait()
};
match status {
Ok(WaitStatus::Exited(p, c)) if c == 0 => {
Ok(WaitStatus::Exited(p, c))
},
Ok(WaitStatus::Exited(p, c)) if c == 0 => Ok(WaitStatus::Exited(p, c)),
_ => Err(Error::Runtime),
}
}
Expand Down
Loading

0 comments on commit b7ad509

Please sign in to comment.