sx-open/sx-open

63 lines
1.2 KiB
Plaintext
Raw Normal View History

2014-09-25 13:26:15 +00:00
#!/usr/bin/env bash
# This is an attempt to replace xdg-open with something sane.
declare -A uri_handlers
declare -A mime_handlers
2014-09-25 13:26:15 +00:00
# Source the config file.
cfg_file="$HOME/.config/sx-open.cfg"
cfg_uri_regex='^[A-Za-z]([A-Za-z0-9+.-]+)?://.+'
2014-09-25 13:26:15 +00:00
[[ -f "$cfg_file" ]] && { source "$cfg_file"; }
2014-11-08 05:03:59 +00:00
usage() { echo "${0##*/} <uri/file>"; }
2014-09-25 13:26:15 +00:00
handle_uri() {
2014-09-25 15:05:17 +00:00
local target="$1"
2014-09-25 13:26:15 +00:00
for h in "${!uri_handlers[@]}"; do
2014-10-16 09:46:57 +00:00
[[ "$target" =~ ${uri_handlers[${h}]} ]] && {
2014-09-25 15:05:17 +00:00
${h} "$target" &
return 0
2014-09-25 13:26:15 +00:00
}
done
2014-09-25 15:05:17 +00:00
return 1
2014-09-25 13:26:15 +00:00
}
handle_mime() {
2014-09-25 13:26:15 +00:00
target_mimetype=$(file -ib "$target")
for m in "${!mime_handlers[@]}"; do
2014-10-16 09:46:57 +00:00
[[ "$target_mimetype" =~ ${mime_handlers[${m}]} ]] && {
2014-09-25 15:05:17 +00:00
${m} "$target" &
return 0
2014-09-25 13:26:15 +00:00
}
done
2014-09-25 15:05:17 +00:00
return 1
2014-09-25 13:26:15 +00:00
}
main() {
target="$1"
[[ "$target" ]] || { usage; exit; }
if [[ "$target" =~ ${cfg_uri_regex} ]]; then
handle_uri "$target"
elif [[ -e "$target" ]]; then
[[ "$target" =~ ^/.* ]] || { target="${PWD}/${target}"; }
handle_uri "file://${target}" || {
handle_mime "$target"
}
else
echo "$target is not a uri nor is it an existing file. Bailing."
return 1
fi
2014-09-25 18:16:11 +00:00
[[ "$?" -gt 0 ]] && { echo "No handlers found for $target"; }
return 0
2014-09-25 13:26:15 +00:00
}
main "$@"