#!/bin/env bash

# This tool generates the tests in spec/std/file/match-fast-glob_spec.cr
# from https://github.com/oxc-project/fast-glob/blob/main/tests/test.rs
# converted to Crystal

set -euo pipefail

target=spec/std/file/match-fast-glob_spec.cr
URL="https://raw.githubusercontent.com/oxc-project/fast-glob/refs/heads/main/tests/test.rs"

curl -L "$URL" |
  (
    echo '
# This file was automatically generated by running:
#
#   scripts/generate_glob_specs.cr
#
# DO NOT EDIT
'

    echo "
# These tests are autogenerated from $URL
# They are are  collection of tests from bash and micromatch
# https://github.com/micromatch/picomatch/blob/master/test/bash.js.
"

    echo '
require "spec"

private def assert_file_matches(pattern, path : String, *, file = __FILE__, line = __LINE__)
  File.match?(pattern, path).should be_true, file: file, line: line
  File.match?(pattern, Path.posix(path)).should be_true, file: file, line: line
  File.match?(pattern, Path.posix(path).to_windows(mappings: false)).should be_true, file: file, line: line
end

private def refute_file_matches(pattern, path : String, *, file = __FILE__, line = __LINE__)
  File.match?(pattern, path).should be_false, file: file, line: line
  File.match?(pattern, Path.posix(path)).should be_false, file: file, line: line
  File.match?(pattern, Path.posix(path).to_windows(mappings: false)).should be_false, file: file, line: line
end
'

    echo 'describe "File .match? bash tests" do'

    sed -E '1,5d' |
      sed '/let patterns/,/#\[test\]/d; s/fn not_paired_braces/end\n\nfn not_paired_braces/' | # drop complex patterns implementation
      sed '/fn fuzz_tests/,$d' |                                                               # drop complex fuzz tests implementation
      sed '/^\s*#\[/d' |
      sed -E 's/fn (.*)\(\) \{/it "\1" do/' |
      sed -E 's/\}$/end/' |
      sed -E 's|^\s*//|#|' |
      sed -E 's/assert!\(!glob_match\("(.*)", "(.*)"\)\);/refute_file_matches "\1", "\2"/' |
      sed -E 's/assert!\(glob_match\("(.*)", "(.*)"\)\);/assert_file_matches "\1", "\2"/' |
      # multiline assertions:
      sed -E 's/assert!\(glob_match\(/assert_file_matches(/' |
      sed -E 's/assert!\(!glob_match\(/refute_file_matches(/' |
      sed -E 's/\)\);/)/' |
      sed -E 's/let //' |
      sed -E 's/it "negation"/pending "negation"/' | # File.match? currently does not support negated patterns
      sed -E '/it "generic_input"/,/end$/d'          # Generic input tests are specific to Rust types

    echo 'end'
  ) >"$target"

crystal tool format "$target"
