Compare commits

13 Commits

Author SHA1 Message Date
fbf6be2779 drone
All checks were successful
continuous-integration/drone/push Build is passing
2023-07-14 12:15:36 +02:00
0aabd711a3 Merge pull request 'dev' (#4) from dev into main
Reviewed-on: #4
2023-05-01 13:44:36 +02:00
f333069a32 Fixed the ./ bug 2023-05-01 13:42:56 +02:00
7677adfafe Readme 2023-03-14 22:27:43 +01:00
1eefd44a89 Merge pull request 'dev' (#3) from dev into main
Reviewed-on: #3
2023-03-04 20:26:00 +01:00
09cea688b7 Added export command 2023-03-04 20:17:22 +01:00
5743678e23 Fixed bug on incorrect command, missing carriage return on cd 2023-03-04 19:56:50 +01:00
1e052f1a79 Merge pull request 'dev' (#2) from dev into main
Reviewed-on: #2
2023-03-04 14:31:17 +01:00
522b8e7037 Add doc 2023-03-04 14:30:13 +01:00
643c69623c Forget to add the config part 2023-03-04 14:28:20 +01:00
68dc23a15e Added a dirty implementation of env var setting 2023-03-04 14:19:01 +01:00
1eb1b239c2 Reformatted the command execution part 2023-03-02 14:49:34 +01:00
488c9c6e0a Started to implement CmdOutput - keep going... 2023-03-02 11:46:21 +01:00
7 changed files with 474 additions and 57 deletions

View File

@ -3,8 +3,38 @@ type: docker
name: default
steps:
- name: test
image: rust:1.66.0-alpine3.17
- name: build
image: rust:latest
commands:
- cargo build --verbose
- cargo build --release
---
kind: pipeline
type: docker
name: release
steps:
- name: build
image: rust:latest
commands:
- cargo build --release
when:
event:
include:
- tag
- name: create-release
image: plugins/gitea-release:latest
custom_dns: [ 9.9.9.9 ]
settings:
api_key:
from_secret: gitea_api
base_url: https://gitea.squi.fr
note: This is an automated release of sqish.
files:
- ./target/release/portnut
when:
event:
include:
- tag

View File

@ -14,12 +14,16 @@ Sqish is now my default shell on my home computer, and I'll keep adding features
Also keep in mind I'm a beginner in Rust, so the code is pretty dirty; I will probably come around to reformating it once I have all the features I want and ironed out all the bugs.
TODO:
* Allow redirecting >> to the end of a file ?
* Allow && in commands ?
* Improve word jumping
* Add arguments : run a file (sqish myexec) which I believe would make it compatible with gdb ?
* Add export command
# TODO
TODO (Reformat):
* Creating a struct "shell" that contains builder method taking an input and an output as parameters as well as a conf could be cool
TODO (features):
* Add a &&
TODO (Bugz):
* Autocomplete shits itself when typing a path starting with /
## sqishrc (Config)
See the included sqishrc file included for comments, and copy it as ~/.sqishrc for use (optionnal).

View File

@ -44,3 +44,8 @@ hotkeys:
#Init : A command to run on startup. Can be used for many things...
init: "echo ---Initialization over---"
#Env : to set environment variables at launch
env:
CAT: "meow"
PATH: /home/cat/bin:$PATH

View File

@ -1,5 +1,6 @@
#[allow(unused_must_use)]
pub mod shell {
use regex::Regex;
use std::io::Stdout;
use std::process::Command;
use std::io::stdin;
@ -14,7 +15,7 @@ pub mod shell {
use termion::input::TermRead;
use termion::raw::IntoRawMode;
use termion::raw::RawTerminal;
use termion::cursor;
use termion::{color, cursor};
use termion;
use unicode_segmentation::UnicodeSegmentation;
use std::collections::HashMap;
@ -33,7 +34,61 @@ pub mod shell {
extern crate shell_words;
extern crate ctrlc;
fn change_dir(args: &Vec<String>, previous_command: &mut Option<Stdio>) {
///Stores essential terminal variables
struct TermElements {
//Stores currently typed command
command: String,
//Current cursor position in the line
cur_pos: usize,
//Max position of cursor in the line
max_pos: usize,
stdout: RawTerminal<Stdout>,
//Current history number
current_number: i32,
//Configuration
conf: SqishConf,
}
///Used to unify command output and error handling
///across functions
struct CmdOutput {
outp: String,
rc: i16,
}
impl CmdOutput {
fn from_values(output: String, rc: i16) -> CmdOutput {
let myoutp = CmdOutput {
outp: output,
rc: rc,
};
return myoutp;
}
fn new_empty() -> CmdOutput {
let outp = CmdOutput {
outp: String::new(),
rc: 0,
};
return outp;
}
}
fn export_var(command: String) -> Result<CmdOutput, CmdOutput> {
let cmd_split = command.split('=').collect::<Vec<&str>>();
if cmd_split.len() < 2 {
return Err(CmdOutput::from_values(
String::from("Please a format such as : VAR=value"),
255));
}
let key = String::from(cmd_split[0].to_uppercase());
let val = String::from(cmd_split[1]);
let mut map = HashMap::new();
map.insert(key, val);
set_envvars(&map);
return Ok(CmdOutput::new_empty());
}
fn change_dir(args: &Vec<String>, previous_command: &mut Option<Stdio>) -> Result<CmdOutput, CmdOutput> {
let homedir = dirs::home_dir().unwrap().into_os_string().into_string().unwrap();
//let new_dir = args.peekable().peek().map_or(homedir.as_str(), |x| *x);
let mut new_dir = String::new();
@ -45,14 +100,15 @@ pub mod shell {
let root = Path::new(&new_dir);
if let Err(e) = env::set_current_dir(&root) {
eprintln!(" Err: {}", e);
} else {
println!("");
}
return Err(CmdOutput::from_values(
format!("Error setting directory to {}, got {:?}",
new_dir, e), -1));
};
*previous_command = None;
return Ok(CmdOutput::new_empty());
}
fn print_hist(previous_command: &mut Option<Stdio>, command_next: bool) {
fn print_hist(previous_command: &mut Option<Stdio>, command_next: bool) -> Result<CmdOutput, CmdOutput> {
//let stdout = Stdio::inherit();
let res = get_history();
match res {
@ -65,30 +121,45 @@ pub mod shell {
print!("{}", r);
}
},
Err(e) => eprintln!(" Err reading history: {}", e),
Err(e) => {
return Err(CmdOutput::from_values(format!("Could not print history, got {:?}", e), 255));
},
}
return Ok(CmdOutput::new_empty());
}
fn process_line(input: &str) -> String {
fn process_line(input: &str) -> Result<CmdOutput, CmdOutput> {
let mut commands = input.trim().split("|").peekable();
let mut previous_command = None;
let mut resultat = String::new();
let mut rc: i16 = 0;
while let Some(command) = commands.next() {
let parts = match shell_words::split(&command.trim()) {
Ok(w) => w,
Err(e) => { return format!("Error parsing the command : {:?}", e); },
Err(e) => {
return Err(CmdOutput::from_values(format!("Could not parse command {:?}", e), -1));
},
};
if parts.len() < 1 {
return Err(CmdOutput::from_values(String::from("Could not parse command"), -1));
}
let command = parts[0].as_str();
let args = Vec::from(&parts[1..]);
match command {
"cd" => {
change_dir(&args, &mut previous_command);
change_dir(&args, &mut previous_command)?;
print!("\r\n");
},
"history" => {
let next = commands.peek().is_some();
print_hist(&mut previous_command, next);
print_hist(&mut previous_command, next)?;
},
"export" => {
export_var(args.join(" "))?;
print!("\r\n");
},
command => {
if commands.peek().is_some() {
@ -126,7 +197,7 @@ pub mod shell {
Ok(h) => h,
Err(_) => {
let err_string = format!("Not found : {}", command);
return String::from(err_string);
return Err(CmdOutput::from_values(err_string, -1));
},
};
@ -140,12 +211,15 @@ pub mod shell {
previous_command = None;
let format_res = format!("{}",
status);
let _ = &mut resultat.push_str(&format_res);
*&mut rc = format_res.parse::<i16>().unwrap();
*&mut resultat = String::from_utf8(output.stdout).unwrap();
//let _ = &mut resultat.push_str(&format_res);
}
},
};
}
return resultat;
//return resultat;
return Ok(CmdOutput::from_values(resultat, rc));
}
fn replace_signs(line: &String) -> String {
@ -165,17 +239,18 @@ pub mod shell {
return ayo;
}
fn handle_input(line: &str) -> String {
fn handle_input(line: &str) -> Result<CmdOutput, CmdOutput> {
//history callback
if (line.len() > 0) && (line.starts_with('!')) {
let command_found = treat_history_callback(line);
match command_found {
Some(c) => {
write_to_history(&c);
let outp = process_line(&c);
return outp;
return process_line(&c);
},
None => return String::from(" "),
None => return Err(CmdOutput::from_values(
String::from("No such value"),
255)),
};
//Regular command
} else if line.len() > 0 {
@ -184,7 +259,7 @@ pub mod shell {
//Nothing
} else {
//Command was empty, new line
return String::from("");
return Ok(CmdOutput::new_empty());
}
}
@ -262,25 +337,36 @@ pub mod shell {
current_number: &mut i32,
conf: &mut SqishConf,
stdout: &mut RawTerminal<Stdout>) {
//NORMAL CMD
if (mycommand != &String::from("")) && (mycommand != &String::from("exit")) {
//Run the command
let comm = replace_signs(&mycommand);
RawTerminal::suspend_raw_mode(&stdout);
let res = handle_input(&comm);
//Display the results
match res {
Ok(_) => (),
Err(e) => {
println!("\r\n{}Got error {}, RC : {:?}{}",
color::Fg(color::Red),
e.outp,
e.rc,
color::Fg(color::Reset));
},
};
//Prepare for a new command
RawTerminal::activate_raw_mode(&stdout);
mycommand.clear();
for line in res.split("\r\n") {
if line != "" && line.starts_with('N'){
write!(stdout, "{}\r\n", line);
}
}
conf.update_prompt(get_curr_history_number());
write!(stdout, "{}", conf.promptline).unwrap();
stdout.flush();
*current_number += 1;
//EXITTING
} else if mycommand == &String::from("exit") {
write!(stdout, "\r\nThanks for using Sqish!\r\nSayonara \r\n");
RawTerminal::suspend_raw_mode(&stdout);
std::process::exit(0);
//EMPTY LINE
} else {
conf.update_prompt(get_curr_history_number());
write!(stdout, "\r\n{}", conf.promptline).unwrap();
@ -350,6 +436,7 @@ pub mod shell {
aliases: HashMap::new(),
hotkeys: HashMap::new(),
init: String::new(),
env: HashMap::new(),
};
let ret_line = format!("Could not build conf, got {}\
\r\nUsing default promptline", e);
@ -516,20 +603,6 @@ pub mod shell {
write!(elems.stdout, "{}{}", elems.conf.promptline, elems.command);
}
struct TermElements {
//Stores currently typed command
command: String,
//Current cursor position in the line
cur_pos: usize,
//Max position of cursor in the line
max_pos: usize,
stdout: RawTerminal<Stdout>,
//Current history number
current_number: i32,
//Configuration
conf: SqishConf,
}
fn jmp_nxt_word(elems: &mut TermElements) {
let steps = find_next_space(&elems.cur_pos, &elems.max_pos, &elems.command);
//println!("steps: {:?} cur {:?} max {:?}", steps, elems.cur_pos, elems.max_pos);
@ -588,6 +661,38 @@ pub mod shell {
};
}
//I smell horrible code in here
fn set_envvars(vars: &HashMap<String, String>) {
let vars = vars.clone();
let re = Regex::new(r"\$[A-Za-z_]+").unwrap();
for (key, value) in vars {
let mut after = value.clone();
let mut nbr_of_vars = *&value.matches('$').count();
while nbr_of_vars >= 1 {
let temp = after.clone();
let caps = re.captures(&temp).unwrap();
for cap in caps.iter() {
match cap {
Some(c) => {
let myvar = String::from(c.as_str()).replace('$', "");
match env::var(myvar) {
Ok(r) => {
*&mut after = after.replace(c.as_str(), &r);
},
Err(_) => continue,
};
},
None => continue,
};
}
nbr_of_vars -= 1;
}
env::set_var(&key, &after);
}
}
//THE ENTRYPOINT FUNCTION
pub fn run_raw() {
@ -610,6 +715,7 @@ pub mod shell {
//Initializing
write!(elems.stdout, "\r\n ---Sqish initializing--- \r\n{}", elems.conf.promptline);
elems.stdout.flush();
set_envvars(&elems.conf.env);
if elems.conf.init != String::from("") {
run_cmd(&mut String::from(&elems.conf.init), &mut elems.current_number, &mut elems.conf, &mut elems.stdout);

View File

@ -25,6 +25,8 @@ pub struct Search {
local_search: bool,
//the kind of search
search_type: SearchType,
//the original command
original: String,
}
impl Search {
@ -83,6 +85,7 @@ impl Search {
searchee: searchee,
local_search: local,
search_type: search_type,
original: String::from(input),
};
return Ok(s);
}
@ -141,6 +144,8 @@ fn autocomplete_file(search: &Search) -> std::io::Result<(String, String)> {
let mut last_found = String::new();
let mut results = Vec::new();
//This is pretty messy.
for file in fs::read_dir(search.search_path.clone())? {
let filepath = file.unwrap().path();
let filename = filepath
@ -192,18 +197,44 @@ fn autocomplete_file(search: &Search) -> std::io::Result<(String, String)> {
*&mut last_found = search.searchee.clone();
}
//Handle the path when tabbing in a long path, zsh-like
//then return the value
let xxx = &search.search_path.clone().into_os_string().into_string().unwrap();
let mut return_val = String::new();
if !&search.local_search && !&last_found.contains(&xxx.as_str()) {
*&mut return_val = format!("{}{}{}", &search.command, &search.search_path.display(), last_found);
} else {
*&mut return_val = format!("{}{}", &search.command, last_found);
//Not looking for anything in particular, this is a special case.
if search.searchee == "" {
return Ok((String::from(&search.original), all_res));
}
//Remote search... is annoying
if !search.local_search {
last_found = last_found.replace("./", "");
return Ok((format!("{}{}{}", search.command, search.search_path.display(), last_found), String::new()));
}
last_found = last_found.replace("./", "");
//Otherwise... Handling the return as gracefully as I can
let mut return_val = String::new();
if all_res.len() > 0 {
let ret_string = replace_last_word(&String::from(&search.original), last_found);
*&mut return_val = format!("{}", ret_string);
} else {
*&mut return_val = format!("{}", &search.original);
}
return Ok((return_val, all_res));
}
//Matches on space or slash
fn replace_last_word(sentence: &String, replacement: String) -> String {
let lastword = sentence.split(|c| c == ' ' || c == '/').last().unwrap_or("");
let mut work_sent = sentence.clone();
work_sent.truncate(sentence.len() - lastword.len());
work_sent.push_str(&replacement);
return work_sent;
}
//fn return_last_word(sentence: &String) -> String {
// let lastword = sentence.split(|c| c == ' ' || c == '/').last().unwrap_or("");
// return String::from(lastword);
//}
fn autocomplete_cmd(input: &String, search: &Search) -> (String, String) {
let found_bins = find_bin(input);

236
src/shell/commandrun.rs Normal file
View File

@ -0,0 +1,236 @@
use std::io::Stdout;
use std::process::Command;
use std::io::stdin;
use std::io::{stdout};
use std::io::Write;
use std::path::Path;
use std::env;
use std::str;
use std::fs::File;
use std::process::Stdio;
use termion::event::Key;
use termion::input::TermRead;
use termion::raw::IntoRawMode;
use termion::raw::RawTerminal;
use termion::{color, cursor};
use termion;
use unicode_segmentation::UnicodeSegmentation;
use std::collections::HashMap;
mod history;
use crate::shell::history::*;
///Used to unify command output and error handling
///across functions
pub struct CmdOutput {
pub outp: String,
pub rc: i16,
}
impl CmdOutput {
pub fn from_values(output: String, rc: i16) -> CmdOutput {
let myoutp = CmdOutput {
outp: output,
rc: rc,
};
return myoutp;
}
pub fn new_empty() -> CmdOutput {
let outp = CmdOutput {
outp: String::new(),
rc: 0,
};
return outp;
}
}
fn change_dir(args: &Vec<String>, previous_command: &mut Option<Stdio>) -> Result<CmdOutput, CmdOutput> {
let homedir = dirs::home_dir().unwrap().into_os_string().into_string().unwrap();
//let new_dir = args.peekable().peek().map_or(homedir.as_str(), |x| *x);
let mut new_dir = String::new();
if args.len() > 0 {
*&mut new_dir = args.join(" ");
} else {
*&mut new_dir = String::from(homedir.as_str());
}
let root = Path::new(&new_dir);
if let Err(e) = env::set_current_dir(&root) {
return Err(CmdOutput::from_values(
format!("Error setting directory to {}, got {:?}",
new_dir, e), -1));
};
*previous_command = None;
return Ok(CmdOutput::new_empty());
}
fn print_hist(previous_command: &mut Option<Stdio>, command_next: bool) -> Result<CmdOutput, CmdOutput> {
//let stdout = Stdio::inherit();
let res = get_history();
match res {
Ok(r) => {
let filepath = dirs::home_dir().unwrap().join(".history.sqish");
let file = File::open(filepath).unwrap();
*previous_command = Some(Stdio::from(file));
//if !commands.peek().is_some() {
if !command_next {
print!("{}", r);
}
},
Err(e) => {
return Err(CmdOutput::from_values(format!("Could not print history, got {:?}", e), 255));
},
}
return Ok(CmdOutput::new_empty());
}
fn process_line(input: &str) -> Result<CmdOutput, CmdOutput> {
let mut commands = input.trim().split("|").peekable();
let mut previous_command = None;
let mut resultat = String::new();
let mut rc: i16 = 0;
while let Some(command) = commands.next() {
let parts = match shell_words::split(&command.trim()) {
Ok(w) => w,
Err(e) => {
return Err(CmdOutput::from_values(format!("Could not parse command {:?}", e), -1));
},
};
let command = parts[0].as_str();
let args = Vec::from(&parts[1..]);
match command {
"cd" => {
change_dir(&args, &mut previous_command)?;
},
"history" => {
let next = commands.peek().is_some();
print_hist(&mut previous_command, next)?;
},
command => {
if commands.peek().is_some() {
let stdin = match previous_command {
None => Stdio::inherit(),
Some(o) => o,
};
let stdout = Stdio::piped();
let output = Command::new(command)
.args(args)
.stdout(stdout)
.stdin(stdin)
.spawn();
match output {
Ok(o) => previous_command = Some(Stdio::from(o.stdout.unwrap())),
Err(e) => {
previous_command = None;
eprintln!(" Err: {}", e);
},
};
} else {
let stdin = match previous_command {
None => Stdio::inherit(),
Some(o) => o,
};
print!("\r\n");
let child = match Command::new(command)
.args(args)
.stdin(stdin)
.spawn() {
Ok(h) => h,
Err(_) => {
let err_string = format!("Not found : {}", command);
return Err(CmdOutput::from_values(err_string, -1));
},
};
let output = child
.wait_with_output()
.expect("Failed to wait on child");
let status = output.status
.code()
.unwrap_or(255)
.to_string();
previous_command = None;
let format_res = format!("{}",
status);
*&mut rc = format_res.parse::<i16>().unwrap();
*&mut resultat = String::from_utf8(output.stdout).unwrap();
//let _ = &mut resultat.push_str(&format_res);
}
},
};
}
//return resultat;
return Ok(CmdOutput::from_values(resultat, rc));
}
pub fn run_cmd(mycommand: &mut String,
current_number: &mut i32,
conf: &mut SqishConf,
stdout: &mut RawTerminal<Stdout>) {
//NORMAL CMD
if (mycommand != &String::from("")) && (mycommand != &String::from("exit")) {
//Run the command
let comm = replace_signs(&mycommand);
RawTerminal::suspend_raw_mode(&stdout);
let res = handle_input(&comm);
//Display the results
match res {
Ok(_) => (),
Err(e) => {
println!("\r\n{}Got error {}, RC : {:?}{}",
color::Fg(color::Red),
e.outp,
e.rc,
color::Fg(color::Reset));
},
};
//Prepare for a new command
RawTerminal::activate_raw_mode(&stdout);
mycommand.clear();
conf.update_prompt(get_curr_history_number());
write!(stdout, "{}", conf.promptline).unwrap();
stdout.flush();
*current_number += 1;
//EXITTING
} else if mycommand == &String::from("exit") {
write!(stdout, "\r\nThanks for using Sqish!\r\nSayonara \r\n");
RawTerminal::suspend_raw_mode(&stdout);
std::process::exit(0);
//EMPTY LINE
} else {
conf.update_prompt(get_curr_history_number());
write!(stdout, "\r\n{}", conf.promptline).unwrap();
}
stdout.flush();
}
pub fn handle_input(line: &str) -> Result<CmdOutput, CmdOutput> {
//history callback
if (line.len() > 0) && (line.starts_with('!')) {
let command_found = treat_history_callback(line);
match command_found {
Some(c) => {
write_to_history(&c);
return process_line(&c);
},
None => return Err(CmdOutput::from_values(
String::from("No such value"),
255)),
};
//Regular command
} else if line.len() > 0 {
write_to_history(line);
return process_line(line);
//Nothing
} else {
//Command was empty, new line
return Ok(CmdOutput::new_empty());
}
}

View File

@ -16,6 +16,7 @@ pub struct SqishConf {
pub aliases: HashMap<String, String>,
pub hotkeys: HashMap<String, String>,
pub init: String,
pub env: HashMap<String, String>,
}
impl SqishConf {
@ -54,12 +55,16 @@ impl SqishConf {
let hotkeys_yaml = &sqishrc["hotkeys"];
let hotkeys = Self::yaml_dict2hashmap(hotkeys_yaml);
let env_yaml = &sqishrc["env"];
let env = Self::yaml_dict2hashmap(env_yaml);
let mut out_conf = SqishConf {
promptline: out_str.clone(),
promptline_base: out_str,
aliases: aliases,
hotkeys: hotkeys,
init: startup,
env: env,
};
out_conf.handle_rgb();