Skip to content
Merged
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
86 changes: 82 additions & 4 deletions src/helper.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,29 @@
use std::cell::RefCell;
use std::rc::Rc;

use rustyline::completion::{Completer, Pair, extract_word};
use rustyline::highlight::Highlighter;
use rustyline::hint::Hinter;
use rustyline::validate::Validator;
use rustyline::{Context, Helper, Result};

use crate::state::ShellState;

const BUILTINS: &[&str] = &[
"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "base", "header", "exit", "help",
"history", "rerun", "set", "unset", "save", "run", "vars", "headers", "requests", "clear",
"history", "rerun", "set", "timeout", "unset", "save", "run", "vars", "headers", "requests",
"clear",
];

pub struct ShellHelper;
pub struct ShellHelper {
state: Rc<RefCell<ShellState>>,
}

impl ShellHelper {
pub fn new(state: Rc<RefCell<ShellState>>) -> Self {
ShellHelper { state }
}
}

impl Helper for ShellHelper {}
impl Hinter for ShellHelper {
Expand All @@ -23,9 +37,9 @@ impl Completer for ShellHelper {

fn complete(&self, line: &str, pos: usize, _ctx: &Context<'_>) -> Result<(usize, Vec<Pair>)> {
let (start, word) = extract_word(line, pos, None, |c| c == ' ');
let first_word = line[..start].trim().is_empty();
let before_cursor = line[..start].trim();

if first_word {
if before_cursor.is_empty() {
let matches: Vec<Pair> = BUILTINS
.iter()
.copied()
Expand All @@ -39,6 +53,70 @@ impl Completer for ShellHelper {
return Ok((start, matches));
}

let parts: Vec<&str> = before_cursor.split_whitespace().collect();

match parts[0] {
"run" => {
let state = self.state.borrow();
let matches: Vec<Pair> = state
.get_all_requests()
.keys()
.filter(|name| name.starts_with(word))
.map(|name| Pair {
display: name.clone(),
replacement: name.clone(),
})
.collect();
return Ok((start, matches));
}
"unset" if parts.len() == 1 => {
let state = self.state.borrow();
let mut matches: Vec<Pair> = state
.get_variables()
.keys()
.filter(|name| name.starts_with(word))
.map(|name| Pair {
display: name.clone(),
replacement: name.clone(),
})
.collect();
if "header".starts_with(word) {
matches.push(Pair {
display: "header".to_string(),
replacement: "header".to_string(),
});
}
return Ok((start, matches));
}
"unset" if parts.len() >= 2 && parts[1] == "header" => {
let state = self.state.borrow();
let matches: Vec<Pair> = state
.get_headers()
.keys()
.filter(|name| name.starts_with(word))
.map(|name| Pair {
display: name.clone(),
replacement: name.clone(),
})
.collect();
return Ok((start, matches));
}
"header" => {
let state = self.state.borrow();
let matches: Vec<Pair> = state
.get_headers()
.keys()
.filter(|name| name.starts_with(word))
.map(|name| Pair {
display: name.clone(),
replacement: name.clone(),
})
.collect();
return Ok((start, matches));
}
_ => {}
}

Ok((start, vec![]))
}
}
40 changes: 23 additions & 17 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::cell::RefCell;
use std::env;
use std::path::PathBuf;
use std::rc::Rc;

use reqsh::builtin::{ControlFlow, handle};
use reqsh::help::help_text;
Expand All @@ -20,7 +22,7 @@ fn history_path() -> PathBuf {
home.join(".reqsh_history")
}

fn run_repl(ctx: &mut ShellState) {
fn run_repl(ctx: Rc<RefCell<ShellState>>) {
let config = Config::builder()
.history_ignore_space(true)
.completion_type(CompletionType::List)
Expand All @@ -29,7 +31,7 @@ fn run_repl(ctx: &mut ShellState) {

let hist_path = history_path();
let mut rl = Editor::with_config(config).unwrap();
rl.set_helper(Some(ShellHelper));
rl.set_helper(Some(ShellHelper::new(ctx.clone())));
rl.load_history(&hist_path).unwrap_or_default();

loop {
Expand All @@ -53,19 +55,23 @@ fn run_repl(ctx: &mut ShellState) {

match parse(raw) {
Ok(parsed) => match parsed {
Parsed::Builtin(cmd) => match handle(cmd, ctx, rl.history()) {
Ok(ControlFlow::Continue) => {}
Ok(ControlFlow::Exit) => {
break;
}
Err(e) => {
eprintln!("{}", e.red().bold());
Parsed::Builtin(cmd) => {
let mut state = ctx.borrow_mut();
match handle(cmd, &mut state, rl.history()) {
Ok(ControlFlow::Continue) => {}
Ok(ControlFlow::Exit) => {
break;
}
Err(e) => {
eprintln!("{}", e.red().bold());
}
}
},
}

Parsed::Request(req) => {
ctx.set_last_request(req.clone());
match execute(req, ctx) {
ctx.borrow_mut().set_last_request(req.clone());
let state = ctx.borrow();
match execute(req, &state) {
Ok(res) => {
println!("{}", res);
}
Expand Down Expand Up @@ -149,8 +155,8 @@ fn main() {

match args.as_slice() {
[] => {
let mut ctx = ShellState::new();
run_repl(&mut ctx);
let ctx = Rc::new(RefCell::new(ShellState::new()));
run_repl(ctx);
}

[arg] if arg == "--help" || arg == "-h" => {
Expand All @@ -166,9 +172,9 @@ fn main() {
eprintln!("Invalid timeout: {value}");
std::process::exit(1);
});
let mut ctx = ShellState::new();
ctx.set_timeout(secs);
run_repl(&mut ctx);
let ctx = Rc::new(RefCell::new(ShellState::new()));
ctx.borrow_mut().set_timeout(secs);
run_repl(ctx);
}

[unknown] => {
Expand Down
Loading