1
0
dust/src/abstract_tree/command.rs

75 lines
2.1 KiB
Rust
Raw Normal View History

2024-01-25 13:43:21 +00:00
use std::process;
2024-01-25 13:27:24 +00:00
use serde::{Deserialize, Serialize};
2024-01-25 12:10:45 +00:00
2024-01-31 18:51:48 +00:00
use crate::{
error::{RuntimeError, SyntaxError, ValidationError},
2024-02-01 00:35:27 +00:00
AbstractTree, Format, Map, Type, Value,
2024-01-31 18:51:48 +00:00
};
2024-01-25 13:27:24 +00:00
2024-01-30 23:19:05 +00:00
/// An external program invokation.
2024-01-25 13:27:24 +00:00
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
2024-01-25 12:10:45 +00:00
pub struct Command {
2024-01-26 20:23:24 +00:00
command_text: String,
command_arguments: Vec<String>,
2024-01-25 12:10:45 +00:00
}
impl AbstractTree for Command {
2024-01-31 18:51:48 +00:00
fn from_syntax(
node: tree_sitter::Node,
source: &str,
_context: &crate::Map,
) -> Result<Self, SyntaxError> {
2024-02-01 00:35:27 +00:00
SyntaxError::expect_syntax_node(source, "command", node)?;
2024-01-25 13:43:21 +00:00
2024-01-26 20:23:24 +00:00
let command_text_node = node.child(1).unwrap();
let command_text = source[command_text_node.byte_range()].to_string();
2024-01-25 13:43:21 +00:00
2024-01-26 20:23:24 +00:00
let mut command_arguments = Vec::new();
for index in 2..node.child_count() {
2024-01-25 13:43:21 +00:00
let text_node = node.child(index).unwrap();
2024-01-25 13:57:55 +00:00
let mut text = source[text_node.byte_range()].to_string();
if (text.starts_with('\'') && text.ends_with('\''))
|| (text.starts_with('"') && text.ends_with('"'))
|| (text.starts_with('`') && text.ends_with('`'))
{
text = text[1..text.len() - 1].to_string();
}
2024-01-25 13:43:21 +00:00
2024-01-26 20:23:24 +00:00
command_arguments.push(text);
2024-01-25 13:43:21 +00:00
}
2024-01-26 20:23:24 +00:00
Ok(Command {
command_text,
command_arguments,
})
2024-01-25 12:10:45 +00:00
}
2024-01-31 18:51:48 +00:00
fn expected_type(&self, _context: &Map) -> Result<Type, ValidationError> {
Ok(Type::String)
}
2024-02-01 01:52:34 +00:00
fn validate(&self, _source: &str, _context: &Map) -> Result<(), ValidationError> {
2024-01-31 18:51:48 +00:00
todo!()
}
fn run(&self, _source: &str, _context: &Map) -> Result<Value, RuntimeError> {
2024-01-26 20:23:24 +00:00
let output = process::Command::new(&self.command_text)
.args(&self.command_arguments)
2024-01-25 13:43:21 +00:00
.spawn()?
.wait_with_output()?
.stdout;
let string = String::from_utf8(output)?;
Ok(Value::String(string))
2024-01-25 12:10:45 +00:00
}
}
impl Format for Command {
2024-01-25 13:43:21 +00:00
fn format(&self, _output: &mut String, _indent_level: u8) {
2024-01-25 12:10:45 +00:00
todo!()
}
}