mirror of
https://github.com/ChrisTitusTech/linutil.git
synced 2024-11-24 22:14:28 +00:00
fix: Respect shebangs in scripts (#606)
* Cargo will rebuild if anything changes in src/, recursively. E.g src/commands/ is also checked * No need to make a generic, we only use 1 backend * Delete the imports that are no longer needed * Replace the weird struct hack with an enum * Delete a useless line * The None should be explicit * Support for non-english keyboard input * Commit Linutil * refactor: Improve conciseness of char passthrough * fix: Respect shebang in script files * refactor: More efficiently handle shebangs * refactor: Remove unnecessary error handling If 2 characters can be read from the file, a line must exist * fix: Drop accidentally added file * fix: Ensure that executable exists before displaying entry * fix: Explicitly check if the executable is a file * refactor: Replace unnecessary import Co-authored-by: Adam Perkowski <adas1per@protonmail.com> * fix: Check whether the file is directly executable * fix: Comply with rustfmt Co-authored-by: Adam Perkowski <adas1per@protonmail.com> --------- Co-authored-by: Andrii Dokhniak <adokhniak@gmail.com> Co-authored-by: JustLinuxUser <JustLinuxUser@users.noreply.github.com> Co-authored-by: Adam Perkowski <adas1per@protonmail.com>
This commit is contained in:
parent
c0a9820c32
commit
aca42f2411
|
@ -2,7 +2,12 @@ use crate::{Command, ListNode, Tab};
|
||||||
use ego_tree::{NodeMut, Tree};
|
use ego_tree::{NodeMut, Tree};
|
||||||
use include_dir::{include_dir, Dir};
|
use include_dir::{include_dir, Dir};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use std::path::{Path, PathBuf};
|
use std::{
|
||||||
|
fs::File,
|
||||||
|
io::{BufRead, BufReader, Read},
|
||||||
|
os::unix::fs::PermissionsExt,
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
};
|
||||||
use tempdir::TempDir;
|
use tempdir::TempDir;
|
||||||
|
|
||||||
const TAB_DATA: Dir = include_dir!("$CARGO_MANIFEST_DIR/tabs");
|
const TAB_DATA: Dir = include_dir!("$CARGO_MANIFEST_DIR/tabs");
|
||||||
|
@ -37,7 +42,7 @@ pub fn get_tabs(validate: bool) -> Vec<Tab> {
|
||||||
task_list: String::new(),
|
task_list: String::new(),
|
||||||
});
|
});
|
||||||
let mut root = tree.root_mut();
|
let mut root = tree.root_mut();
|
||||||
create_directory(data, &mut root, &directory);
|
create_directory(data, &mut root, &directory, validate);
|
||||||
Tab {
|
Tab {
|
||||||
name,
|
name,
|
||||||
tree,
|
tree,
|
||||||
|
@ -78,16 +83,22 @@ struct Entry {
|
||||||
description: String,
|
description: String,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
preconditions: Option<Vec<Precondition>>,
|
preconditions: Option<Vec<Precondition>>,
|
||||||
#[serde(default)]
|
#[serde(flatten)]
|
||||||
entries: Option<Vec<Entry>>,
|
entry_type: EntryType,
|
||||||
#[serde(default)]
|
|
||||||
command: Option<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
script: Option<PathBuf>,
|
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
task_list: String,
|
task_list: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
enum EntryType {
|
||||||
|
#[serde(rename = "entries")]
|
||||||
|
Entries(Vec<Entry>),
|
||||||
|
#[serde(rename = "command")]
|
||||||
|
Command(String),
|
||||||
|
#[serde(rename = "script")]
|
||||||
|
Script(PathBuf),
|
||||||
|
}
|
||||||
|
|
||||||
impl Entry {
|
impl Entry {
|
||||||
fn is_supported(&self) -> bool {
|
fn is_supported(&self) -> bool {
|
||||||
self.preconditions.as_deref().map_or(true, |preconditions| {
|
self.preconditions.as_deref().map_or(true, |preconditions| {
|
||||||
|
@ -142,7 +153,7 @@ fn filter_entries(entries: &mut Vec<Entry>) {
|
||||||
if !entry.is_supported() {
|
if !entry.is_supported() {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if let Some(entries) = &mut entry.entries {
|
if let EntryType::Entries(entries) = &mut entry.entry_type {
|
||||||
filter_entries(entries);
|
filter_entries(entries);
|
||||||
!entries.is_empty()
|
!entries.is_empty()
|
||||||
} else {
|
} else {
|
||||||
|
@ -151,53 +162,89 @@ fn filter_entries(entries: &mut Vec<Entry>) {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create_directory(data: Vec<Entry>, node: &mut NodeMut<ListNode>, command_dir: &Path) {
|
fn create_directory(
|
||||||
|
data: Vec<Entry>,
|
||||||
|
node: &mut NodeMut<ListNode>,
|
||||||
|
command_dir: &Path,
|
||||||
|
validate: bool,
|
||||||
|
) {
|
||||||
for entry in data {
|
for entry in data {
|
||||||
if [
|
match entry.entry_type {
|
||||||
entry.entries.is_some(),
|
EntryType::Entries(entries) => {
|
||||||
entry.command.is_some(),
|
let mut node = node.append(ListNode {
|
||||||
entry.script.is_some(),
|
name: entry.name,
|
||||||
]
|
description: entry.description,
|
||||||
.iter()
|
command: Command::None,
|
||||||
.filter(|&&x| x)
|
task_list: String::new(),
|
||||||
.count()
|
});
|
||||||
> 1
|
create_directory(entries, &mut node, command_dir, validate);
|
||||||
{
|
}
|
||||||
panic!("Entry must have only one data type");
|
EntryType::Command(command) => {
|
||||||
}
|
node.append(ListNode {
|
||||||
|
name: entry.name,
|
||||||
if let Some(entries) = entry.entries {
|
description: entry.description,
|
||||||
let mut node = node.append(ListNode {
|
command: Command::Raw(command),
|
||||||
name: entry.name,
|
task_list: String::new(),
|
||||||
description: entry.description,
|
});
|
||||||
command: Command::None,
|
}
|
||||||
task_list: String::new(),
|
EntryType::Script(script) => {
|
||||||
});
|
let script = command_dir.join(script);
|
||||||
create_directory(entries, &mut node, command_dir);
|
if !script.exists() {
|
||||||
} else if let Some(command) = entry.command {
|
panic!("Script {} does not exist", script.display());
|
||||||
node.append(ListNode {
|
}
|
||||||
name: entry.name,
|
|
||||||
description: entry.description,
|
if let Some((executable, args)) = get_shebang(&script, validate) {
|
||||||
command: Command::Raw(command),
|
node.append(ListNode {
|
||||||
task_list: String::new(),
|
name: entry.name,
|
||||||
});
|
description: entry.description,
|
||||||
} else if let Some(script) = entry.script {
|
command: Command::LocalFile {
|
||||||
let dir = command_dir.join(script);
|
executable,
|
||||||
if !dir.exists() {
|
args,
|
||||||
panic!("Script {} does not exist", dir.display());
|
file: script,
|
||||||
|
},
|
||||||
|
task_list: entry.task_list,
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
node.append(ListNode {
|
|
||||||
name: entry.name,
|
|
||||||
description: entry.description,
|
|
||||||
command: Command::LocalFile(dir),
|
|
||||||
task_list: entry.task_list,
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
panic!("Entry must have data");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn get_shebang(script_path: &Path, validate: bool) -> Option<(String, Vec<String>)> {
|
||||||
|
let default_executable = || Some(("/bin/sh".into(), vec!["-e".into()]));
|
||||||
|
|
||||||
|
let script = File::open(script_path).expect("Failed to open script file");
|
||||||
|
let mut reader = BufReader::new(script);
|
||||||
|
|
||||||
|
// Take the first 2 characters from the reader; check whether it's a shebang
|
||||||
|
let mut two_chars = [0; 2];
|
||||||
|
if reader.read_exact(&mut two_chars).is_err() || two_chars != *b"#!" {
|
||||||
|
return default_executable();
|
||||||
|
}
|
||||||
|
|
||||||
|
let first_line = reader.lines().next().unwrap().unwrap();
|
||||||
|
|
||||||
|
let mut parts = first_line.split_whitespace();
|
||||||
|
|
||||||
|
let Some(executable) = parts.next() else {
|
||||||
|
return default_executable();
|
||||||
|
};
|
||||||
|
|
||||||
|
let is_valid = !validate || is_executable(Path::new(executable));
|
||||||
|
|
||||||
|
is_valid.then(|| {
|
||||||
|
let mut args: Vec<String> = parts.map(ToString::to_string).collect();
|
||||||
|
args.push(script_path.to_string_lossy().to_string());
|
||||||
|
(executable.to_string(), args)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_executable(path: &Path) -> bool {
|
||||||
|
path.metadata()
|
||||||
|
.map(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0)
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
impl TabList {
|
impl TabList {
|
||||||
fn get_tabs() -> Vec<PathBuf> {
|
fn get_tabs() -> Vec<PathBuf> {
|
||||||
let temp_dir = TempDir::new("linutil_scripts").unwrap().into_path();
|
let temp_dir = TempDir::new("linutil_scripts").unwrap().into_path();
|
||||||
|
|
|
@ -8,7 +8,12 @@ pub use inner::get_tabs;
|
||||||
#[derive(Clone, Hash, Eq, PartialEq)]
|
#[derive(Clone, Hash, Eq, PartialEq)]
|
||||||
pub enum Command {
|
pub enum Command {
|
||||||
Raw(String),
|
Raw(String),
|
||||||
LocalFile(PathBuf),
|
LocalFile {
|
||||||
|
executable: String,
|
||||||
|
args: Vec<String>,
|
||||||
|
// The file path is included within the arguments; don't pass this in addition
|
||||||
|
file: PathBuf,
|
||||||
|
},
|
||||||
None, // Directory
|
None, // Directory
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -155,11 +155,10 @@ impl FloatingText {
|
||||||
// just apply highlights directly
|
// just apply highlights directly
|
||||||
(max_width!(get_lines(cmd)), Some(cmd.clone()))
|
(max_width!(get_lines(cmd)), Some(cmd.clone()))
|
||||||
}
|
}
|
||||||
|
Command::LocalFile { file, .. } => {
|
||||||
Command::LocalFile(file_path) => {
|
|
||||||
// have to read from tmp dir to get cmd src
|
// have to read from tmp dir to get cmd src
|
||||||
let raw = std::fs::read_to_string(file_path)
|
let raw = std::fs::read_to_string(file)
|
||||||
.map_err(|_| format!("File not found: {:?}", file_path))
|
.map_err(|_| format!("File not found: {:?}", file))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
(max_width!(get_lines(&raw)), Some(raw))
|
(max_width!(get_lines(&raw)), Some(raw))
|
||||||
|
|
|
@ -19,10 +19,7 @@ use crossterm::{
|
||||||
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
|
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
|
||||||
ExecutableCommand,
|
ExecutableCommand,
|
||||||
};
|
};
|
||||||
use ratatui::{
|
use ratatui::{backend::CrosstermBackend, Terminal};
|
||||||
backend::{Backend, CrosstermBackend},
|
|
||||||
Terminal,
|
|
||||||
};
|
|
||||||
use state::AppState;
|
use state::AppState;
|
||||||
|
|
||||||
// Linux utility toolbox
|
// Linux utility toolbox
|
||||||
|
@ -59,7 +56,10 @@ fn main() -> io::Result<()> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn run<B: Backend>(terminal: &mut Terminal<B>, state: &mut AppState) -> io::Result<()> {
|
fn run(
|
||||||
|
terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
|
||||||
|
state: &mut AppState,
|
||||||
|
) -> io::Result<()> {
|
||||||
loop {
|
loop {
|
||||||
terminal.draw(|frame| state.draw(frame)).unwrap();
|
terminal.draw(|frame| state.draw(frame)).unwrap();
|
||||||
// Wait for an event
|
// Wait for an event
|
||||||
|
|
|
@ -148,11 +148,19 @@ impl RunningCommand {
|
||||||
for command in commands {
|
for command in commands {
|
||||||
match command {
|
match command {
|
||||||
Command::Raw(prompt) => script.push_str(&format!("{}\n", prompt)),
|
Command::Raw(prompt) => script.push_str(&format!("{}\n", prompt)),
|
||||||
Command::LocalFile(file) => {
|
Command::LocalFile {
|
||||||
if let Some(parent) = file.parent() {
|
executable,
|
||||||
script.push_str(&format!("cd {}\n", parent.display()));
|
args,
|
||||||
|
file,
|
||||||
|
} => {
|
||||||
|
if let Some(parent_directory) = file.parent() {
|
||||||
|
script.push_str(&format!("cd {}\n", parent_directory.display()));
|
||||||
|
}
|
||||||
|
script.push_str(&executable);
|
||||||
|
for arg in args {
|
||||||
|
script.push(' ');
|
||||||
|
script.push_str(&arg);
|
||||||
}
|
}
|
||||||
script.push_str(&format!("sh {}\n", file.display()));
|
|
||||||
}
|
}
|
||||||
Command::None => panic!("Command::None was treated as a command"),
|
Command::None => panic!("Command::None was treated as a command"),
|
||||||
}
|
}
|
||||||
|
@ -262,27 +270,25 @@ impl RunningCommand {
|
||||||
fn handle_passthrough_key_event(&mut self, key: &KeyEvent) {
|
fn handle_passthrough_key_event(&mut self, key: &KeyEvent) {
|
||||||
let input_bytes = match key.code {
|
let input_bytes = match key.code {
|
||||||
KeyCode::Char(ch) => {
|
KeyCode::Char(ch) => {
|
||||||
let mut send = vec![ch as u8];
|
let raw_utf8 = || ch.to_string().into_bytes();
|
||||||
let upper = ch.to_ascii_uppercase();
|
|
||||||
if key.modifiers == KeyModifiers::CONTROL {
|
match ch.to_ascii_uppercase() {
|
||||||
match upper {
|
_ if key.modifiers != KeyModifiers::CONTROL => raw_utf8(),
|
||||||
// https://github.com/fyne-io/terminal/blob/master/input.go
|
// https://github.com/fyne-io/terminal/blob/master/input.go
|
||||||
// https://gist.github.com/ConnerWill/d4b6c776b509add763e17f9f113fd25b
|
// https://gist.github.com/ConnerWill/d4b6c776b509add763e17f9f113fd25b
|
||||||
'2' | '@' | ' ' => send = vec![0],
|
'2' | '@' | ' ' => vec![0],
|
||||||
'3' | '[' => send = vec![27],
|
'3' | '[' => vec![27],
|
||||||
'4' | '\\' => send = vec![28],
|
'4' | '\\' => vec![28],
|
||||||
'5' | ']' => send = vec![29],
|
'5' | ']' => vec![29],
|
||||||
'6' | '^' => send = vec![30],
|
'6' | '^' => vec![30],
|
||||||
'7' | '-' | '_' => send = vec![31],
|
'7' | '-' | '_' => vec![31],
|
||||||
char if ('A'..='_').contains(&char) => {
|
c if ('A'..='_').contains(&c) => {
|
||||||
let ascii_val = char as u8;
|
let ascii_val = c as u8;
|
||||||
let ascii_to_send = ascii_val - 64;
|
let ascii_to_send = ascii_val - 64;
|
||||||
send = vec![ascii_to_send];
|
vec![ascii_to_send]
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
}
|
||||||
|
_ => raw_utf8(),
|
||||||
}
|
}
|
||||||
send
|
|
||||||
}
|
}
|
||||||
KeyCode::Enter => vec![b'\n'],
|
KeyCode::Enter => vec![b'\n'],
|
||||||
KeyCode::Backspace => vec![0x7f],
|
KeyCode::Backspace => vec![0x7f],
|
||||||
|
|
|
@ -357,7 +357,7 @@ impl AppState {
|
||||||
Focus::Search => match self.filter.handle_key(key) {
|
Focus::Search => match self.filter.handle_key(key) {
|
||||||
SearchAction::Exit => self.exit_search(),
|
SearchAction::Exit => self.exit_search(),
|
||||||
SearchAction::Update => self.update_items(),
|
SearchAction::Update => self.update_items(),
|
||||||
_ => {}
|
SearchAction::None => {}
|
||||||
},
|
},
|
||||||
Focus::TabList => match key.code {
|
Focus::TabList => match key.code {
|
||||||
KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right => self.focus = Focus::List,
|
KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right => self.focus = Focus::List,
|
||||||
|
|
Loading…
Reference in New Issue
Block a user