|
| 1 | +// Copyright 2024 The Gitea Authors. All rights reserved. |
| 2 | +// SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +package webtheme |
| 5 | + |
| 6 | +import ( |
| 7 | + "strings" |
| 8 | + "sync" |
| 9 | + |
| 10 | + "code.gitea.io/gitea/modules/container" |
| 11 | + "code.gitea.io/gitea/modules/log" |
| 12 | + "code.gitea.io/gitea/modules/public" |
| 13 | + "code.gitea.io/gitea/modules/setting" |
| 14 | +) |
| 15 | + |
| 16 | +var ( |
| 17 | + availableThemes []string |
| 18 | + availableThemesSet container.Set[string] |
| 19 | + themeOnce sync.Once |
| 20 | +) |
| 21 | + |
| 22 | +func initThemes() { |
| 23 | + availableThemes = nil |
| 24 | + defer func() { |
| 25 | + availableThemesSet = container.SetOf(availableThemes...) |
| 26 | + }() |
| 27 | + cssFiles, err := public.AssetFS().ListFiles("/assets/css") |
| 28 | + if err != nil { |
| 29 | + log.Error("Failed to list themes: %v", err) |
| 30 | + availableThemes = []string{setting.UI.DefaultTheme} |
| 31 | + return |
| 32 | + } |
| 33 | + var foundThemes []string |
| 34 | + for _, name := range cssFiles { |
| 35 | + name, ok := strings.CutPrefix(name, "theme-") |
| 36 | + if !ok { |
| 37 | + continue |
| 38 | + } |
| 39 | + name, ok = strings.CutSuffix(name, ".css") |
| 40 | + if !ok { |
| 41 | + continue |
| 42 | + } |
| 43 | + foundThemes = append(foundThemes, name) |
| 44 | + } |
| 45 | + if len(setting.UI.Themes) > 0 { |
| 46 | + allowedThemes := container.SetOf(setting.UI.Themes...) |
| 47 | + for _, theme := range foundThemes { |
| 48 | + if allowedThemes.Contains(theme) { |
| 49 | + availableThemes = append(availableThemes, theme) |
| 50 | + } |
| 51 | + } |
| 52 | + } else { |
| 53 | + availableThemes = foundThemes |
| 54 | + } |
| 55 | + if len(availableThemes) == 0 { |
| 56 | + log.Error("No theme candidate, but gitea requires there should be at least one usable theme") |
| 57 | + availableThemes = []string{setting.UI.DefaultTheme} |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +func GetAvailableThemes() []string { |
| 62 | + themeOnce.Do(initThemes) |
| 63 | + return availableThemes |
| 64 | +} |
| 65 | + |
| 66 | +func IsThemeAvailable(name string) bool { |
| 67 | + themeOnce.Do(initThemes) |
| 68 | + return availableThemesSet.Contains(name) |
| 69 | +} |
0 commit comments