Skip to content
Draft

Repl #68

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 9 additions & 7 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ maintenance = { status = "experimental" }
travis-ci = { repository = "https://github.com/nixpulvis/oursh" }

[features]
default = ["raw", "shebang-block"]
default = ["raw", "history", "completion", "shebang-block"]

# TODO: Justify and explain features.
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As always, I think documentation will mark the end of the PR.

Generally in a collaborative environment (which this is currently not), I like this, writing a summary gives people time to review as well as giving future developers the needed information.


Expand All @@ -33,13 +33,13 @@ shebang-block = []
# things like arrow keys for history, and cursor editing.
raw = []

# # Save the history of commands (entered) for quick recall.
# # TODO: Stop depending on raw if this ever interacts with anything beside the
# # RELP input.
# history = ["raw"]
# Save the history of commands (entered) for quick recall.
# TODO: Stop depending on raw if this ever interacts with anything beside the
# RELP input.
history = ["raw"]

# # REPL tab completion.
# completion = ["raw"]
# REPL tab completion.
completion = ["raw", "tabwriter"]

[dependencies]
docopt = "1.1"
Expand All @@ -54,6 +54,8 @@ ctrlc = "3.1"
# Option 2: http://ticki.github.io/blog/making-terminal-applications-in-rust-with-termion/
termion = "1.5"
rustyline = "8"
tabwriter = { version = "1.2", optional = true }


[build-dependencies]
lalrpop = "0.19"
Expand Down
21 changes: 10 additions & 11 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,21 +76,20 @@ fn main() -> MainResult {
// TODO: From sh docs:
// "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());

let args = Docopt::new(USAGE).and_then(|d|
d.version(Some(VERSION.into()))
.argv(env::args())
.parse())
.unwrap_or_else(|e| e.exit());

// Default inputs and outputs for the processes.
let io = IO::default();
// Elementary job management.
let mut jobs: Jobs = Rc::new(RefCell::new(vec![]));

// Default inputs and outputs.
let mut io = IO::default();

#[cfg(feature = "history")]
let mut history = History::load();

let mut runtime = Runtime {
io,
jobs: &mut jobs,
Expand Down Expand Up @@ -141,7 +140,7 @@ fn main() -> MainResult {
// Trap SIGINT.
ctrlc::set_handler(move || println!()).unwrap();

let result = repl::start(stdin, stdout, &mut io, &mut jobs, &mut args);
let result = repl::start(stdin, stdout, &mut runtime);
MainResult(result)
} else {
// Fill a string buffer from STDIN.
Expand Down
2 changes: 1 addition & 1 deletion src/program/posix/builtin/cd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ impl Builtin for Cd {
};
let dst = home.as_str();
chdir(dst).map(|_| {
set_var("PWD", &dst);
set_var("PWD", dst);
WaitStatus::Exited(Pid::this(), 0)
})
.map_err(|_| Error::Runtime)
Expand Down
2 changes: 1 addition & 1 deletion src/program/posix/builtin/dot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ impl Builtin for Dot {
}
2 => {
let path = argv[1].to_str().unwrap();
if let Ok(mut file) = File::open(&path) {
if let Ok(mut file) = File::open(path) {
let mut contents = String::new();
if file.read_to_string(&mut contents).is_ok() {
parse_and_run(&contents, runtime)
Expand Down
64 changes: 26 additions & 38 deletions src/repl/action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,23 @@ use termion::{
cursor::DetectCursorPos,
raw::RawTerminal,
};
use docopt::ArgvMap;
use crate::program::{Runtime, parse_and_run};
use crate::process::{IO, Jobs};
use crate::repl::prompt;

#[cfg(feature = "history")]
use super::history::History;

#[cfg(feature = "completion")]
use super::completion::*;
use super::completion::{self, *};


pub struct Action;

pub struct ActionContext<'a> {
pub struct ActionContext<'a, 'b> {
pub stdout: &'a mut RawTerminal<Stdout>,
pub io: &'a mut IO,
pub jobs: &'a mut Jobs,
pub args: &'a mut ArgvMap,
pub runtime: &'a mut Runtime<'b>,
// TODO: Remove this field.
#[cfg(feature = "raw")]
pub prompt_length: u16,
#[cfg(feature = "raw")]
pub text: &'a mut String,
#[cfg(feature = "history")]
pub history: &'a mut History,
}

#[cfg(feature = "raw")]
Expand All @@ -43,30 +34,24 @@ impl Action {

// Run the command.
context.stdout.suspend_raw_mode().unwrap();
let mut runtime = Runtime {
background: false,
io: context.io.clone(),
jobs: context.jobs,
args: context.args,
prompt::ps0(&mut context.stdout);
if parse_and_run(context.text, context.runtime).is_ok() {
#[cfg(feature = "history")]
history: context.history,
};
if parse_and_run(context.text, &mut runtime).is_ok() {
#[cfg(feature = "history")]
context.history.add(&context.text, 1);
context.runtime.history.add(context.text, 1);
}
context.stdout.activate_raw_mode().unwrap();

// Reset for the next program.
context.text.clear();
#[cfg(feature = "history")]
context.history.reset_index();
context.runtime.history.reset_index();

prompt::ps1(&mut context.stdout);
}

pub fn insert(context: &mut ActionContext, c: char) {
if let Ok((x, y)) = context.stdout.cursor_pos() {
// XXX: Why did this panic?
let i = (x - context.prompt_length) as usize;
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Worth looking into this again for a bit.

context.text.insert(i, c);
print!("{}{}",
Expand Down Expand Up @@ -108,7 +93,7 @@ impl Action {

// Save history to file in $HOME.
#[cfg(feature = "history")]
context.history.save();
context.runtime.history.save().unwrap();

// Manually drop the raw terminal.
// TODO: Needed?
Expand Down Expand Up @@ -164,9 +149,9 @@ impl Action {
print!("{}{}",
termion::cursor::Left(1000), // XXX
termion::clear::CurrentLine);
context.prompt.display(&mut context.stdout);
prompt::ps1(&mut context.stdout);

if let Some(history_text) = context.history.get_up() {
if let Some(history_text) = context.runtime.history.get_up() {
*context.text = history_text;
print!("{}", context.text);
}
Expand All @@ -178,9 +163,9 @@ impl Action {
print!("{}{}",
termion::cursor::Left(1000), // XXX
termion::clear::CurrentLine);
context.prompt.display(&mut context.stdout);
prompt::ps1(&mut context.stdout);

if let Some(history_text) = context.history.get_down() {
if let Some(history_text) = context.runtime.history.get_down() {
*context.text = history_text;
print!("{}", context.text);
context.stdout.flush().unwrap();
Expand All @@ -191,20 +176,23 @@ impl Action {

#[cfg(feature = "completion")]
pub fn complete(context: &mut ActionContext) {
match complete(&context.text) {
match complete(context.text) {
Completion::Partial(possibilities) => {
if possibilities.len() > 25 {
print!("\n\r");
for possibility in possibilities {
print!("{}\n\r", possibility);
}
print!("\n\r");
} else {
print!("\n\r{}\n\r", possibilities.join("\t"));
}
println!();
print!("{}{}",
termion::cursor::Left(1000), // XXX
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it worth fixing this now?

termion::clear::CurrentLine);
context.stdout.flush().unwrap();
context.stdout.suspend_raw_mode().unwrap();
completion::write_table(&mut context.stdout, &possibilities);
context.stdout.activate_raw_mode().unwrap();
print!("{}{}",
termion::cursor::Left(1000), // XXX
termion::clear::CurrentLine);
prompt::ps1(&mut context.stdout);
print!("{}", context.text);
context.stdout.flush().unwrap();

},
Completion::Complete(t) => {
*context.text = t;
Expand Down
37 changes: 36 additions & 1 deletion src/repl/completion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ use std::{
fs,
cmp::Ordering::Equal,
os::unix::fs::PermissionsExt,
io::Write,
};
use tabwriter::TabWriter;

/// The result of a query for text completion.
///
Expand Down Expand Up @@ -134,9 +136,10 @@ pub fn executable_completions(text: &str) -> Completion {
0 => Completion::None,
1 => Completion::Complete(matches.remove(0)),
_ => {
// TODO: Support POSIX style lexicographical order?
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm torn on this, as am I torn on row major vs column major order.

matches.sort_by(|a, b| {
match a.len().cmp(&b.len()) {
Equal => b.cmp(&a),
Equal => b.cmp(a),
o => o
}
});
Expand Down Expand Up @@ -168,6 +171,38 @@ pub fn path_complete(text: &str) -> Completion {
}
}

pub fn write_table(writer: impl Write, words: &[String]) {
// TODO: Handle empty case better.
let max_length = words.iter().max_by(|a,b| a.len().cmp(&b.len())).unwrap().len() as u16;
// TODO: Can this function be called from outside a terminal environment?
let (width, _height) = termion::terminal_size().unwrap();
let padding = 5;
let columns = width / (max_length + padding);
let mut tw = TabWriter::new(writer).padding(padding as usize);
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We may want to ditch this albeit neat method of table generation and go for something that will produce better results in our case.

Issues at the moment:

  • Sort order is inconsistent with expectation
  • Every column is treated as if it was as wide as the widest

// TODO: Determine table width/height and calculate iteration better
let mut _row = 0;
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leave a note here about what we are planning on using row for.

let mut col = 0;
let mut needs_newline = false;
for word in words {
let _r = tw.write(word.as_bytes()).unwrap();

if col == columns-1 {
col = 0;
_row += 1;
let _r = tw.write(b"\n").unwrap();
needs_newline = false;
} else {
col += 1;
let _r = tw.write(b"\t").unwrap();
needs_newline = true;
}
}
if needs_newline {
let _r = tw.write(b"\n").unwrap();
}
tw.flush().unwrap();
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
12 changes: 6 additions & 6 deletions src/repl/history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ impl History {
return;
}

// HACK: There's got to be a cleaner way.
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❤️

let mut index = 0;
if self.1.iter().enumerate().find(|(i, (t, _))| {
index = *i;
text == t
}).is_some() {
if self.1.iter().enumerate()
.any(|(_,(t, i))| {
index = *i;
text == t })
{
self.1[index].1 += count;
let text = self.1.remove(index);
self.1.insert(0, text);
Expand Down Expand Up @@ -86,7 +86,7 @@ impl History {
// println!("{:?}", s);
// })
// }).collect::<Vec<String, usize>>();
let hist = contents.split("\n").map(|s| {
let hist = contents.split('\n').map(|s| {
(String::from(s), 0)
});

Expand Down
Loading