Debian Codegraph @

hugolib/roles/roles.go

raw
1 // Copyright 2025 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package roles
15
16 import (
17 "errors"
18 "fmt"
19 "iter"
20 "sort"
21
22 "github.com/gohugoio/hugo/common/paths"
23 "github.com/gohugoio/hugo/common/predicate"
24 "github.com/gohugoio/hugo/config"
25 "github.com/gohugoio/hugo/hugolib/sitesmatrix"
26 "github.com/mitchellh/mapstructure"
27 )
28
29 var _ sitesmatrix.DimensionInfo = (*roleWrapper)(nil)
30
31 type RoleConfig struct {
32 // The weight of the role.
33 // Used to determine the order of the roles.
34 // If zero, we use the role name.
35 Weight int
36 }
37
38 type Role interface {
39 Name() string
40 }
41
42 type Roles []Role
43
44 var _ Role = (*roleWrapper)(nil)
45
46 func NewRole(r RoleInternal) Role {
47 return roleWrapper{r: r}
48 }
49
50 type roleWrapper struct {
51 r RoleInternal
52 }
53
54 func (r roleWrapper) Name() string {
55 return r.r.Name
56 }
57
58 func (r roleWrapper) IsDefault() bool {
59 return r.r.Default
60 }
61
62 type RoleInternal struct {
63 // Name is the name of the role, extracted from the key in the config.
64 Name string
65
66 // Whether this role is the default role.
67 // This will be rendered in the root.
68 // There is only be one default role.
69 Default bool
70
71 RoleConfig
72 }
73
74 type RolesInternal struct {
75 roleConfigs map[string]RoleConfig
76 Sorted []RoleInternal
77 }
78
79 func (r RolesInternal) Len() int {
80 return len(r.Sorted)
81 }
82
83 func (r RolesInternal) IndexDefault() int {
84 for i, role := range r.Sorted {
85 if role.Default {
86 return i
87 }
88 }
89 panic("no default role found")
90 }
91
92 func (r RolesInternal) ResolveName(i int) string {
93 if i < 0 || i >= len(r.Sorted) {
94 panic(fmt.Sprintf("index %d out of range for roles", i))
95 }
96 return r.Sorted[i].Name
97 }
98
99 func (r RolesInternal) ResolveIndex(name string) int {
100 for i, role := range r.Sorted {
101 if role.Name == name {
102 return i
103 }
104 }
105 return -1
106 }
107
108 // IndexMatch returns an iterator for the roles that match the filter.
109 func (r RolesInternal) IndexMatch(match predicate.P[predicate.IndexString]) (iter.Seq[int], error) {
110 return func(yield func(i int) bool) {
111 for i, role := range r.Sorted {
112 if match(predicate.IndexString{Index: i, String: role.Name}) {
113 if !yield(i) {
114 return
115 }
116 }
117 }
118 }, nil
119 }
120
121 // ForEachIndex returns an iterator for the indices of the roles.
122 func (r RolesInternal) ForEachIndex() iter.Seq[int] {
123 return func(yield func(i int) bool) {
124 for i := range r.Sorted {
125 if !yield(i) {
126 return
127 }
128 }
129 }
130 }
131
132 const defaultContentRoleFallback = "guest"
133
134 func (r *RolesInternal) init(defaultContentRole string) (string, error) {
135 if r.roleConfigs == nil {
136 r.roleConfigs = make(map[string]RoleConfig)
137 }
138 defaultContentRoleProvided := defaultContentRole != ""
139 if len(r.roleConfigs) == 0 {
140 // Add a default role.
141 if defaultContentRole == "" {
142 defaultContentRole = defaultContentRoleFallback
143 }
144 r.roleConfigs[defaultContentRole] = RoleConfig{}
145 }
146
147 var defaultSeen bool
148 for k, v := range r.roleConfigs {
149 if k == "" {
150 return "", errors.New("role name cannot be empty")
151 }
152
153 if err := paths.ValidateIdentifier(k); err != nil {
154 return "", fmt.Errorf("role name %q is invalid: %s", k, err)
155 }
156
157 var isDefault bool
158 if k == defaultContentRole {
159 isDefault = true
160 defaultSeen = true
161 }
162
163 r.Sorted = append(r.Sorted, RoleInternal{Name: k, Default: isDefault, RoleConfig: v})
164 }
165
166 // Sort by weight if set, then by name.
167 sort.SliceStable(r.Sorted, func(i, j int) bool {
168 ri, rj := r.Sorted[i], r.Sorted[j]
169 if ri.Weight == rj.Weight {
170 return ri.Name < rj.Name
171 }
172 if rj.Weight == 0 {
173 return true
174 }
175 if ri.Weight == 0 {
176 return false
177 }
178 return ri.Weight < rj.Weight
179 })
180
181 if !defaultSeen {
182 if defaultContentRoleProvided {
183 return "", fmt.Errorf("the configured defaultContentRole %q does not exist", defaultContentRole)
184 }
185 // If no default role is set, we set the first one.
186 first := r.Sorted[0]
187 first.Default = true
188 r.roleConfigs[first.Name] = first.RoleConfig
189 r.Sorted[0] = first
190 defaultContentRole = first.Name
191 }
192
193 return defaultContentRole, nil
194 }
195
196 func (r RolesInternal) Has(role string) bool {
197 _, found := r.roleConfigs[role]
198 return found
199 }
200
201 func DecodeConfig(defaultContentRole string, m map[string]any) (*config.ConfigNamespace[map[string]RoleConfig, RolesInternal], string, error) {
202 v, err := config.DecodeNamespace[map[string]RoleConfig](m, func(in any) (RolesInternal, any, error) {
203 var roles RolesInternal
204 var conf map[string]RoleConfig
205 if err := mapstructure.Decode(m, &conf); err != nil {
206 return roles, nil, err
207 }
208 roles.roleConfigs = conf
209 var err error
210 if defaultContentRole, err = roles.init(defaultContentRole); err != nil {
211 return roles, nil, err
212 }
213 return roles, roles.roleConfigs, nil
214 })
215
216 return v, defaultContentRole, err
217 }