r4d 3.0.0-rc.4

Text oriented macro processor
Documentation
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
use crate::auth::AuthType;
#[cfg(feature = "signature")]
use crate::consts::LINE_ENDING;
use crate::logger::WarningType;
#[cfg(feature = "signature")]
use crate::models::SignatureType;
use crate::models::{CommentType, DiffOption};
use crate::processor::Processor;
#[cfg(feature = "template")]
use crate::script;
use crate::utils::Utils;
use crate::{RadError, RadResult};
#[cfg(feature = "signature")]
use std::fmt::Write as _;
use std::io::Read;
#[cfg(feature = "signature")]
use std::io::Write;
use std::path::{Path, PathBuf};
use std::str::FromStr;

/// Struct to parse command line arguments and execute proper operations
pub struct RadCli<'cli> {
    rules: Vec<PathBuf>,
    write_to_file: Option<PathBuf>,
    error_to_file: Option<PathBuf>,
    allow_auth: Vec<AuthType>,
    allow_auth_warn: Vec<AuthType>,
    processor: Processor<'cli>,
}

impl<'cli> Default for RadCli<'cli> {
    fn default() -> Self {
        Self::new()
    }
}

impl<'cli> RadCli<'cli> {
    pub fn print_error(&mut self, error: &str) -> RadResult<()> {
        self.processor.print_error(error)?;
        Ok(())
    }

    pub fn new() -> Self {
        Self {
            rules: vec![],
            write_to_file: None,
            error_to_file: None,
            allow_auth: vec![],
            allow_auth_warn: vec![],
            processor: Processor::new(),
        }
    }

    /// User method to call cli workflow
    ///
    /// This sequentially parse command line arguments and execute necessary operations
    pub fn parse(&mut self) -> RadResult<()> {
        let cli_args = Self::args_builder(None);
        self.run_processor(&cli_args)?;
        Ok(())
    }

    pub(crate) fn parse_from(&mut self, source: &[&str]) -> RadResult<()> {
        let cli_args = Self::args_builder(Some(source));
        self.run_processor(&cli_args)?;
        Ok(())
    }

    /// Parse arguments and run processor
    fn run_processor(&mut self, args: &clap::ArgMatches) -> RadResult<()> {
        self.parse_options(args);

        // Build processor
        let mut processor = Processor::new()
            .set_comment_type(CommentType::from_str(
                if args.occurrences_of("comment") == 0 {
                    "none" // None when no runtime flag
                } else {
                    args.value_of("comment").unwrap() // default is start
                },
            )?)
            .purge(args.is_present("purge"))
            .lenient(args.is_present("lenient"))
            .silent(WarningType::from_str(
                args.value_of("silent").unwrap_or("none"),
            )?)
            .assert(args.is_present("assert"))
            .allow(&self.allow_auth)
            .allow_with_warning(&self.allow_auth_warn)
            .unix_new_line(args.is_present("newline"))
            .melt_files(&self.rules)?
            .discard(args.is_present("discard"));

        // Help command
        #[cfg(feature = "signature")]
        if let Some(name) = args.value_of("manual") {
            if name == "*" {
                // Get all values
                // Sort by name
                // and make it a single stirng, then print
                let sig_map = processor.get_signature_map(SignatureType::All)?;
                let mut manual = sig_map.content.values().collect::<Vec<_>>();
                manual.sort_unstable_by(|a, b| a.name.cmp(&b.name));
                let manual = manual.iter().fold(String::new(), |mut acc, sig| {
                    writeln!(acc, "{0}{1}{1}----", sig, LINE_ENDING).unwrap();
                    acc
                });
                write!(std::io::stdout(), "{}", manual)?
            } else {
                match processor.get_macro_manual(name) {
                    Some(text) => writeln!(std::io::stdout(), "{}", text)?,
                    None => writeln!(
                        std::io::stdout(),
                        "Given macro \"{}\" doesn't exist and cannot display a manual",
                        name
                    )?,
                }
            }
            return Ok(());
        }

        if let Some(file) = self.write_to_file.as_ref() {
            processor = processor.write_to_file(file)?;
        }
        if let Some(file) = self.error_to_file.as_ref() {
            processor = processor.error_to_file(file)?;
        }

        #[cfg(feature = "template")]
        script::extend_processor(&mut processor)?;

        #[cfg(feature = "debug")]
        {
            processor = processor
                .debug(args.is_present("debug"))
                .log(args.is_present("log"))
                .interactive(args.is_present("interactive"))
                .diff(DiffOption::from_str(if args.occurrences_of("diff") == 0 {
                    "none" // None when no runtime flag
                } else {
                    args.value_of("diff").unwrap() // default is all
                })?)?;
        }

        // Update processor
        self.processor = processor;

        // Debug
        // Clear terminal cells
        #[cfg(feature = "debug")]
        if args.is_present("debug") {
            Utils::clear_terminal()?;
        }

        // ========
        // Main options
        // print permission
        self.processor.print_permission()?;

        // Process
        // Redirect stdin as argument
        if args.is_present("pipe") {
            let stdin = std::io::stdin();
            let mut input = String::new();
            stdin.lock().read_to_string(&mut input)?;
            self.processor.set_pipe(&input)
        }

        // -->> Read from files or process as raw text
        if let Some(sources) = args.values_of("INPUT") {
            // Also read from stdin if given combiation option
            if args.is_present("combination") {
                self.processor.process_stdin()?;
            }

            // Interpret every input source as literal text
            let literal = args.is_present("literal");

            // Read from given sources and write with given options
            for src in sources {
                if literal {
                    self.processor.process_string(src)?;
                } else {
                    let src_as_file = Path::new(src);
                    if src_as_file.exists() {
                        match self.processor.process_file(src_as_file) {
                            // Exit is a sane behaviour and should not exit from whole process
                            Ok(_) => {
                                self.processor.reset_flow_control();
                                continue;
                            }
                            Err(err) => {
                                return Err(err);
                            }
                        }
                    } else {
                        return Err(RadError::InvalidFile(format!("{}", src_as_file.display())));
                    }
                }
            }
            #[cfg(feature = "signature")]
            self.print_signature(args)?;
        } else {
            // -->> Read from stdin

            // Print signature if such option is given
            // Signature option doesn't go with stdin option
            #[cfg(feature = "signature")]
            if self.print_signature(args)? {
                return Ok(());
            }
            self.processor.process_stdin()?;
        }

        // Print result
        self.processor.print_result()?;

        // Freeze to a rule file if such option was given
        if let Some(file) = args.value_of("freeze") {
            self.processor.freeze_to_file(Path::new(file))?;
        }
        Ok(())
    }

    /// Print signature
    ///
    /// Returns whether signature operation was executed or not
    #[cfg(feature = "signature")]
    fn print_signature(&mut self, args: &clap::ArgMatches) -> RadResult<bool> {
        #[cfg(feature = "signature")]
        if args.occurrences_of("signature") != 0 {
            let sig_type = SignatureType::from_str(args.value_of("sigtype").unwrap_or("all"))?;
            let sig_map = self.processor.get_signature_map(sig_type)?;
            // TODO
            let sig_json =
                serde_json::to_string(&sig_map.content).expect("Failed to create sig map");

            // This is file name
            let file_name = args.value_of("signature").unwrap();

            // This is default empty value should not be "" because it is ignored by clap
            if file_name != " " {
                std::fs::write(Path::new(file_name), sig_json.as_bytes())?;
            } else {
                writeln!(std::io::stdout(), "{}", &sig_json)?;
            }
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Parse processor options
    fn parse_options(&mut self, args: &clap::ArgMatches) {
        // ========
        // Sub options
        // custom rules
        self.rules = if let Some(files) = args.values_of("melt") {
            files
                .into_iter()
                .map(PathBuf::from)
                .collect::<Vec<PathBuf>>()
        } else {
            vec![]
        };

        // Write to file
        self.write_to_file = args.value_of("out").map(PathBuf::from);

        // Error to file
        self.error_to_file = args.value_of("err").map(PathBuf::from);

        // Permission
        if let Some(auths) = args.value_of("allow") {
            self.allow_auth = auths
                .split('+')
                .into_iter()
                .filter_map(AuthType::from)
                .collect()
        }

        // Permission with warning
        if let Some(auths) = args.value_of("allow_warn") {
            self.allow_auth_warn = auths
                .split('+')
                .into_iter()
                .filter_map(AuthType::from)
                .collect()
        }

        // Permission all
        if args.is_present("allow_all") {
            self.allow_auth = vec![AuthType::FIN, AuthType::FOUT, AuthType::ENV, AuthType::CMD];
        }

        // Permission all with warning
        if args.is_present("allow_all_warn") {
            self.allow_auth_warn =
                vec![AuthType::FIN, AuthType::FOUT, AuthType::ENV, AuthType::CMD];
        }
    }

    fn args_builder(source: Option<&[&str]>) -> clap::ArgMatches {
        use clap::{App, Arg};
        let app = App::new("rad")
            .version("3.0")
            .author("Simon creek <simoncreek@tutanota.com>")
            .about( "R4d(rad) is a modern macro processor made with rust. Refer https://github.com/simhyeon/r4d for detailed usage.")
            .long_about("R4d is a text oriented macro processor which aims to be an modern alternative to m4 macro processor. R4d procedurally follows texts and substitue macro calls with defined macro body. R4d comes with varoius useful built in macros so that user don't have to define from scratch. R4d also supports multiple debugging flags for easier error detection. Refer https://github.com/simhyeon/r4d for detailed usage.")
            .override_usage("rad <FILE> -o <OUT_FILE> -e <ERR_FILE>
    echo <STDIN_TEXT | rad 
    echo <STDIN_TEXT> | rad --combination <FILE> --diff
    rad <FILE> --debug --log --interactive
    rad <FILE> -f <RULE_FILE> --discard -n --silent")
            .arg(Arg::new("INPUT")
                .multiple_values(true)
                .help("INPUT source to execute processing"))
            .arg(Arg::new("pipe")
                .long("pipe")
                .conflicts_with("combination")
                .help("Send stdin as a pipe value"))
            .arg(Arg::new("literal")
                .long("literal")
                .help("Don't interpret input source as file"))
            .arg(Arg::new("out")
                .short('o')
                .long("out")
                .takes_value(true)
                .conflicts_with("discard")
                .value_name("FILE")
                .help("Save processed output to the file"))
            .arg(Arg::new("err")
                .short('e')
                .long("err")
                .takes_value(true)
                .value_name("FILE")
                .help("Save error logs to the file"))
            .arg(Arg::new("combination")
                .short('c')
                .long("combination")
                .help("Read from both stdin and file inputs. Stdin is evaluated first"))
            .arg(Arg::new("discard")
                .short('D')
                .long("discard")
                .help("Discard output"))
            .arg(Arg::new("silent")
                .short('s')
                .long("silent")
                .takes_value(true)
                .default_missing_value("none")
                .value_name("WARNING TYPE")
                .help("Supress warnings (security|sanity|any)"))
            .arg(Arg::new("purge")
                .short('p')
                .long("purge")
                .help("Purge unused macros without panicking. Doesn't work in strict mode"))
            .arg(Arg::new("lenient")
                .short('l')
                .long("lenient")
                .help("Lenient mode, disables strict mode"))
            .arg(Arg::new("debug")
                .short('d')
                .long("debug")
                .help("Debug mode"))
            .arg(Arg::new("log")
                .long("log")
                .help("Print log for every macro invocation. Only works on debug mode"))
            .arg(Arg::new("diff")
                .long("diff")
                .takes_value(true)
                .value_name("DIFF TYPE")
                .default_missing_value("all")
                .help("Show diff result (none|change|all)"))
            .arg(Arg::new("interactive")
                .short('i')
                .long("interactive")
                .help("Use interactive debug mode. This enables line wrapping."))
            .arg(Arg::new("assert")
                .long("assert")
                .help("Enable assert mode"))
            .arg(Arg::new("comment")
                .long("comment")
                .takes_value(true)
                .default_missing_value("start")
                .value_name("COMMENT TYPE")
                .help("Use comment option (none|start|any)"))
            .arg(Arg::new("allow")
                .short('a')
                .takes_value(true)
                .value_name("AUTH TYPE")
                .help("Allow permission (fin|fout|cmd|env)"))
            .arg(Arg::new("allow_warn")
                .short('w')
                .takes_value(true)
                .value_name("AUTH TYPE")
                .help("Allow permission with warnings (fin|fout|cmd|env)"))
            .arg(Arg::new("allow_all")
                .short('A')
                .conflicts_with("allow_all_warn")
                .help("Allow all permission"))
            .arg(Arg::new("allow_all_warn")
                .short('W')
                .conflicts_with("allow_all")
                .help("Allow all permission with warning"))
            .arg(Arg::new("newline")
                .short('n')
                .long("newline")
                .help("Use unix newline for formatting"))
            .arg(Arg::new("melt")
                .short('m')
                .long("melt")
                .takes_value(true)
                .value_name("FILE")
                .help("Read macros from frozen file"))
            .arg(Arg::new("freeze")
                .short('f')
                .long("freeze")
                .takes_value(true)
                .value_name("FILE")
                .help("Freeze macros into a single file"));

        #[cfg(feature = "signature")]
        let app = app
            .arg(
                Arg::new("manual")
                    .long("man")
                    .takes_value(true)
                    .default_missing_value("*")
                    .value_name("MACRO_NAME")
                    .help("Get manual of a macro"),
            )
            .arg(
                Arg::new("signature")
                    .long("signature")
                    .takes_value(true)
                    .value_name("FILE")
                    .default_missing_value(" ")
                    .help("Print signature to file."),
            )
            .arg(
                Arg::new("sigtype")
                    .long("sigtype")
                    .takes_value(true)
                    .value_name("SIG TYPE")
                    .default_value("all")
                    .help("Signature type to get"),
            );

        if let Some(src) = source {
            app.get_matches_from(src)
        } else {
            app.get_matches()
        }
    }
}