btl 0.2.8

Btl is a simple library that makes shell scripting with rust easier. It was originally written with the purposes of being used for build.rs files, but it can be used for more complex purposes. It's main premise is about making shell scripting easier to work with rust. This works both on windows and unix machines. Originally designed in linux, not tested on Windows or Mac yet, but they should work since the library is platform-agnostic. Github Repo: https://github.com/znx3p0/btlsh
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
use proc_macro::TokenStream;
use quote::quote;
use syn::parse::{Parse, ParseStream, Result};
use syn::{parse_macro_input, Expr, Token};

struct Commands {
    fmt: Vec<String>,
    args: Vec<String>,
}

struct CD {
    fmt: Expr,
    args: Vec<Expr>,
}

impl Parse for Commands {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut fmt: Vec<String> = vec![];
        let mut args: Vec<String> = vec![];
        // Parse all commands loop

        'cmd: loop {
            let cmd = match input.parse::<Expr>() {
                Ok(cmd) => cmd,
                Err(_) => break,
            };

            let mut current_expr = vec![];

            loop {
                if input.parse::<Token![;]>().is_ok() {
                    fmt.push(quote! {#cmd}.to_string());
                    args.push(quote! {#(,#current_expr)*}.to_string());

                    continue 'cmd;
                }

                current_expr.push(input.parse::<Expr>().unwrap());
            }
        }

        Ok(Commands {
            fmt: fmt,
            args: args,
        })
    }
}

impl Parse for CD {
    fn parse(input: ParseStream) -> Result<Self> {
        let fmt: Expr = input.parse().unwrap();

        let mut args: Vec<Expr> = vec![];
        // Parse all commands loop

        loop {
            match input.parse::<Expr>() {
                Ok(cmd) => args.push(cmd),
                Err(_) => break,
            }
        }

        Ok(CD { fmt, args })
    }
}

/// The shell!{} macro allows for easy integration of the shell for rust.
/// It is designed to be ergonomic, easy to use and understand.

/// All other macros are based of this macro's syntax since it's easy to use,
/// and easy to customize.
///
///
/// Syntax:
/// You have to call the macro followed by a command.
/// This command can be used as a format! format string
///
/// Variables you use in the format string need to be after
/// the command and need to be separated by spaces. No commas.
/// Commands are separated by semicolons and they're obligatory.
///
/// ```
/// use btl::shell;
/// let foo = "test";
///
/// shell! {
///     "pwd";
///     "cd ..";
///     "pwd";
///     "echo {} > example.txt" foo;
/// };
/// ```
///
///
/// It's important to understand this syntax because all other macros this crate includes
/// are based off this syntax.
/// All other macros are slight variations of this macro,
/// but the use cases differ from relatively the same as this macro,
/// to completely different use cases, such as the detach!{} macro.
///
/// The main differences between these macros compared to the shell macro are:

/// - detach!{}: completely detaches the shell process to be run from the rust process.
/// - execute!{}: returns the stdout as a String.
/// - exec!{}: returns a bool if the command was successful.
/// - detailed_exec!{}: returns the output of the whole command as std::process::Output.
/// - cd!{}: changes the rust's process directory. This is important to note since all other macros live on their own shell.
///
#[proc_macro]
pub fn shell(input: TokenStream) -> TokenStream {
    if input.to_string().len() == 0 {
        return "".to_string().parse().unwrap();
    }

    let Commands { fmt, args } = parse_macro_input!(input as Commands);

    let key = std::time::SystemTime::elapsed(&std::time::UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let args = args.join("");
    let mut fmt = fmt.join(format!(" {}", key).as_str());

    if cfg!(target_os = "windows") {
        fmt = fmt.replace(format!("\" {}\"", key).as_str(), ";");
    } else {
        fmt = fmt.replace(format!("\" {}\"", key).as_str(), " && ");
    }

    let out;
    if cfg!(target_os = "windows") {
        out = format!(
            "
std::process::Command::new(\"powershell\")
.args(&[\"-C\", format!({}{}).as_str()])
.spawn()
.unwrap()
.wait()
.unwrap();
",
            fmt, args
        );
    } else {
        out = format!(
            "
std::process::Command::new(\"sh\")
.arg(\"-c\")
.arg(format!({}{}))
.spawn()
.unwrap()
.wait()
.unwrap();
",
            fmt, args
        );
    }

    out.to_string().parse().unwrap()
}

/// This is equivalent to shell in syntax and in execution.
/// The difference is that this shell process is completely separated
/// from the rust process and can outlive the rust process.     
/// This is exceptionally useful for creating programs which outlive the main process.
///
/// This macro returns an std::process::Child
///
/// Try running this example.
///
/// ```
/// use btl::detach;
///
/// detach! {
///     "touch example.txt";
///     "sleep {}" 10;
///     "rm example.txt";
/// };
///
/// ```
///
#[proc_macro]
pub fn detach(input: TokenStream) -> TokenStream {
    if input.to_string().len() == 0 {
        return "".to_string().parse().unwrap();
    }

    let Commands { fmt, args } = parse_macro_input!(input as Commands);

    let key = std::time::SystemTime::elapsed(&std::time::UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let args = args.join("");
    let mut fmt = fmt.join(format!(" {}", key).as_str());

    if cfg!(target_os = "windows") {
        fmt = fmt.replace(format!("\" {}\"", key).as_str(), ";");
    } else {
        fmt = fmt.replace(format!("\" {}\"", key).as_str(), " && ");
    }

    let out;
    if cfg!(target_os = "windows") {
        out = format!(
            "
{{
std::process::Command::new(\"powershell\")
.args(&[\"-C\", format!({}{}).as_str()])
.spawn()
.unwrap()
}}
",
            fmt, args
        );
    } else {
        out = format!(
            "
{{
std::process::Command::new(\"sh\")
.arg(\"-c\")
.arg(format!({}{}))
.spawn()
.unwrap()
}}
",
            fmt, args
        );
    }

    out.to_string().parse().unwrap()
}

// Returns stdout string
/// It's the same as all macros, but it returns the stdout as a String.

/// This is useful for getting information from cli tools back to rust ergonomically.

/// If you do not understand the syntax of this macro, please read the docs from shell!{}
/// as it provides the same interface but has different purposes.
///
/// ```
/// use btl::execute;
///
/// let contents = execute! {
///     "ls -la";
/// };
///
/// println!("Current directory's contents: {}", contents);
/// ```
#[proc_macro]
pub fn execute(input: TokenStream) -> TokenStream {
    if input.to_string().len() == 0 {
        return "".to_string().parse().unwrap();
    }

    let Commands { fmt, args } = parse_macro_input!(input as Commands);

    let key = std::time::SystemTime::elapsed(&std::time::UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let args = args.join("");
    let mut fmt = fmt.join(format!(" {}", key).as_str());

    if cfg!(target_os = "windows") {
        fmt = fmt.replace(format!("\" {}\"", key).as_str(), ";");
    } else {
        fmt = fmt.replace(format!("\" {}\"", key).as_str(), " && ");
    }

    let out;
    if cfg!(target_os = "windows") {
        out = format!(
            "
{{
    std::string::String::from_utf8_lossy(
        std::process::Command::new(\"powershell\")
        .args(&[\"-C\", format!({}{}).as_str()])
        .spawn()
        .unwrap().wait_with_output().unwrap().stdout.as_slice()
    ).to_string()
}}
",
            fmt, args
        );
    } else {
        out = format!(
            "
{{
    std::string::String::from_utf8_lossy(
        std::process::Command::new(\"sh\")
        .arg(\"-c\")
        .arg(format!({}{}))
        .spawn()
        .unwrap().wait_with_output().unwrap().stdout.as_slice()
    ).to_string()
}}
",
            fmt, args
        );
    }

    out.to_string().parse().unwrap()
}

// Returns status as bool
/// It's the same as all macros, but it returns a bool indicating if the command succeded.

/// If you do not understand the syntax of this macro, please read the docs from shell!{}
/// as it provides the same interface but has different purposes.
///
/// ```
/// use btl::exec;
///
/// if exec! {
///     "ls -la | grep Cargo";
/// } {
///     println!("Cargo found");
/// } else {
///     println!("Cargo not found");
/// }
/// ```
///
#[proc_macro]
pub fn exec(input: TokenStream) -> TokenStream {
    if input.to_string().len() == 0 {
        return "".to_string().parse().unwrap();
    }

    let Commands { fmt, args } = parse_macro_input!(input as Commands);

    let key = std::time::SystemTime::elapsed(&std::time::UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let args = args.join("");
    let mut fmt = fmt.join(format!(" {}", key).as_str());

    if cfg!(target_os = "windows") {
        fmt = fmt.replace(format!("\" {}\"", key).as_str(), ";");
    } else {
        fmt = fmt.replace(format!("\" {}\"", key).as_str(), " && ");
    }

    let out;
    if cfg!(target_os = "windows") {
        out = format!(
            "
{{
    std::process::Command::new(\"powershell\")
    .args(&[\"-C\", format!({}{}).as_str()])
    .output().unwrap().status.success()
}}
",
            fmt, args
        );
    } else {
        out = format!(
            "
{{
    std::process::Command::new(\"sh\")
    .arg(\"-c\")
    .arg(format!({}{}))
    .output().unwrap().status.success()
}}
",
            fmt, args
        );
    }

    out.to_string().parse().unwrap()
}

// Returns complete output
/// It's the same as all macros, but it returns a std::process::Output

/// If you do not understand the syntax of this macro, please read the docs from shell!{}
/// as it provides the same interface but has different purposes.
///
///```
/// use btl::detailed_exec;
///
/// let out: std::process::Output = detailed_exec! {
///     "pwd";
/// };
/// println!("{:#?}", out);
///
/// ```

#[proc_macro]
pub fn detailed_exec(input: TokenStream) -> TokenStream {
    if input.to_string().len() == 0 {
        return "".to_string().parse().unwrap();
    }

    let Commands { fmt, args } = parse_macro_input!(input as Commands);

    let key = std::time::SystemTime::elapsed(&std::time::UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let args = args.join("");
    let mut fmt = fmt.join(format!(" {}", key).as_str());

    if cfg!(target_os = "windows") {
        fmt = fmt.replace(format!("\" {}\"", key).as_str(), ";");
    } else {
        fmt = fmt.replace(format!("\" {}\"", key).as_str(), " && ");
    }

    let out;
    if cfg!(target_os = "windows") {
        out = format!(
            "
{{
    std::process::Command::new(\"powershell\")
    .args(&[\"-C\", format!({}{}).as_str()])
    .spawn()
    .unwrap().wait_with_output().unwrap()
}}
",
            fmt, args
        );
    } else {
        out = format!(
            "
{{
    std::process::Command::new(\"sh\")
    .arg(\"-c\")
    .arg(format!({}{}))
    .spawn()
    .unwrap().wait_with_output().unwrap()
}}
",
            fmt, args
        );
    }

    out.to_string().parse().unwrap()
}

/// The cd macro changes the directory of the current rust process.
/// This does not work for shell or any of the other macros.
/// Only works as a helper macro to make it easier to use cd inside rust.
/// You can still use all normal commands, including cd inside all macros.
/// They don't change the rust's process directory.
/// That's this macro's purpose.
///
///```
/// use btl::cd;
///
/// let dir = "..";
/// cd!{
///     "{}" dir
/// };
///
///
/// cd!{
///     ".."
/// };
///
///```
///
#[proc_macro]
pub fn cd(input: TokenStream) -> TokenStream {
    if input.to_string().len() == 0 {
        return "".to_string().parse().unwrap();
    }

    let CD { fmt, args } = parse_macro_input!(input as CD);

    let p = quote! {
        std::env::set_current_dir(format!(#fmt #(,#args)*).as_str()).unwrap();
    };

    TokenStream::from(p)
}

/// The pwd macro gives back the current working directory. Nothing fancy.
///
/// ```
/// use btl::pwd;
///
/// let curr = pwd!();
/// println!("Current working directory: {}", curr);
///
/// ```
///
#[proc_macro]
pub fn pwd(_: TokenStream) -> TokenStream {
    TokenStream::from(quote! {
        std::env::current_dir().unwrap().to_string_lossy().to_string()
    })
}