1use std::path::{Path, PathBuf};
2
3use anyhow::Result;
4use syntect::{
5 easy::HighlightLines,
6 highlighting::{Style, ThemeSet},
7 parsing::SyntaxSet,
8 util::{as_24_bit_terminal_escaped, LinesWithEndings},
9};
10use xreq_lib::{KeyVal, KeyValType};
11
12pub fn parse_key_val(s: &str) -> Result<KeyVal> {
17 let (kv_type, input) = match s.chars().next() {
18 Some(c) => match c {
19 '%' => (KeyValType::Header, &s[1..]),
20 '@' => (KeyValType::Body, &s[1..]),
21 'A'..='Z' | 'a'..='z' => (KeyValType::Query, s),
22 _ => return Err(anyhow::anyhow!("invalid key val pair: {}", s)),
23 },
24 None => return Err(anyhow::anyhow!("empty key-value pair is invalid")),
25 };
26
27 let mut parts = input.splitn(2, '=');
28 let key = parts.next().ok_or_else(|| anyhow::anyhow!("missing key"))?;
29 let val = parts
30 .next()
31 .ok_or_else(|| anyhow::anyhow!("missing value"))?;
32 Ok(KeyVal::new(kv_type, key, val))
33}
34
35pub fn get_config_file(s: &str) -> Result<PathBuf> {
36 let path = Path::new(s);
37 if path.exists() {
38 Ok(path.to_path_buf())
39 } else {
40 Err(anyhow::anyhow!("config file not found"))
41 }
42}
43
44pub fn get_default_config(name: &str) -> Result<PathBuf> {
45 let paths = [
46 format!("{}/.config/{}", std::env::var("HOME").unwrap(), name),
47 format!("./{}", name),
48 format!("/etc/{}", name),
49 ];
50
51 for path in paths.iter() {
52 if Path::new(path).exists() {
53 return Ok(Path::new(path).to_path_buf());
54 }
55 }
56
57 Err(anyhow::anyhow!("Config file not found. You can either specify it with the --config option or put it in one of the following locations: {}", paths.join(", ")))
58}
59
60pub fn print_syntect(output: &mut Vec<String>, s: String, ext: &str) -> Result<()> {
61 if atty::isnt(atty::Stream::Stdout) {
62 output.push(s);
63 return Ok(());
64 }
65
66 let ps = SyntaxSet::load_defaults_newlines();
68 let ts = ThemeSet::load_defaults();
69 let syntax = ps.find_syntax_by_extension(ext).unwrap();
70 let mut h = HighlightLines::new(syntax, &ts.themes["base16-ocean.dark"]);
71 for line in LinesWithEndings::from(&s) {
72 let ranges: Vec<(Style, &str)> = h.highlight_line(line, &ps)?;
73 let escaped = as_24_bit_terminal_escaped(&ranges[..], false);
74 output.push(escaped);
75 }
76
77 Ok(())
78}