Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ac196e720b |
@@ -2,6 +2,10 @@ package system
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"regexp"
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -42,6 +46,16 @@ type SetKeymapInput struct {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type GenerateLocaleInput struct {
|
||||||
|
Body struct {
|
||||||
|
Locale string `json:"locale" example:"fr_FR.UTF-8" doc:"Locale to generate (e.g. fr_FR.UTF-8)"`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// localeRe validates a locale identifier: language_TERRITORY with an optional
|
||||||
|
// .charmap suffix (e.g. fr_FR, fr_FR.UTF-8, en_US.ISO-8859-1).
|
||||||
|
var localeRe = regexp.MustCompile(`^[a-z]{2,3}_[A-Z]{2}(\.[A-Za-z0-9_-]+)?$`)
|
||||||
|
|
||||||
func localeStatus() (LocaleStatusBody, error) {
|
func localeStatus() (LocaleStatusBody, error) {
|
||||||
lines, err := oscmd.RunLines("localectl", "status")
|
lines, err := oscmd.RunLines("localectl", "status")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -183,4 +197,117 @@ func registerLocale(api huma.API) {
|
|||||||
}
|
}
|
||||||
return oscmd.OK(), nil
|
return oscmd.OK(), nil
|
||||||
})
|
})
|
||||||
|
|
||||||
|
huma.Register(api, huma.Operation{
|
||||||
|
OperationID: "system-generate-locale",
|
||||||
|
Method: "POST",
|
||||||
|
Path: "/api/system/locale/generate",
|
||||||
|
Summary: "Generate (install) a new locale",
|
||||||
|
Description: "Generates a locale so it becomes available for use with set-locale. " +
|
||||||
|
"On Debian/Ubuntu/Arch this uncomments the entry in /etc/locale.gen and runs " +
|
||||||
|
"locale-gen; on RHEL/Fedora it uses localedef. Idempotent: if the locale is " +
|
||||||
|
"already generated, returns 200 immediately.",
|
||||||
|
Tags: []string{tagSystem},
|
||||||
|
Metadata: op("write"),
|
||||||
|
Errors: append(writeErrors, 501),
|
||||||
|
}, func(ctx context.Context, in *GenerateLocaleInput) (*oscmd.StatusOutput, error) {
|
||||||
|
locale := strings.TrimSpace(in.Body.Locale)
|
||||||
|
if locale == "" {
|
||||||
|
return nil, huma.Error400BadRequest("empty locale")
|
||||||
|
}
|
||||||
|
if !localeRe.MatchString(locale) {
|
||||||
|
return nil, huma.Error400BadRequest("invalid locale format: "+locale,
|
||||||
|
fmt.Errorf("expected language_TERRITORY[.charmap], e.g. fr_FR.UTF-8"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Idempotency: already generated → success.
|
||||||
|
existing, err := oscmd.RunLines("localectl", "list-locales")
|
||||||
|
if err != nil {
|
||||||
|
return nil, huma.Error500InternalServerError("localectl failed", err)
|
||||||
|
}
|
||||||
|
if slices.Contains(existing, locale) {
|
||||||
|
return oscmd.OK(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Detect which generation path the host supports.
|
||||||
|
localeGenFile := "/etc/locale.gen"
|
||||||
|
_, hasFile := os.Stat(localeGenFile)
|
||||||
|
_, hasLocaleGen := exec.LookPath("locale-gen")
|
||||||
|
_, hasLocaledef := exec.LookPath("localedef")
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case hasFile == nil && hasLocaleGen == nil:
|
||||||
|
if err := enableLocaleGen(localeGenFile, locale); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
case hasLocaledef == nil:
|
||||||
|
if err := generateLocaledef(locale); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return nil, huma.Error501NotImplemented(
|
||||||
|
"locale generation not supported on this host (no locale-gen or localedef found)")
|
||||||
|
}
|
||||||
|
return oscmd.OK(), nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// enableLocaleGen uncomments the locale in /etc/locale.gen and runs locale-gen.
|
||||||
|
// This is the Debian/Ubuntu/Arch path.
|
||||||
|
func enableLocaleGen(path, locale string) error {
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return huma.Error500InternalServerError("reading locale.gen failed", err)
|
||||||
|
}
|
||||||
|
newContent, found := uncommentLocaleGen(string(data), locale)
|
||||||
|
if !found {
|
||||||
|
return huma.Error400BadRequest("locale not available for generation: " + locale)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, []byte(newContent), 0644); err != nil {
|
||||||
|
return huma.Error500InternalServerError("writing locale.gen failed", err)
|
||||||
|
}
|
||||||
|
if _, err := oscmd.Run("locale-gen"); err != nil {
|
||||||
|
return huma.Error500InternalServerError("locale-gen failed", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// uncommentLocaleGen finds a commented-out line for the given locale in a
|
||||||
|
// locale.gen file and uncomments it. Returns the modified content and whether
|
||||||
|
// a matching line was found. Pure function for testability.
|
||||||
|
func uncommentLocaleGen(content, locale string) (string, bool) {
|
||||||
|
lines := strings.Split(content, "\n")
|
||||||
|
found := false
|
||||||
|
for i, line := range lines {
|
||||||
|
trimmed := strings.TrimSpace(line)
|
||||||
|
// Match lines like "# fr_FR.UTF-8 UTF-8" or "#fr_FR.UTF-8 UTF-8".
|
||||||
|
if !strings.HasPrefix(trimmed, "#") {
|
||||||
|
// Also check if already uncommented (idempotent at the file level).
|
||||||
|
if strings.HasPrefix(trimmed, locale+" ") || trimmed == locale {
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
uncommented := strings.TrimSpace(strings.TrimPrefix(trimmed, "#"))
|
||||||
|
if strings.HasPrefix(uncommented, locale+" ") || uncommented == locale {
|
||||||
|
lines[i] = uncommented
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.Join(lines, "\n"), found
|
||||||
|
}
|
||||||
|
|
||||||
|
// generateLocaledef generates a locale using localedef. This is the RHEL/Fedora
|
||||||
|
// path where there is no /etc/locale.gen.
|
||||||
|
func generateLocaledef(locale string) error {
|
||||||
|
// Parse "fr_FR.UTF-8" into language_territory="fr_FR" and charmap="UTF-8".
|
||||||
|
// If there is no dot, default to UTF-8 (the common case on modern systems).
|
||||||
|
langTerritory, charmap, _ := strings.Cut(locale, ".")
|
||||||
|
if charmap == "" {
|
||||||
|
charmap = "UTF-8"
|
||||||
|
}
|
||||||
|
if _, err := oscmd.Run("localedef", "-i", langTerritory, "-f", charmap, locale); err != nil {
|
||||||
|
return huma.Error500InternalServerError("localedef failed", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"nadir/internal/oscmd"
|
"nadir/internal/oscmd"
|
||||||
@@ -199,6 +200,37 @@ func TestSystemHandlers(t *testing.T) {
|
|||||||
t.Errorf("set keymap: got %d, want %d", resp.Code, http.StatusOK)
|
t.Errorf("set keymap: got %d, want %d", resp.Code, http.StatusOK)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 4b. Test POST /api/system/locale/generate (validation & idempotent)
|
||||||
|
// Empty locale → 422 (huma validates non-empty before handler runs)
|
||||||
|
resp = api.Post("/api/system/locale/generate", struct {
|
||||||
|
Locale string `json:"locale"`
|
||||||
|
}{
|
||||||
|
Locale: "",
|
||||||
|
})
|
||||||
|
if resp.Code != http.StatusBadRequest && resp.Code != http.StatusUnprocessableEntity {
|
||||||
|
t.Errorf("generate empty locale: got %d, want 400 or 422", resp.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Invalid format → 400
|
||||||
|
resp = api.Post("/api/system/locale/generate", struct {
|
||||||
|
Locale string `json:"locale"`
|
||||||
|
}{
|
||||||
|
Locale: "not-a-locale!!",
|
||||||
|
})
|
||||||
|
if resp.Code != http.StatusBadRequest {
|
||||||
|
t.Errorf("generate invalid locale: got %d, want %d", resp.Code, http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Already generated (it_IT.UTF-8 is in list-locales mock) → 200 (idempotent)
|
||||||
|
resp = api.Post("/api/system/locale/generate", struct {
|
||||||
|
Locale string `json:"locale"`
|
||||||
|
}{
|
||||||
|
Locale: "it_IT.UTF-8",
|
||||||
|
})
|
||||||
|
if resp.Code != http.StatusOK {
|
||||||
|
t.Errorf("generate existing locale (idempotent): got %d, want %d", resp.Code, http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
// 5. Test POST /api/system/reboot and /api/system/poweroff
|
// 5. Test POST /api/system/reboot and /api/system/poweroff
|
||||||
oscmd.SetMock("shutdown", func(args []string) oscmd.MockCommand {
|
oscmd.SetMock("shutdown", func(args []string) oscmd.MockCommand {
|
||||||
if reflect.DeepEqual(args, []string{"-r", "now"}) || reflect.DeepEqual(args, []string{"-h", "now"}) {
|
if reflect.DeepEqual(args, []string{"-r", "now"}) || reflect.DeepEqual(args, []string{"-h", "now"}) {
|
||||||
@@ -225,3 +257,58 @@ func TestSystemHandlers(t *testing.T) {
|
|||||||
t.Errorf("poweroff: got %d, want %d", resp.Code, http.StatusOK)
|
t.Errorf("poweroff: got %d, want %d", resp.Code, http.StatusOK)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestUncommentLocaleGen(t *testing.T) {
|
||||||
|
const sampleLocaleGen = `# This file lists locales that you wish to have built.
|
||||||
|
#
|
||||||
|
# en_US.UTF-8 UTF-8
|
||||||
|
# fr_FR.UTF-8 UTF-8
|
||||||
|
# de_DE.UTF-8 UTF-8
|
||||||
|
it_IT.UTF-8 UTF-8
|
||||||
|
`
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
locale string
|
||||||
|
wantFound bool
|
||||||
|
wantSubstr string // substring that should appear uncommented
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "uncomment commented locale",
|
||||||
|
locale: "fr_FR.UTF-8",
|
||||||
|
wantFound: true,
|
||||||
|
wantSubstr: "\nfr_FR.UTF-8 UTF-8\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "already uncommented",
|
||||||
|
locale: "it_IT.UTF-8",
|
||||||
|
wantFound: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "locale not in file",
|
||||||
|
locale: "ja_JP.UTF-8",
|
||||||
|
wantFound: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
result, found := uncommentLocaleGen(sampleLocaleGen, tt.locale)
|
||||||
|
if found != tt.wantFound {
|
||||||
|
t.Errorf("found = %v, want %v", found, tt.wantFound)
|
||||||
|
}
|
||||||
|
if tt.wantSubstr != "" && !contains(result, tt.wantSubstr) {
|
||||||
|
t.Errorf("result does not contain %q:\n%s", tt.wantSubstr, result)
|
||||||
|
}
|
||||||
|
// The commented versions of OTHER locales should remain commented.
|
||||||
|
if tt.locale == "fr_FR.UTF-8" && !contains(result, "# en_US.UTF-8 UTF-8") {
|
||||||
|
t.Errorf("other locales should stay commented:\n%s", result)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func contains(s, substr string) bool {
|
||||||
|
return len(s) >= len(substr) && (s == substr || len(substr) == 0 ||
|
||||||
|
(len(s) > 0 && strings.Contains(s, substr)))
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user