From 42dddd64fe87e8fda97d69f682ea58e9e444c57a Mon Sep 17 00:00:00 2001 From: Filippo Costa Date: Mon, 15 Jan 2024 11:55:44 +0100 Subject: [PATCH] Initial commit Signed-off-by: Filippo Costa --- .github/workflows/ci.yml | 74 +++++++++++ .gitignore | 13 ++ Cargo.lock | 253 ++++++++++++++++++++++++++++++++++++ Cargo.toml | 19 +++ LICENSE.txt | 201 +++++++++++++++++++++++++++++ src/main.rs | 268 +++++++++++++++++++++++++++++++++++++++ 6 files changed, 828 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE.txt create mode 100644 src/main.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..855eee9 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,74 @@ +name: CI + +on: + push: + branches: ["main"] + pull_request: + branches: ["main"] + +env: + CARGO_TERM_COLOR: always + RUSTFLAGS: -D warnings + +jobs: + check-aggregate: + # Follows the guide at . + runs-on: ubuntu-latest + if: always() + needs: + # If you're modifying this workflow file and you're adding/removing a job + # which should be required to pass before merging a PR, don't forget to + # update this list! + - check + - features + - test + steps: + - name: Compute whether the needed jobs succeeded or failed + uses: re-actors/alls-green@release/v1 + with: + allowed-skips: deploy-github-pages + jobs: ${{ toJSON(needs) }} + + check: + name: check + runs-on: buildjet-4vcpu-ubuntu-2204 + timeout-minutes: 60 + steps: + - uses: actions/checkout@v3 + - name: Install Rust + run: rustup show + - uses: Swatinem/rust-cache@v2 + - name: Check formatting + run: cargo fmt --all --check + - run: cargo check --all-targets --all-features + - run: cargo clippy --all-targets --all-features + + # Check that every combination of features is working properly. + features: + name: features + runs-on: buildjet-8vcpu-ubuntu-2204 + timeout-minutes: 120 + steps: + - uses: actions/checkout@v3 + - name: Install Rust + run: rustup show + - name: cargo install cargo-hack + uses: taiki-e/install-action@cargo-hack + - uses: Swatinem/rust-cache@v2 + - name: cargo hack + run: cargo hack check --workspace --feature-powerset --all-targets + test: + name: test + runs-on: buildjet-4vcpu-ubuntu-2204 + timeout-minutes: 60 + steps: + - uses: actions/checkout@v3 + - uses: taiki-e/install-action@nextest + - name: Install Rust + run: rustup show + - uses: Swatinem/rust-cache@v2 + - run: cargo nextest run --workspace --all-features + # `cargo-nextest` does not support doctests (yet?), so we have to run them + # separately. + # TODO: https://github.com/nextest-rs/nextest/issues/16 + - run: cargo test --workspace --doc --all-features diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5478aeb --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +# From . +# Cargo.lock is not .gitignore'd because the repository contains binaries. + +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..881f40c --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,253 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "anstream" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd2405b3ac1faab2990b74d728624cd9fd115651fcecc7c2d8daf01376275ba" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7079075b41f533b8c61d2a4d073c4676e1f8b249ff94a393b0595db304e0dd87" + +[[package]] +name = "anstyle-parse" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c75ac65da39e5fe5ab759307499ddad880d724eed2f6ce5b5e8a26f4f387928c" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e28923312444cdd728e4738b3f9c9cac739500909bb3d3c94b43551b16517648" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cd54b81ec8d6180e24654d0b371ad22fc3dd083b6ff8ba325b72e00c87660a7" +dependencies = [ + "anstyle", + "windows-sys", +] + +[[package]] +name = "bashtestmd" +version = "0.3.0" +dependencies = [ + "clap", + "indoc", + "markdown", + "shell-escape", +] + +[[package]] +name = "clap" +version = "4.4.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58e54881c004cec7895b0068a0a954cd5d62da01aef83fa35b1e594497bf5445" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.4.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59cb82d7f531603d2fd1f507441cdd35184fa81beff7bd489570de7f773460bb" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf9804afaaf59a91e75b022a30fb7229a7901f60c755489cc61c9b423b836442" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "702fc72eb24e5a1e48ce58027a675bc24edd52096d5397d4aea7c6dd9eca0bd1" + +[[package]] +name = "colorchoice" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "indoc" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e186cfbae8084e513daff4240b4797e342f988cecda4fb6c939150f96315fd8" + +[[package]] +name = "markdown" +version = "1.0.0-alpha.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b0f0025e8c0d89b84d6dc63e859475e40e8e82ab1a08be0a93ad5731513a508" +dependencies = [ + "unicode-id", +] + +[[package]] +name = "proc-macro2" +version = "1.0.76" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95fc56cda0b5c3325f5fbbd7ff9fda9e02bb00bb3dac51252d2f1bfa1cb8cc8c" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "shell-escape" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45bb67a18fa91266cc7807181f62f9178a6873bfad7dc788c42e6430db40184f" + +[[package]] +name = "strsim" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" + +[[package]] +name = "syn" +version = "2.0.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f3531638e407dfc0814761abb7c00a5b54992b849452a0646b7f65c9f770f3f" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-id" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1b6def86329695390197b82c1e244a54a131ceb66c996f2088a3876e2ae083f" + +[[package]] +name = "unicode-ident" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" + +[[package]] +name = "utf8parse" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a18201040b24831fbb9e4eb208f8892e1f50a37feb53cc7ff887feb8f50e7cd" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7764e35d4db8a7921e09562a0304bf2f93e0a51bfccee0bd0bb0b666b015ea" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbaa0368d4f1d2aaefc55b6fcfee13f41544ddf36801e793edbbfd7d7df075ef" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28637cb1fa3560a16915793afb20081aba2c92ee8af57b4d5f28e4b3e7df313" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffe5e8e31046ce6230cc7215707b816e339ff4d4d67c65dffa206fd0f7aa7b9a" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d6fa32db2bc4a2f5abeacf2b69f7992cd09dca97498da74a151a3132c26befd" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a657e1e9d3f514745a572a6846d3c7aa7dbe1658c056ed9c3344c4109a6949e" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..4cd9b9c --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "bashtestmd" +version = "0.3.0" +description = "Compiles shell commands in .md files into Bash scripts for testing" +edition = "2021" +authors = ["Sovereign Labs "] +repository = "https://github.com/sovereign-labs/bashtestmd" +homepage = "https://www.sovereign.xyz" +license = "MIT OR Apache-2.0" + +resolver = "2" +autotests = false +publish = true + +[dependencies] +clap = { version = "4", features = ["derive"] } +indoc = "2" +markdown = "1.0.0-alpha.16" +shell-escape = "0.1.5" diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..9214f23 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,268 @@ +use std::collections::VecDeque; +use std::io::{self, Write}; + +use clap::Parser; +use indoc::indoc; +use markdown::mdast; + +#[derive(Debug, Parser)] +struct Args { + /// Input Markdown file to parse + #[clap(short, long)] + input: String, + /// Path to output Bash script + #[clap(short, long)] + output: String, + /// Only run code blocks with this tag + #[clap(short, long)] + tag: String, +} + +fn main() { + let args = Args::parse(); + + let file_contents = std::fs::read_to_string(&args.input).unwrap(); + let markdown_parse_options = markdown::ParseOptions::gfm(); + let markdown_ast = markdown::to_mdast(&file_contents, &markdown_parse_options).unwrap(); + + let code_blocks = get_all_code_blocks(markdown_ast); + let commands = convert_code_blocks_into_commands(code_blocks, &args.tag); + let script = compile_commands_into_bash(commands); + + std::fs::write(&args.output, script).unwrap(); +} + +struct Command { + cmd: String, + long_running: bool, + expected_output: Option, + wait_until: Option, + exit_code: Option, +} + +impl Command { + fn new(cmd: &str) -> Self { + Self { + cmd: cmd.to_string(), + long_running: false, + expected_output: None, + wait_until: None, + exit_code: Some(0), + } + } + + fn compile(&self, mut w: impl io::Write) -> io::Result<()> { + writeln!( + w, + "echo {}", + shell_escape::escape(format!("Running: '{}'", self.cmd).into()) + )?; + + if self.long_running { + if let Some(wait_until) = &self.wait_until { + writeln!( + w, + indoc!( + r#" + output=$(mktemp) + {} &> $output & + background_process_pid=$! + echo "Waiting for process with PID: $background_process_pid" + until grep -q -i {} $output + do + if ! ps $background_process_pid > /dev/null + then + echo "The background process died died" >&2 + exit 1 + fi + echo -n "." + sleep 5 + done + "# + ), + self.cmd, + shell_escape::escape(wait_until.into()) + )?; + } else { + // No expected output, just run the command and wait two + // minutes. Very, very hackish. + writeln!(w, "{} &", self.cmd)?; + writeln!(w, "sleep 120")?; + } + return Ok(()); + } + + if let Some(output) = &self.expected_output { + writeln!( + w, + indoc!( + r#" + output=$({}) + expected={} + # Either of the two must be a substring of the other. This kinda protects us + # against whitespace differences, trimming, etc. + if ! [[ $output == *"$expected"* || $expected == *"$output"* ]]; then + echo "'$expected' not found in text:" + echo "'$output'" + exit 1 + fi + "# + ), + self.cmd, + shell_escape::escape(output.into()) + )?; + } else { + writeln!(w, "{}", self.cmd)?; + } + + if let Some(exit_code) = self.exit_code { + writeln!( + w, + indoc!( + r#" + if [ $? -ne {0} ]; then + echo "Expected exit code {0}, got $?" + exit 1 + fi + "#, + ), + exit_code + )?; + } + + Ok(()) + } +} + +fn compile_commands_into_bash(cmds: Vec) -> String { + let mut script = Vec::::new(); + // Shebang. + writeln!(&mut script, "#!/usr/bin/env bash").unwrap(); + writeln!(&mut script, r#"trap 'jobs -p | xargs -r kill' EXIT"#).unwrap(); + + for cmd in cmds { + cmd.compile(&mut script).unwrap(); + } + writeln!(&mut script, r#"echo "All tests passed!"; exit 0"#).unwrap(); + String::from_utf8(script).unwrap() +} + +struct CodeBlockTags { + long_running: bool, + compare_output: bool, + exit_code: Option, + wait_until: Option, +} + +impl CodeBlockTags { + fn parse(code_block: &mdast::Code) -> Self { + let langs: Vec = code_block + .lang + .as_deref() + .unwrap_or_default() + .split(',') + .map(str::to_string) + .collect(); + + let mut tags = Self { + long_running: false, + compare_output: false, + exit_code: Some(0), + wait_until: None, + }; + + for lang in langs { + if lang == "bashtestmd:long-running" { + tags.long_running = true; + } else if lang == "bashtestmd:compare-output" { + tags.compare_output = true; + } else if lang == "bashtestmd:exit-code-ignore" { + tags.exit_code = None; + } else if lang.starts_with("bashtestmd:exit-code=") { + let exit_code = lang.split_once('=').unwrap().1.parse().unwrap(); + tags.exit_code = Some(exit_code); + } else if lang.starts_with("bashtestmd:wait-until=") { + let wait_until = lang.split_once('=').unwrap().1.to_string(); + tags.wait_until = Some(wait_until); + } else { + println!("Unknown bashtestmd tag, ignoring: {}", lang); + } + } + + tags + } +} + +fn convert_code_blocks_into_commands( + code_blocks: Vec, + only_tag: &str, +) -> Vec { + const PROMPT: &str = "$ "; + + let mut commands = Vec::new(); + + for code_block in code_blocks { + if !code_block + .lang + .as_deref() + .unwrap_or_default() + .contains(only_tag) + { + continue; + } + let tags = CodeBlockTags::parse(&code_block); + + let mut cmd: Option = None; + let mut output = String::new(); + + for line in code_block.value.lines() { + if let Some(cmd_string) = line.strip_prefix(PROMPT) { + if let Some(cmd) = cmd { + commands.push(Command::new(&cmd)); + } + cmd = Some(cmd_string.to_string()); + } else { + output.push_str(line); + output.push('\n'); + } + } + if let Some(cmd) = cmd { + let mut cmd = Command::new(&cmd); + cmd.long_running = tags.long_running; + cmd.wait_until = tags.wait_until; + cmd.expected_output = if tags.compare_output { + Some(output) + } else { + None + }; + commands.push(cmd); + } + } + + commands +} + +/// Ordered list of all code blocks in the Markdown file. +fn get_all_code_blocks(markdown_ast: mdast::Node) -> Vec { + let mut code_blocks = Vec::new(); + + let mut nodes: VecDeque = markdown_ast + .children() + .cloned() + .unwrap_or_default() + .into_iter() + .collect(); + + while let Some(next_node) = nodes.pop_front() { + if let mdast::Node::Code(code_node) = next_node { + code_blocks.push(code_node); + } else { + let children = next_node.children().map(Vec::as_slice).unwrap_or_default(); + for child in children.iter() { + nodes.push_front(child.clone()); + } + } + } + + code_blocks +}