Created
March 4, 2018 14:51
-
-
Save u8sand/7f84e9547d74ff39de128a56a2618ec3 to your computer and use it in GitHub Desktop.
Perl-based uri parser for bash scripts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env sh | |
| # Parse a normal uri--e.g. http://user:pass@host:1234 into a custom perl-based substitution format. | |
| # e.g. parse_uri "http://localhost:80" '$+{port}' ==> 80 | |
| function parse_uri() { | |
| URI=$1 | |
| FMT=$2 | |
| echo ${URI} | perl -pe "s#(?<proto>[\w\+-]+)://((?<user>[-\w]+):(?<pass>[-\w]+)@)?((?<host>[-\w]+)(:(?<port>\d+))?)#${FMT}#g" | |
| } | |
| function test_eq() { | |
| let TEST="${TEST}+1" | |
| if [ "$1" == "$2" ]; then | |
| let PASS="${PASS}+1" | |
| echo -n "." | |
| else | |
| echo "" | |
| echo "Failure. Test ${PASS}: $1 != $2" | |
| fi | |
| } | |
| function test_parse_uri() { | |
| export PASS=0 | |
| export TEST=0 | |
| test_eq $(parse_uri "http://localhost" '$+{proto}') "http" | |
| test_eq $(parse_uri "https://localhost" '$+{host}') "localhost" | |
| test_eq $(parse_uri "tcp://localhost:80" '$+{port}') 80 | |
| test_eq $(parse_uri "ssh://root:toor@localhost" '$+{user}') "root" | |
| test_eq $(parse_uri "git://root:toor@localhost:80" '$+{pass}') "toor" | |
| test_eq $(parse_uri "git+ssh://my-user:my-pass@my-host:8080" '$+{proto};$+{user};$+{pass};$+{host};$+{port}') "git+ssh;my-user;my-pass;my-host;8080" | |
| let SUCCESS_RATE="100*${PASS}/${TEST}" | |
| echo "" | |
| echo "${SUCCESS_RATE}% Success" | |
| } | |
| test_parse_uri |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment