dust/src/abstract_tree/command.rs

64 lines
1.8 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-25 13:43:21 +00:00
use crate::{AbstractTree, Error, Format, Map, Result, Type, Value};
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-25 13:43:21 +00:00
fn from_syntax(node: tree_sitter::Node, source: &str, _context: &crate::Map) -> Result<Self> {
2024-01-25 13:27:24 +00:00
Error::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-25 13:43:21 +00:00
fn run(&self, _source: &str, _context: &Map) -> Result<Value> {
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
}
2024-01-25 13:43:21 +00:00
fn expected_type(&self, _context: &Map) -> Result<Type> {
Ok(Type::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!()
}
}