From 24359131f7d33d51aecd211e89770656b0a1971a Mon Sep 17 00:00:00 2001 From: Auca Coyan Date: Tue, 6 Jun 2023 09:34:07 -0300 Subject: [PATCH] :white_check_mark: restore testing, add CI workflow and `README.md` (#16) * :white_check_mark: restore testing, add CI workflow and `README.md` * :rewind: move `example.nu` back into the benches\ folder * :rewind: return benchmarking with `criterion` --- .github/workflows/clippy_check.yml | 18 --- .github/workflows/main.yml | 50 ++++++++ .github/workflows/pull_request.yml | 43 +++++++ Cargo.lock | 75 ++--------- Cargo.toml | 4 +- README.md | 82 ++++++++++-- benches/bench.rs | 17 --- {examples => benches}/example.nu | 0 benches/file-format-bench.rs | 15 +++ examples/24bit-1.nu | 37 ------ examples/256_color_testpattern.nu | 69 ---------- examples/gradient.nu | 41 ------ examples/turtle.nu | 10 -- src/lib.rs | 198 +++-------------------------- src/main.rs | 5 - 15 files changed, 210 insertions(+), 454 deletions(-) delete mode 100644 .github/workflows/clippy_check.yml create mode 100644 .github/workflows/main.yml create mode 100644 .github/workflows/pull_request.yml delete mode 100644 benches/bench.rs rename {examples => benches}/example.nu (100%) create mode 100644 benches/file-format-bench.rs delete mode 100644 examples/24bit-1.nu delete mode 100644 examples/256_color_testpattern.nu delete mode 100644 examples/gradient.nu delete mode 100644 examples/turtle.nu diff --git a/.github/workflows/clippy_check.yml b/.github/workflows/clippy_check.yml deleted file mode 100644 index 9f184f4..0000000 --- a/.github/workflows/clippy_check.yml +++ /dev/null @@ -1,18 +0,0 @@ -on: [push, pull_request] - -name: Clippy check - -jobs: - clippy_check: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - - name: Setup Rust toolchain and cache - uses: actions-rust-lang/setup-rust-toolchain@v1.4.4 - - - name: cargo fmt - run: cargo fmt --all -- --check - - - name: Clippy - run: cargo clippy --no-deps diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..3dbcd60 --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,50 @@ +# This workflow run when something is pushed on main and it does +# normal checks like in the normal PRs + +# Jobs on pull request +name: CI on main +on: + workflow_dispatch: + push: + branches: + - main + +jobs: + format: + name: format rust files + runs-on: ubuntu-latest + steps: + - name: checkout repository + uses: actions/checkout@v3 + - name: Setup Rust toolchain and cache + uses: actions-rust-lang/setup-rust-toolchain@v1.4.4 + - name: format files + run: cargo fmt --all --check + + lint: + name: lint all rust files + runs-on: ubuntu-latest + steps: + - name: checkout repository + uses: actions/checkout@v3 + - name: Setup Rust toolchain and cache + uses: actions-rust-lang/setup-rust-toolchain@v1.4.4 + - name: Clippy + run: cargo clippy --no-deps + + test: + name: test rust files + strategy: + matrix: + include: + - os: windows-latest + - os: ubuntu-latest + + runs-on: ${{ matrix.os }} + steps: + - name: checkout repository + uses: actions/checkout@v3 + - name: Setup Rust toolchain and cache + uses: actions-rust-lang/setup-rust-toolchain@v1.4.4 + - name: run tests + run: cargo test --workspace diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml new file mode 100644 index 0000000..7e90384 --- /dev/null +++ b/.github/workflows/pull_request.yml @@ -0,0 +1,43 @@ +# Jobs on pull request +name: Pull request +on: pull_request + +jobs: + format: + name: format rust files + runs-on: ubuntu-latest + steps: + - name: checkout repository + uses: actions/checkout@v3 + - name: Setup Rust toolchain and cache + uses: actions-rust-lang/setup-rust-toolchain@v1.4.4 + - name: format files + run: cargo fmt --all --check + + lint: + name: lint all rust files + runs-on: ubuntu-latest + steps: + - name: checkout repository + uses: actions/checkout@v3 + - name: Setup Rust toolchain and cache + uses: actions-rust-lang/setup-rust-toolchain@v1.4.4 + - name: Clippy + run: cargo clippy --no-deps + + test: + name: test rust files + strategy: + matrix: + include: + - os: windows-latest + - os: ubuntu-latest + + runs-on: ${{ matrix.os }} + steps: + - name: checkout repository + uses: actions/checkout@v3 + - name: Setup Rust toolchain and cache + uses: actions-rust-lang/setup-rust-toolchain@v1.4.4 + - name: run tests + run: cargo test --workspace diff --git a/Cargo.lock b/Cargo.lock index 93be9b3..563e28c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -121,17 +121,6 @@ version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" -[[package]] -name = "atty" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" -dependencies = [ - "hermit-abi 0.1.19", - "libc", - "winapi", -] - [[package]] name = "autocfg" version = "1.1.0" @@ -251,18 +240,6 @@ dependencies = [ "half", ] -[[package]] -name = "clap" -version = "3.2.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ea181bf566f71cb9a5d17a59e1871af638180a18fb0035c92ae62b705207123" -dependencies = [ - "bitflags", - "clap_lex 0.2.4", - "indexmap", - "textwrap 0.16.0", -] - [[package]] name = "clap" version = "4.3.0" @@ -283,7 +260,7 @@ dependencies = [ "anstream", "anstyle", "bitflags", - "clap_lex 0.5.0", + "clap_lex", "strsim", "unicase", "unicode-width", @@ -301,15 +278,6 @@ dependencies = [ "syn 2.0.18", ] -[[package]] -name = "clap_lex" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2850f2f5a82cbf437dd5af4d49848fbdfc27c157c3d010345776f952765261c5" -dependencies = [ - "os_str_bytes", -] - [[package]] name = "clap_lex" version = "0.5.0" @@ -330,19 +298,19 @@ checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" [[package]] name = "criterion" -version = "0.4.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7c76e09c1aae2bc52b3d2f29e13c6572553b30c4aa1b8a49fd70de6412654cb" +checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f" dependencies = [ "anes", - "atty", "cast", "ciborium", - "clap 3.2.25", + "clap", "criterion-plot", + "is-terminal", "itertools", - "lazy_static", "num-traits", + "once_cell", "oorandom", "plotters", "rayon", @@ -548,15 +516,6 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" -[[package]] -name = "hermit-abi" -version = "0.1.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" -dependencies = [ - "libc", -] - [[package]] name = "hermit-abi" version = "0.2.6" @@ -673,12 +632,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" - [[package]] name = "libc" version = "0.2.144" @@ -744,7 +697,7 @@ dependencies = [ "supports-hyperlinks", "supports-unicode", "terminal_size", - "textwrap 0.15.2", + "textwrap", "thiserror", "unicode-width", ] @@ -871,7 +824,7 @@ name = "nufmt" version = "0.1.0" dependencies = [ "anyhow", - "clap 4.3.0", + "clap", "criterion", "env_logger", "log", @@ -926,12 +879,6 @@ version = "11.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" -[[package]] -name = "os_str_bytes" -version = "6.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ceedf44fb00f2d1984b0bc98102627ce622e083e49a5bacdb3e514fa4238e267" - [[package]] name = "owo-colors" version = "3.5.0" @@ -1270,12 +1217,6 @@ dependencies = [ "unicode-width", ] -[[package]] -name = "textwrap" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "222a222a5bfe1bba4a77b45ec488a741b3cb8872e5e499451fd7d0129c9c7c3d" - [[package]] name = "thiserror" version = "1.0.40" diff --git a/Cargo.toml b/Cargo.toml index 7a53bd7..a8bb777 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,7 +22,7 @@ nu-parser = "0.80.0" nu-protocol = "0.80.0" [dev-dependencies] -criterion = "0.4" +criterion = "0.5.1" [features] default = ["bin"] @@ -38,5 +38,5 @@ path = "src/main.rs" required-features = ["bin"] [[bench]] -name = "bench" +name = "file-format-bench" harness = false diff --git a/README.md b/README.md index 6a83013..7a96493 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,77 @@ -# Nushell script formatter +
-## some example formatting -[`g.nu`](examples/g.nu) should get formatted into [`gradient.nu`](examples/gradient.nu) +# `nufmt`: the nushell formatter -> **Warning** -> these scripts are very much deprecated, see the `0.31.1` version of `nushell`!! -> we're now in `0.74` on latest `main` :muscle: +[![MIT licensed][mit-badge]][mit-url] +[![Discord chat][discord-badge]][discord-url] +[![CI on main][ci-badge]][ci-url] +[![nushell version][nushell-badge]][nushell-url] -> **Note** -> true ideal examples *COMING SOON* :wink: +[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg?color=brightgreen +[mit-url]: LICENSE +[discord-badge]: https://img.shields.io/discord/678763474494423051?logo=discord&label=discord&color=brightgreen +[discord-url]: https://discord.gg/NtAbbGn +[ci-badge]: https://github.com/AucaCoyan/nufmt/actions/workflows/main.yml/badge.svg +[ci-url]: https://github.com/AucaCoyan/nufmt/actions/workflows/main.yml +[nushell-badge]: https://img.shields.io/badge/nushell-v0.80.0-green +[nushell-url]: https://crates.io/crates/nu + +
+ +## Table of contents + +- [Status](#status) +- [Usage](#usage) + - [Files](#files) + - [Options](#options) +- [Contributing](#contributing) + +## Status + +This project is still very much in beta. Expect bugs, unconsistent behaviour. Do not use in productive nushell scripts! + +Some of the outputs deletes comments, break the functionality of the script or doesn't format at all. + +To use the formatter, test it first and use it with caution!. + +## Usage + +If you still want to use it, or test it to contribute, this is the `--help`. + +```text +nufmt [OPTIONS] [FILES] ... +``` + +### Files + +`Files` are a list of files. It cannot be used combined with `--stdin`. +You can format many files with one command!. For example: + +```text +nufmt my-file1.nu my-file2.nu my-file3.nu +``` + +### Options + +- `-s` or `--stdin` formats from `stdin`, returns to `stdout` as a String. It cannot be used combined with `files`. +- `-c` or `--config` pass the config file path. + Sample: + + ```text + nufmt --config my-config.json + ``` + + or + + ```text + nufmt --stdin --config my-stdin-config.json + ``` + +- `-h` or `--help` show help and exit +- `-v` or `--version` prints the version and exit + +## Contributing + +Submit an issue, or come and say hi in the [Discord](https://discord.gg/NtAbbGn)! + +You can mention @AucaCoyan who is active on this repo. diff --git a/benches/bench.rs b/benches/bench.rs deleted file mode 100644 index ad0e79c..0000000 --- a/benches/bench.rs +++ /dev/null @@ -1,17 +0,0 @@ -use criterion::{criterion_group, criterion_main, Criterion}; -use nufmt::{format_nu, Indentation}; -use std::{fs, io}; - -/// You need a nu file called massive.nu in your project root -fn format_massive_nu(file: &str) -> io::Result { - Ok(format_nu(&file, Indentation::Default)) -} - -fn criterion_benchmark(c: &mut Criterion) { - let file = fs::read_to_string("massive.nu").expect("massive.nu file in project directory"); - - c.bench_function("Format massive nu", |b| b.iter(|| format_massive_nu(&file))); -} - -criterion_group!(benches, criterion_benchmark); -criterion_main!(benches); diff --git a/examples/example.nu b/benches/example.nu similarity index 100% rename from examples/example.nu rename to benches/example.nu diff --git a/benches/file-format-bench.rs b/benches/file-format-bench.rs new file mode 100644 index 0000000..e4c296d --- /dev/null +++ b/benches/file-format-bench.rs @@ -0,0 +1,15 @@ +use criterion::{criterion_group, criterion_main, Criterion}; +use nufmt::{config::Config, format_single_file}; +use std::{io, path::PathBuf}; + +fn format_massive_nu(file: &PathBuf) -> io::Result<()> { + Ok(format_single_file(file, &Config::default())) +} + +fn criterion_benchmark(c: &mut Criterion) { + let file = PathBuf::from("./benches/example.nu"); + c.bench_function("Format massive nu", |b| b.iter(|| format_massive_nu(&file))); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/examples/24bit-1.nu b/examples/24bit-1.nu deleted file mode 100644 index 75b06f0..0000000 --- a/examples/24bit-1.nu +++ /dev/null @@ -1,37 +0,0 @@ -export def draw [] { - let term_cols = ((term size).columns - 1) - - # let's itertate through each of the columns of our terminal - 0..$term_cols | each { |col| - let r = (255 - ($col * 255 / $term_cols) | math round) - let g = ($col * 510 / $term_cols | math round) - let b = ($col * 255 / $term_cols | math round) - if $g > 255 { - let g = (510 - $g) - build-colorstr $r $g $b $col - } else { - build-colorstr $r $g $b $col - } - } | str collect -} - -def build-colorstr [ - r:int # Red - g:int # Green - b:int # Blue - c:int # Column -] { - # Heavy use of string interpolation below - let bg = $"(ansi rgb_bg)($r);($g);($b)m" - let fg = $"(ansi rgb_fg)(255 - $r);(255 - $g);(255 - $b)m" - let idx = ($c mod 2) - let slash_str = (if $idx == 0 { - $'/(ansi reset)' - } else { - $'\(ansi reset)' - }) - $"($bg)($fg)($slash_str)" - # sleep 10ms | ignore -} - -print (draw) \ No newline at end of file diff --git a/examples/256_color_testpattern.nu b/examples/256_color_testpattern.nu deleted file mode 100644 index 3e484b6..0000000 --- a/examples/256_color_testpattern.nu +++ /dev/null @@ -1,69 +0,0 @@ -def contrast_colour [ colour:int ] { - # The first 16 colors - if $colour < 16 { - if $colour == 0 { - 15 - } else { - 0 - } - } else { - # The gray colors - if $colour > 231 { - if $colour < 244 { - 15 - } else { - 0 - } - } else { - # The rest - let r = ($colour - 16) / 36 - let g = (($colour - 16) mod 36) / 6 - let b = ($colour - 16) mod 6 - - let luminance = ($r * 299) + ($g * 587) + ($b * 114) - if $luminance > 2500 { - 0 - } else { - 15 - } - } - } -} - -def print_colour [ colour:int ] { - let contrast = (contrast_colour $colour) - let bg_color = $"(ansi idx_bg)($colour)m" # Start block of colour - let fg_color = $"(ansi idx_fg)($contrast)m" # In contrast, print number - let text = $"($colour | into string | fill -c ' ' -w 3 -a r)(ansi reset)" - $bg_color + $fg_color + $text + " " -} - -let printable_colours = 256 - -def print_run [start:int, amount:int] { - $start..<($start + $amount) | each { |i| - if $i < $printable_colours { - print_colour $i - } else { - "" - } - } | append " " | str collect -} - -def print_blocks [start:int, end:int, block_cols:int, block_rows:int, blocks_per_line:int] { - let block_length = ($block_cols * $block_rows) - let end = (($end - $start) / (($blocks_per_line) * $block_length)) - 0..<$end | each { |i| - 0..<$block_rows | each { |row| - 0..<$blocks_per_line | each { |block| - print_run ($start + $block * $block_length + $row * $block_cols + $i * $block_length * $blocks_per_line) $block_cols - } | append (char nl) | str collect - } | str collect - } | str collect -} - -print (print_run 0 16) # The first 16 colours are spread over the whole spectrum -print "" # Single line -print (print_blocks 16 123 6 6 3) # 6x6x6 colour cube between 16 and 123 inclusive -print (print_blocks 124 231 6 6 3) # 6x6x6 colour cube between 124 and 231 inclusive -print (print_blocks 232 255 12 2 1) # Not 50, but 24 Shades of Grey \ No newline at end of file diff --git a/examples/gradient.nu b/examples/gradient.nu deleted file mode 100644 index babdbee..0000000 --- a/examples/gradient.nu +++ /dev/null @@ -1,41 +0,0 @@ -# this script will print a blue gradient on the screen - -# We can get the terminal width and height now with term size -# but we like to use the script as a benchmark, so let's keep -# it a constant size for now -let height = 40 # really need to get the terminal height here -let width = 160 # really need to get the terminal width here -let stamp = 'Nu' -seq 0 $height | each { |row| - let row_data = (seq 0 $width | each { |col| - let fgcolor = (iter_inc 2 2 $col) - if $fgcolor > 200 and $fgcolor < 210 { - $"(ansi -e '48;2;0;0;')($fgcolor)m($stamp)(ansi -e '0m')" - } else { - $"(ansi -e '48;2;0;0;')($fgcolor)m(char sp)(ansi -e '0m')" - } - } | str collect) - print -n $"($row_data)(char newline)" -} | str collect - -def iter_inc [incr mult iter] { - $incr + $mult * $iter -} - - -# ╭────────────────────┬──────────────────────────────────────────────────────╮ -# │ version │ 0.1.0 │ -# │ branch │ main │ -# │ short_commit │ ec94ca46 │ -# │ commit_hash │ ec94ca46bb64f3aa95f1366d76d60da2ddc53782 │ -# │ commit_date │ 2022-01-24 19:45:20 +00:00 │ -# │ build_os │ windows-x86_64 │ -# │ rust_version │ rustc 1.58.1 (db9d1b20b 2022-01-20) │ -# │ rust_channel │ stable-x86_64-pc-windows-msvc │ -# │ cargo_version │ cargo 1.58.0 (f01b232bc 2022-01-19) │ -# │ pkg_version │ 0.1.0 │ -# │ build_time │ 2022-01-24 15:04:00 -06:00 │ -# │ build_rust_channel │ debug │ -# │ features │ dataframe, default, which, zip │ -# │ installed_plugins │ gstat, inc, nu-example-1, nu-example-2, nu-example-3 │ -# ╰────────────────────┴──────────────────────────────────────────────────────╯ diff --git a/examples/turtle.nu b/examples/turtle.nu deleted file mode 100644 index 8b812d3..0000000 --- a/examples/turtle.nu +++ /dev/null @@ -1,10 +0,0 @@ -# The infamous turtle benchmark -def turtle [column: string] { - wrap $column | table -} - -print $"Turtle 1 = ('turtle' | turtle 1 | str length)" -print $"Turtle 2 = ('turtle' | turtle 1 | turtle 2 | str length)" -print $"Turtle 3 = ('turtle' | turtle 1 | turtle 2 | turtle 3 | str length)" -print $"Turtle 4 = ('turtle' | turtle 1 | turtle 2 | turtle 3 | turtle 4 | str length)" -print $"Turtle 5 = ('turtle' | turtle 1 | turtle 2 | turtle 3 | turtle 4 | turtle 5 | str length)" \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index 25baaaa..54a95ad 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,9 +6,8 @@ use config::Config; use formatting::format_inner; use log::{debug, trace}; -use std::error::Error; use std::fs::File; -use std::io::{BufReader, BufWriter, Read, Write}; +use std::io::Write; use std::path::PathBuf; pub mod config; @@ -44,171 +43,6 @@ pub fn format_string(input_string: &String, config: &Config) -> String { String::from_utf8(formatted_bytes).unwrap() } -/// -/// Set the indentation used for the formatting. -/// -/// Note: It is *not* recommended to set indentation to anything oder than some spaces or some tabs, -/// but nothing is stopping you from doing that. -#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] -pub enum Indentation<'a> { - /// Use the default indentation, which is two spaces - Default, - /// Use a custom indentation String - Custom(&'a str), -} - -/// -/// # Formats a nu string -/// -/// The indentation can be set to any value using [`Indentation`]. The default value is two spaces. The default indentation is faster than a custom one -/// -pub fn format_nu(nu: &str, indentation: Indentation) -> String { - let mut reader = BufReader::new(nu.as_bytes()); - let mut writer = BufWriter::new(Vec::new()); - - format_nu_buffered(&mut reader, &mut writer, indentation).unwrap(); - String::from_utf8(writer.into_inner().unwrap()).unwrap() -} - -/// -/// # Formats a nu string -/// -/// The indentation can be set to any value using [`Indentation`]. The default value is two spaces. The default indentation is faster than a custom one -/// -pub fn format_nu_buffered( - reader: &mut BufReader, - writer: &mut BufWriter, - indentation: Indentation, -) -> Result<(), Box> -where - R: Read, - W: Write, -{ - let mut escaped = false; - let mut in_string = false; - let mut indent_level: usize = 0; - let mut newline_requested = false; // invalidated if next character is ] or } - let mut in_comment = false; - - for char in reader.bytes() { - let char = char?; - // if we're in a comment, ignore and write everything until a newline - if in_comment { - trace!("this character is a comment"); - match char { - b'\n' => { - in_comment = false; - writer.write_all(&[char])?; - } - _ => { - // TODO: read the rest of the line - // write all - // and go to the next line - writer.write_all(&[char])?; - continue; - } - } - } - if in_string { - trace!("this is inside a string"); - let mut escape_here = false; - match char { - b'"' => { - if !escaped { - in_string = false; - } - } - b'\\' => { - if !escaped { - escape_here = true; - } - } - _ => {} - } - writer.write_all(&[char])?; - escaped = escape_here; - } else { - let mut auto_push = true; - let mut request_newline = false; - // let old_level = indent_level; - - match char { - b'#' => in_comment = true, - b'"' => in_string = true, - // b' ' | b'\n' | b'\t' => continue, - b'\n' => continue, - b'[' | b'{' => { - indent_level += 1; - request_newline = true; - } - b']' | b'}' => { - indent_level = indent_level.saturating_sub(1); - if !newline_requested && request_newline { - // see comment below about newline_requested - // writer.write_all(&[b'\n'])?; - indent_buffered(writer, indent_level, indentation)?; - } - } - b':' => { - auto_push = false; - writer.write_all(&[char])?; - writer.write_all(&[b' '])?; - } - b',' => { - request_newline = true; - } - _ => {} - } - - if newline_requested && request_newline { - trace!("new line requested!"); - writer.write_all(&[b'\n'])?; - indent_buffered(writer, indent_level, indentation)?; - } - // if newline_requested && char != b']' && char != b'}' { - // // newline only happens after { [ and , - // // this means we can safely assume that it being followed up by } or ] - // // means an empty object/array - // writer.write_all(&[b'\n'])?; - // indent_buffered(writer, old_level, indentation)?; - // } - - if auto_push { - //trace!("this char is autopushed"); - writer.write_all(&[char])?; - } - - newline_requested = request_newline; - } - // trace the char for guiding - trace!("{:?}", char as char); - } - - Ok(()) -} - -fn indent_buffered( - writer: &mut BufWriter, - level: usize, - indent_str: Indentation, -) -> Result<(), Box> -where - W: std::io::Write, -{ - for _ in 0..level { - match indent_str { - Indentation::Default => { - writer.write_all(b" ")?; - } - Indentation::Custom(indent) => { - writer.write_all(indent.as_bytes())?; - } - } - } - - Ok(()) -} - #[cfg(test)] mod test { use super::*; @@ -232,34 +66,38 @@ mod test { #[test] fn echoes_primitive() { - let nu = "1.35"; - assert_eq!(nu, format_nu(nu, Indentation::Default)); + let nu = String::from("1.35\n"); + assert_eq!(nu, format_string(&nu, &Config::default())); } #[test] fn handle_escaped_strings() { - let nu = " \" hallo \\\" \" "; - let expected = "\" hallo \\\" \""; - assert_eq!(expected, format_nu(nu, Indentation::Default)); + let nu = String::from(" \" hallo \\\" \" \n"); + let expected = String::from("\" hallo \\\" \"\n"); + assert_eq!(expected, format_string(&nu, &Config::default())); } + // comments aren't a part of Spans, + // we need another way of reading a skipping comments + // otherwise the nufmt directly remove them. #[test] + #[ignore] fn ignore_comments() { - let nu = "# this is a comment"; - let expected = "# this is a comment"; - assert_eq!(expected, format_nu(nu, Indentation::Default)); + let nu = String::from("# this is a comment"); + let expected = String::from("# this is a comment"); + assert_eq!(expected, format_string(&nu, &Config::default())); } #[test] fn ignore_whitespace_in_string() { - let nu = "\" hallo \""; - assert_eq!(nu, format_nu(nu, Indentation::Default)); + let nu = String::from("\" hallo \"\n"); + assert_eq!(nu, format_string(&nu, &Config::default())); } #[test] fn remove_leading_whitespace() { - let nu = " 0"; - let expected = "0"; - assert_eq!(expected, format_nu(nu, Indentation::Default)); + let nu = String::from(" 0"); + let expected = String::from("0\n"); + assert_eq!(expected, format_string(&nu, &Config::default())); } } diff --git a/src/main.rs b/src/main.rs index b69eda7..89a5970 100644 --- a/src/main.rs +++ b/src/main.rs @@ -152,9 +152,4 @@ mod tests { use clap::CommandFactory; Cli::command().debug_assert() } - - #[test] - fn todo() { - todo!("First fix the library fixes, then we can do the binary tests.") - } }