1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
use std::{
    env::{consts, var},
    fs::{self, canonicalize, File},
    io::{BufRead, BufReader},
    path::Path,
    str::FromStr,
};

use fpr_cli::*;
use itertools::Itertools;
use regex::Regex;

struct Pats {
    start: Regex,
    ty: Regex,
    arg: Regex,
    sh_var: Regex,
    end: Regex,
}

struct Config {
    shared: bool,
}

enum Type {
    Text,
    Interactive,
}

fn gen(fp: &Path, p: &Pats, cfg: &Config) -> String {
    let f = BufReader::new(File::open(&fp).expect("Failed to open file"));

    let name = fp.file_stem().expect("Failed to get filename.");
    let name = name
        .to_str()
        .expect(&format!("Filename is not valid: {:?}", name));

    let filename = fp.file_name().expect("Failed to get filename.");
    let filename = filename
        .to_str()
        .expect(&format!("Filename is not valid: {:?}", filename));

    let absl = canonicalize(&fp).expect(&format!("Failed to get absolute path: {:?}", &fp));
    let plat_absl = || {
        let m = format!("Failed to get parent path: {:?}", absl);
        let y = absl
            .parent()
            .expect(&m)
            .parent()
            .expect(&m)
            .to_str()
            .expect(&m);
        let plat = match consts::OS {
            "linux" => "win",
            "macos" => "mac",
            e => panic!("Unknown platform: {e}"),
        };
        format!("{y}/{plat}/{filename}")
    };
    let absl = absl
        .to_str()
        .expect(&format!("Failed to get absolute path: {:?}", &fp));

    let lines = (|| {
        let mut inner_lines = Vec::<String>::new();
        let mut b = false;

        for l in f.lines() {
            let l = l.unwrap();
            if p.start.find(&l).is_some() {
                b = true;
                continue;
            }
            if b && p.end.find(&l).is_some() {
                break;
            }

            if b {
                inner_lines.push(l);
            }
        }

        if !b {
            panic!(
                "Not all tags present for '{:?}': {:?}, {:?}",
                name, p.start, p.start
            )
        }

        inner_lines
    })();

    if lines.is_empty() {
        panic!("Expected type at first line.")
    };

    let ty =
        p.ty.captures(&lines[0])
            .expect(&format!("Expected one type tag for '{}': {:?}", name, p.ty));
    let ty = match &ty[1] {
        "text" => Type::Text,
        "interactive" => Type::Interactive,
        e => panic!("Unexpected type for '{name}': {e}"),
    };

    struct Arg {
        name: String,
        num: usize,
        varidic: bool,
        desc: String,
    }

    let args =
        lines
            .iter()
            .skip(1)
            .map(|l| -> Result<_, _> { p.arg.captures(&l).ok_or(format!("Malformed line '{l}'")) })
            .map(|m| -> Result<_, String> {
                let m = m?;
                let v = m[2].to_owned();
                let v_caps = p
                    .sh_var
                    .captures(&v)
                    .ok_or(format!("Malformed variable '{v}'"))?;
                let (num, varidic) = if v_caps.get(3).is_some()
                    && v_caps[1].to_string() == r#"("${@:"# {
                    (v_caps[2].to_owned(), true)
                } else if v_caps.get(3).is_none() && v_caps[1].to_string() == r#"$"# {
                    (v_caps[2].to_owned(), false)
                } else {
                    return Err(format!("Malformed variable '{v}' '{:?}'", v_caps));
                };
                let num = usize::from_str(&num).expect(&format!("Not a digit '{num}'"));
                Ok(Arg {
                    name: m[1].to_owned(),
                    num,
                    varidic,
                    desc: m[3].to_owned(),
                })
            })
            .collect::<Result<Vec<_>, _>>()
            .expect(&format!("Failed to parse file {absl}"));

    args.iter().enumerate().for_each(|(i, a)| {
        if i + 1 != a.num {
            panic!("Argument not ordered at {i} for '{:?}'", &fp);
        }
        if a.varidic && a.num != args.len() {
            panic!(
                "Only the last argument can be varidic in '{:?}' '{}'",
                &fp, a.name
            );
        }
    });

    let is_varidic = 0 < args.iter().filter(|a| a.varidic).count();

    let doc = args
        .iter()
        .filter(|a| !a.desc.is_empty())
        .map(|a| format!("/// {}{}", a.name, a.desc))
        .join("\n");
    let generics = if is_varidic { "<I, S>" } else { "" };
    let generics_where = if is_varidic {
        "where I: IntoIterator<Item = S>, S: std::convert::AsRef<std::ffi::OsStr>"
    } else {
        ""
    };
    let fn_args = args
        .iter()
        .map(|a| {
            if !a.varidic {
                format!("{}: &str", a.name)
            } else {
                format!("{}: I", a.name)
            }
        })
        .join(", ");
    let fn_args2 = args.iter().map(|a| format!("{}", a.name)).join(", ");
    let ret_ty = match ty {
        Type::Text => "String",
        Type::Interactive => "()",
    };
    let ret_raw_ty = match ty {
        Type::Text => "Vec<u8>",
        Type::Interactive => "()",
    };
    let res = match ty {
        Type::Text => "let r = ",
        Type::Interactive => "let _ = ",
    };
    let cmd = if cfg.shared {
        absl.to_owned()
    } else {
        plat_absl()
    };
    let cmd_args = if args.is_empty() {
        format!("")
    } else {
        args.iter()
            .map(|a| {
                if !a.varidic {
                    format!(".arg({})", a.name)
                } else {
                    format!(".args({})", a.name)
                }
            })
            .join("")
    };
    let exec = match ty {
        Type::Text => "output",
        Type::Interactive => "status",
    };
    let ret = match ty {
        Type::Text => format!(
            r#"Ok(String::from_utf8(r).map_err(|e| format!("Output of '{cmd}' not valid UTF-8. '{{e}}'"))?)"#
        ),
        Type::Interactive => format!("Ok(())"),
    };
    let ret_raw = match ty {
        Type::Text => format!(r#"Ok(r.stdout)"#),
        Type::Interactive => format!("Ok(())"),
    };

    let name_raw = format!("{name}_raw");

    format!(
        r#"{doc}
#[allow(dead_code)]
pub fn {name_raw}{generics}({fn_args}) -> Result<{ret_raw_ty}, String> {generics_where} {{
    {res}std::process::Command::new("{cmd}"){cmd_args}.{exec}().map_err(|e| format!("Command '{cmd}' error '{{e}}'"))?;
    {ret_raw}
}}
{doc}
#[allow(dead_code)]
pub fn {name}{generics}({fn_args}) -> Result<{ret_ty}, String> {generics_where} {{
    {res}{name_raw}({fn_args2})?;
    {ret}
}}
"#
    )
}

fn gen2(d: &String, p: &Pats, cfg: Config) -> String {
    fs::read_dir(&d)
        .expect(&format!("Failed to read dir '{}'", d))
        .filter_map(Result::ok)
        .filter(|e| e.path().is_file())
        .map(|f| -> Result<String, String> {
            let f = f.path();
            Ok(gen(&f, &p, &cfg))
        })
        .collect::<Result<Vec<_>, _>>()
        .expect("Failed to generate code")
        .join("\n")
}

pub fn run(src: &'static str, main_plat: &'static str, dst_file: &'static str) {
    let src = format!("{}/{}", var("CARGO_MANIFEST_DIR").unwrap(), src);
    let out = format!("{}/{}", var("OUT_DIR").unwrap(), dst_file);

    let p = Pats {
        start: Regex::new("^# start metadata$").unwrap(),
        end: Regex::new("^# end metadata$").unwrap(),
        ty: Regex::new("^# type ([^ ]+)$").unwrap(),
        arg: Regex::new(r#"^([^=]+)=([()"1-9${}:@]+)(.*)$"#).unwrap(),
        sh_var: Regex::new(r#"([(${"@:]+)([0-9]+)(\}"\))?"#).unwrap(),
    };

    let src_main_plat = format!("{}/{}/", src, main_plat);
    let src_all = format!("{}/all/", src);

    let r_shared = gen2(&src_all, &p, Config { shared: true });
    let r_plat = gen2(&src_main_plat, &p, Config { shared: false });

    fs::write(&out, format!("{r_shared}\n{r_plat}\n"))
        .expect(&format!("Failed to write to '{}'", &out));
}

pub trait Sh<C>: Acts<C> {
    fn gen_rc(pfx: &'static str, dst: &'static str) {
        let pfx = [format!("{pfx}")];
        let cmds = Self::list()
            .iter()
            .map(|a| {
                let mut a = a.to_owned();
                a.splice(0..0, pfx.iter().cloned());
                a
            })
            .collect::<Vec<_>>();
        let out = format!("{}/{}", var("OUT_DIR").unwrap(), dst);

        let body = cmds
            .iter()
            .map(|c| {
                let cmd = c.join("_");
                let cmd2 = c.join(" ");
                format!(r#"function {cmd}() {{ {cmd2} "$@"; }} "#)
            })
            .join("\n");

        const HEAD: &'static str = r"#!/bin/bash
# Generated script";

        let content = format!("{HEAD}\n{body}\n");

        fs::write(&out, content).expect(&format!("Failed to write to {}", &out));
    }
}
impl<C, T: Acts<C>> Sh<C> for T {}