functions/__fish_print_hostnames: Don't run getent hosts twice

`getent hosts` is expensive-ish - ~50ms, so we don't want to run it
twice just to figure out it works.

Apparently this works everywhere but CYGWIN and possibly older
OpenBSD, but we don't want to explicitly blacklist those.

[ci skip]
This commit is contained in:
Fabian Homborg
2019-06-24 19:12:20 +02:00
parent 27e4d1d62d
commit 8f7a47547e

View File

@@ -1,13 +1,14 @@
function __fish_print_hostnames -d "Print a list of known hostnames"
# Print all hosts from /etc/hosts. Use 'getent hosts' on OSes that support it
# (OpenBSD and Cygwin do not).
# (apparently just Cygwin does not).
#
# Test if 'getent hosts' works and redirect output so errors don't print.
if type -q getent
and getent hosts >/dev/null 2>&1
# Ignore zero IPs.
getent hosts | string match -r -v '^0.0.0.0' | string replace -r '^\s*\S+\s+' '' | string split ' '
else if test -r /etc/hosts
#
# This is all done under the assumption that `getent` *might* print more hosts than the static /etc/hosts.
type -q getent
# Ignore zero IPs.
and getent hosts 2>/dev/null | string match -r -v '^0.0.0.0' | string replace -r '^\s*\S+\s+' '' | string split ' '
or if test -r /etc/hosts
# Ignore commented lines and functionally empty lines.
string match -r -v '^\s*0.0.0.0|^\s*#|^\s*$' </etc/hosts | string replace -r -a '#.*$' '' | string replace -r '^\s*\S+\s+' '' | string trim | string replace -r -a '\s+' ' ' | string split ' '
end