make a parser for sv

This commit is contained in:
primardj 2024-04-05 20:12:55 +01:00
parent 3c18c49ea0
commit 41b25cd984
3 changed files with 134 additions and 1 deletions

View file

@ -1,7 +1,17 @@
//mod misc;
mod parser;
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
dbg!(args);
// args
let arg_parser: Vec<String> = parser::parse_args(args);
dbg!(arg_parser);
//dbg!(args);
}

View file

@ -0,0 +1,118 @@
mod misc;
use std::process::exit;
pub fn parse_args(args: Vec<String>) -> Vec<String>{
let mut i: i8 = 0;
let mut parser: Vec<String> = Vec::new();
let mut tmpstr: String;
for arg in args.iter() {
if i == 0 {
i += 1;
}
else if i == 1 {
tmpstr = parse_args_1(arg);
if tmpstr == "--" {
i += 1;
}
if tmpstr == "-w" {
// i = 4 signifie, take next word, and return to i = 1.
i = 4;
}
if tmpstr != "--" && tmpstr != "" {
parser.push(tmpstr);
}
else if tmpstr == "" {
// We are actually in phase II. Do exactly the same if it was phase II.
parser.push(phase2(arg));
i = 3;
}
}
else if i == 2 {
parser.push(phase2(arg));
i += 1;
}
else if i == 3 {
// phase 3, everything is a service name.
parser.push(arg.to_string());
}
else if i == 4 {
// 4. push arg and return to stage 1.
parser.push(arg.to_string());
i = 1;
}
}
return parser;
}
fn phase2(arg: &String) -> String {
let tmpstr: String;
tmpstr = parse_args_2(arg);
if tmpstr == "INVALID" {
misc::usage();
exit(100);
}
return tmpstr
}
pub fn parse_args_1(arg: &String) -> String{
// Get a string
// Return a vect ('first_char', 'length', 'entry_necessary')
let ch1 = arg.chars().next().unwrap();
//println!("{}", ch1);
if ch1 == '-' && arg.len() >= 2{
return (&arg[..2]).to_string()
} else if ch1 == '-' {
return ch1.to_string()
}
println!("{}",arg);
return "".to_string()
}
pub fn parse_args_2(arg: &String) -> String{
let possible: Vec<&str> = vec!["start", "stop", "reload", "restart", "shutdown", "force-stop", "force-reload", "force-restart", "force-shutdown", "try-restart"];
let cpossible: Vec<char> = vec!['s', 'u', 'd', 'o', 'p', 'c', 'h', 'a', 'i', 'q', '1', '2', 't', 'k'];
for var in possible.iter() {
if arg == var {
return var.to_string()
}
}
let ch1 = arg.chars().next().unwrap();
for var in cpossible.iter() {
if ch1 == *var {
return ch1.to_string()
}
}
return "INVALID".to_string()
}

View file

@ -0,0 +1,5 @@
pub fn usage() {
println!("usage: sv [-v] [-w sec] command service ...\n")
}