lure/internal/config/lang.go

68 lines
1.7 KiB
Go
Raw Normal View History

/*
* LURE - Linux User REpository
2023-09-20 22:38:22 +00:00
* Copyright (C) 2023 Elara Musayelyan
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
2023-01-13 03:41:52 +00:00
package config
import (
2023-10-06 21:21:12 +00:00
"context"
2023-01-13 03:41:52 +00:00
"os"
"strings"
2023-10-06 22:07:19 +00:00
"sync"
2023-01-13 03:41:52 +00:00
2023-10-08 00:34:39 +00:00
"lure.sh/lure/pkg/loggerctx"
2023-01-13 03:41:52 +00:00
"golang.org/x/text/language"
)
2023-09-19 21:28:05 +00:00
var (
2023-10-06 22:07:19 +00:00
langMtx sync.Mutex
2023-09-19 21:28:05 +00:00
lang language.Tag
langSet bool
)
2023-01-13 03:41:52 +00:00
2023-09-21 23:18:18 +00:00
// Language returns the system language.
// The first time it's called, it'll detect the langauge based on
// the $LANG environment variable.
// Subsequent calls will just return the same value.
2023-10-06 21:21:12 +00:00
func Language(ctx context.Context) language.Tag {
2023-10-06 22:07:19 +00:00
langMtx.Lock()
defer langMtx.Unlock()
2023-10-06 21:21:12 +00:00
log := loggerctx.From(ctx)
2023-09-19 21:28:05 +00:00
if !langSet {
syslang := SystemLang()
tag, err := language.Parse(syslang)
if err != nil {
log.Fatal("Error parsing system language").Err(err).Send()
}
base, _ := tag.Base()
lang = language.Make(base.String())
langSet = true
2023-01-13 03:41:52 +00:00
}
2023-09-19 21:28:05 +00:00
return lang
2023-01-13 03:41:52 +00:00
}
2023-09-21 23:18:18 +00:00
// SystemLang returns the system language based on
// the $LANG environment variable.
2023-01-13 03:41:52 +00:00
func SystemLang() string {
lang := os.Getenv("LANG")
lang, _, _ = strings.Cut(lang, ".")
if lang == "" || lang == "C" {
2023-01-13 03:41:52 +00:00
lang = "en"
}
return lang
}