commit:     4cdb3c0869a9e6353fee69a7d61123ba8be01c06
Author:     Kerin Millar <kfm <AT> plushkava <DOT> net>
AuthorDate: Mon Jun 24 21:34:37 2024 +0000
Commit:     Sam James <sam <AT> gentoo <DOT> org>
CommitDate: Tue Jun 25 01:17:08 2024 +0000
URL:        
https://gitweb.gentoo.org/proj/gentoo-functions.git/commit/?id=4cdb3c08

Add the fetch() function

This function makes it trivial to issue a network request - such as HTTP
GET - in a manner that is quiet and which yields a useful exit status
value. It prefers curl if present but supports wget also.

Signed-off-by: Kerin Millar <kfm <AT> plushkava.net>

 functions.sh | 42 ++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 42 insertions(+)

diff --git a/functions.sh b/functions.sh
index 7e09611..9336174 100644
--- a/functions.sh
+++ b/functions.sh
@@ -47,6 +47,48 @@ chdir()
        CDPATH= cd -- "$@"
 }
 
+#
+# Considers the first parameter as an URL then attempts to fetch it with either
+# curl(1) or wget(1). If the URL does not contain a scheme then the https://
+# scheme shall be presumed. Both utilities shall be invoked in a manner that
+# suppresses all output unless an error occurs, and whereby HTTP redirections
+# are honoured. Upon success, the body of the response shall be printed to the
+# standard output. Otherwise, the return value shall be greater than 0.
+#
+fetch()
+{
+       if hash curl 2>/dev/null; then
+               fetch()
+               {
+                       if [ "$#" -gt 0 ]; then
+                               # Discard any extraneous parameters.
+                               set -- "$1"
+                       fi
+                       curl -f -sS -L --connect-timeout 10 --proto-default 
https -- "$@"
+               }
+       elif hash wget 2>/dev/null; then
+               fetch()
+               {
+                       if [ "$#" -gt 0 ]; then
+                               # Discard any extraneous parameters.
+                               case $1 in
+                                       ''|ftp://*|ftps://*|https://*)
+                                               set -- "$1"
+                                               ;;
+                                       *)
+                                               set -- "https://$1";
+                               esac
+                       fi
+                       wget -nv -O - --connect-timeout 10 -- "$@"
+               }
+       else
+               warn "fetch: this function requires that curl or wget to be 
installed"
+               return 127
+       fi
+
+       fetch "$@"
+}
+
 #
 # Determines whether the current shell is a subprocess of portage.
 #

Reply via email to