# bash # # Copyright (c) 2022 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # : ${_GLOB_UTILS_TEST:=0} : ${_GLOB_UTILS_LOW_NOISE:=1} # # Convert a glob pattern to a basic (grep/sed) regex. # # This function doesn't treat "/" and "." specially. # glob_to_basic_regex() { # disable "set -x" to reduce noise in jenkins jobs if ( [[ "$_GLOB_UTILS_LOW_NOISE" == 1 ]] && \ shopt -po xtrace | grep -q -- -o >/dev/null ) 2>/dev/null then : "$FUNCNAME: disabling debug trace" set +x local restore_xtrace=1 else local restore_xtrace=0 fi local len="${#1}" local i c c2 local range_start range_len local neg_char local res for ((i=0; i "." if [[ "$c" == '?' ]] ; then res+='.' continue fi # "*" => ".*" if [[ "$c" == '*' ]] ; then res+='.*' continue fi # anything else: append as is res+="$c" done echo "^${res}\$" if [[ "$restore_xtrace" == 1 ]] ; then set -x # debug output of this "set" is suppressed set -x # execute it again, this time with "-x" already on : "$FUNCNAME: restored debug trace" fi } # unit tests if [[ "$_GLOB_UTILS_TEST" == 1 ]] ; then expect() { local glob="$1" local expected="$2" local actual actual="$(glob_to_basic_regex "$1")" if [[ "$actual" != "$expected" ]] ; then echo "${BASH_SOURCE}:${BASH_LINENO}: glob_to_basic_regex '$glob': expected '$expected' actual '$actual'" >&2 exit 1 fi } expect 'a[0-9]b' '^a[0-9]b$' expect 'a[!0-9]b' '^a[^0-9]b$' expect 'a?b' '^a.b$' expect 'a*b' '^a.*b$' expect 'a\*b' '^a[*]b$' expect 'a^b$c' '^a\^b[$]c$' expect '/foo/*' '^[/]foo[/].*$' expect 'a.b' '^a[.]b$' expect 'a\[b' '^a[[]b$' expect 'a[a-z]b[!A-Z]c[!0-9[]d!^' '^a[a-z]b[^A-Z]c[^0-9[]d[!]\^$' expect 'abc\' '^abc[\]$' expect 'a\b' '^a[b]$' fi