Suggested improvements for `dataurl`
macOS and Linux distros have base64 preinstalled, why not use it directly?
IIRC macOS didn't have base64 preinstalled when this was written.
Why stop at base64? This can be done using only POSIX utilities!
# Create a data URL from a file
dataurl() {
# https://github.com/mathiasbynens/dotfiles/commit/5d76fc286f
# POSIX does not define `-b`/`--brief` or `--mime-type`
mimeType="$(LC_ALL='C' file -b --mime-type -- "${1-}")"
if printf -- '%s\n' "${mimeType-}" | grep -q -e '^text/'; then
mimeType="${mimeType-}"';charset=utf-8'
fi
# `uuencode` – part of POSIX since the 1900s – instead of `openssl` or `base64`
uuencode -m -- "${1-}" /dev/stdout |
# remove the first line, then the last line, then remove all newlines
sed -e '1d' -e '$d' - |
sed -e ':a' -e 'N' -e '$! b a' -e 's/\n//g' - |
awk -v mimeType="${mimeType-}" -- '{printf "data:%s;base64,%s\n", mimeType, $0}' -
# `unset` instead of non-standard `local`, but send its errors to `/dev/null` just in case
unset -v -- mimeType 2>/dev/null
}
IIRC macOS didn't have
base64preinstalled when this was written.
Thanks for explaining. I know little about macOS history
Why stop at base64? This can be done using only POSIX utilities! [...]
I like how you used -- to escape args, just-in-case a filename starts with "-". We should probably merge that change (--) into main
BTW, I tried using uuencode in my system, and it wasn't even installed, lol
BTW, speaking of special chars, I just noticed that both openssl base64 and base64, are not URL-safe. This completely defeats the purpose of dataurl.
@mathiasbynens Should I rename this issue to "dataurl suggestions", or should I open a new issue about this?
I'm willing to open a PR for this, but I don't know which commands are more appropriate. I'll do some research
@Rudxain What do you mean with URL-safe?
What do you mean with URL-safe?
I haven't tested the output of dataurl on a browser (neither address bar, nor HTML files), but I assume it can sometimes (depends on input data) cause issues because of the "/" chars
AFAIK, most base64 implementations on Unix-like OSes aren't concerned with being URL-safe, so most systems are susceptible to this problem
According to this SO answer, basenc --base64url is the best alternative (if we aren't concerned with retro-compatibility)
There were other answers that don't require basenc, but instead require cut, tr, awk, sed, etc... (some have more dependencies than others)
I just read Wikipedia: data URI scheme allows standard B64 (not "URL-safe"). I'm so confused lol. I'm sorry for the false alarm