Files
profile/profile.d/lang.sh
2026-07-09 18:17:53 +02:00

226 lines
7.9 KiB
Bash

#!/usr/bin/env bash
# ------------------------------------------------------------------------------
# Copyright (c) 2013-2026 Geoffray Levasseur <fatalerrors@geoffray-levasseur.org>
# Protected by the BSD3 license. Please read bellow for details.
#
# * Redistribution and use in source and binary forms,
# * with or without modification, are permitted provided
# * that the following conditions are met:
# *
# * Redistributions of source code must retain the above
# * copyright notice, this list of conditions and the
# * following disclaimer.
# *
# * Redistributions in binary form must reproduce the above
# * copyright notice, this list of conditions and the following
# * disclaimer in the documentation and/or other materials
# * provided with the distribution.
# *
# * Neither the name of the copyright holder nor the names
# * of any other contributors may be used to endorse or
# * promote products derived from this software without
# * specific prior written permission.
# *
# * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
# * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
# * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# * OF SUCH DAMAGE.
# ------------------------------------------------------------------------------
load_conf lang
# ------------------------------------------------------------------------------
# check if a given locale is installed on the system.
# The comparison is tolerant to the various ways the codeset can be written
# across distributions (UTF-8, UTF8, utf8, utf-8, ISO-8859-1, iso88591, ...).
# On success the canonical name, exactly as the system spells it, is printed on
# stdout so callers can feed it verbatim to `export LANG=...` etc.
# Usage: canonical=$(locale_check <locale>) || handle-missing
locale_check()
{
local requested="$1"
[[ -z $requested ]] && { disp W "No locale given to check."; return 1; }
# Split "lang_TERRITORY[.codeset][@modifier]" into base, codeset, modifier.
local req_body="$requested" req_cs="" req_mod=""
[[ $req_body == *@* ]] && { req_mod="${req_body##*@}"; req_body="${req_body%@*}"; }
[[ $req_body == *.* ]] && { req_cs="${req_body##*.}"; req_body="${req_body%.*}"; }
# Normalise the codeset: lowercase then strip every non-alphanumeric char so
# that UTF-8, UTF8, utf8 and utf-8 all compare equal (likewise ISO variants).
local req_cs_norm="${req_cs,,}"
req_cs_norm="${req_cs_norm//[^a-z0-9]/}"
local cand body cs mod cs_norm
while IFS= read -r cand; do
[[ -z $cand ]] && continue
body="$cand"; cs=""; mod=""
[[ $body == *@* ]] && { mod="${body##*@}"; body="${body%@*}"; }
[[ $body == *.* ]] && { cs="${body##*.}"; body="${body%.*}"; }
cs_norm="${cs,,}"
cs_norm="${cs_norm//[^a-z0-9]/}"
# Base language and modifier must match exactly.
[[ $body == "$req_body" && $mod == "$req_mod" ]] || continue
# A requested codeset must match (normalised); if none was requested,
# accept any codeset the system provides.
[[ -z $req_cs_norm || $cs_norm == "$req_cs_norm" ]] || continue
printf '%s\n' "$cand"
return 0
done < <(locale -a 2>/dev/null)
disp W "Locale '$requested' is not installed on this system."
return 1
}
export -f locale_check
# ------------------------------------------------------------------------------
# Change locale to the given one in parameter
# Usage: setlocale <locale>
setlocale()
{
local PARSED
PARSED=$(getopt -o h --long help -n 'setlocale' -- "$@")
# shellcheck disable=SC2181 # getopt return code is checked immediately after
if [[ $? -ne 0 ]]; then
disp E "Invalid options, use \"setlocale --help\" to display usage."
return 1
fi
local -a _pargs=()
readarray -td '' _pargs < <(printf '%s' "$PARSED" | xargs printf '%s\0')
set -- "${_pargs[@]}"
while true; do
case "$1" in
-h|--help)
printf "setlocale: Configure system environment locale variables.\n\n"
printf "Usage: setlocale <locale>\n\n"
printf "Options:\n"
printf " -h, --help Display this help screen\n"
return 0
;;
--)
shift
break
;;
*)
disp E "Invalid options, use \"setlocale --help\" to display usage."
return 1
;;
esac
done
local loc=$1
[[ -z $loc ]] && disp E "No locale specified." && return 1
# Resolve to the exact spelling installed on this system, tolerant to the
# various codeset writings (UTF-8, UTF8, utf8, utf-8, ...).
loc=$(locale_check "$loc") || return 1
export LANG=$loc
export LC_MESSAGES=$loc
export LC_TIME=$loc
export LC_NUMERIC=$loc
export LC_MONETARY=$loc
export LC_COLLATE=$loc
export LC_CTYPE=$loc
disp I "Locale set to $loc."
}
export -f setlocale
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# Special case : change locale to C standard
# Usage: setc
setc()
{
# Locale definitions
export LC_ALL=C
export LANG=C
disp I "Locale changed to standard C (POSIX)."
}
export -f setc
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# Build dynamic locale shortcuts from SET_LOCALE
# Expected format:
# SET_LOCALE="fr:fr_FR.UTF-8,us:en_US.UTF-8,es:es_ES.UTF-8"
# This creates functions:
# setfr, setus, setes, ...
build_locale_shortcuts()
{
local cfg="${SET_LOCALE:-}"
local item="" alias="" loc="" fname=""
local -a locale_items=()
[[ -z "$cfg" ]] && return 0
IFS=',' read -r -a locale_items <<< "$cfg"
for item in "${locale_items[@]}"; do
# Trim surrounding spaces
item="${item#"${item%%[![:space:]]*}"}"
item="${item%"${item##*[![:space:]]}"}"
[[ -z "$item" ]] && continue
if [[ "$item" != *:* ]]; then
disp W "Ignoring invalid SET_LOCALE entry: '$item' (expected alias:locale)."
continue
fi
alias="${item%%:*}"
loc="${item#*:}"
# Trim alias/locale spaces
alias="${alias#"${alias%%[![:space:]]*}"}"
alias="${alias%"${alias##*[![:space:]]}"}"
loc="${loc#"${loc%%[![:space:]]*}"}"
loc="${loc%"${loc##*[![:space:]]}"}"
# Validate alias for safe function names
if [[ ! "$alias" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]]; then
disp W "Ignoring unsafe locale alias '$alias' in SET_LOCALE."
continue
fi
[[ -z "$loc" ]] && {
disp W "Ignoring empty locale for alias '$alias' in SET_LOCALE."
continue
}
fname="set${alias}"
# Optional collision warning
if declare -F "$fname" >/dev/null 2>&1; then
disp W "Overriding existing function '$fname'."
fi
# Build function dynamically
# shellcheck disable=SC2016
eval "${fname}() { setlocale \"$loc\"; }"
# shellcheck disable=SC2163
export -f "$fname"
done
unset cfg item alias loc fname locale_items
}
# ------------------------------------------------------------------------------
# Dynamically build locale functions based on SET_LOCALE configuration
build_locale_shortcuts
# ------------------------------------------------------------------------------
# EOF