Repository navigation
Expand file tree
/
Copy pathnamespace.go
More file actions
534 lines (470 loc) · 12.9 KB
/
Copy pathnamespace.go
File metadata and controls
534 lines (470 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
package miya
import (
"fmt"
"reflect"
"strings"
"sync"
"github.com/zipreport/miya/runtime"
)
// Namespace represents a Jinja2 namespace object
// Namespaces are mutable objects that allow sharing data between scopes
type Namespace struct {
runtime.NamespaceMarker
mu sync.RWMutex
data map[string]interface{}
}
// NewNamespace creates a new namespace object
func NewNamespace() *Namespace {
return &Namespace{
data: make(map[string]interface{}),
}
}
// Get retrieves a value from the namespace. A list is returned as a plain
// slice; RawGet returns the stored value.
func (ns *Namespace) Get(key string) (interface{}, bool) {
val, ok := ns.RawGet(key)
return runtime.Unbox(val), ok
}
// RawGet retrieves the stored value for the template runtime, which can be
// an internal list box or internal escaped template output; Go code should
// use Get.
func (ns *Namespace) RawGet(key string) (interface{}, bool) {
ns.mu.RLock()
defer ns.mu.RUnlock()
val, ok := ns.data[key]
return val, ok
}
// Set sets a value in the namespace
func (ns *Namespace) Set(key string, value interface{}) {
ns.mu.Lock()
defer ns.mu.Unlock()
ns.data[key] = value
}
// Has checks if a key exists in the namespace
func (ns *Namespace) Has(key string) bool {
ns.mu.RLock()
defer ns.mu.RUnlock()
_, ok := ns.data[key]
return ok
}
// All returns a copy of all data in the namespace; lists are plain slices.
func (ns *Namespace) All() map[string]interface{} {
ns.mu.RLock()
defer ns.mu.RUnlock()
result := make(map[string]interface{}, len(ns.data))
for k, v := range ns.data {
result[k] = runtime.Unbox(v)
}
return result
}
// Delete removes a key from the namespace
func (ns *Namespace) Delete(key string) {
ns.mu.Lock()
defer ns.mu.Unlock()
delete(ns.data, key)
}
// Clear removes all data from the namespace
func (ns *Namespace) Clear() {
ns.mu.Lock()
defer ns.mu.Unlock()
ns.data = make(map[string]interface{})
}
// ReprData returns a copy of the namespace's data for runtime.Repr.
func (ns *Namespace) ReprData() map[string]interface{} {
ns.mu.RLock()
defer ns.mu.RUnlock()
result := make(map[string]interface{}, len(ns.data))
for k, v := range ns.data {
result[k] = v
}
return result
}
// String returns a string representation of the namespace
func (ns *Namespace) String() string {
return runtime.Repr(ns)
}
// namespaceFunction is the global namespace() function for templates
func namespaceFunction(args ...interface{}) (interface{}, error) {
ns := NewNamespace()
// If keyword arguments are provided, initialize the namespace with them
if len(args) == 1 {
if kwargs, ok := args[0].(map[string]interface{}); ok {
for k, v := range kwargs {
ns.Set(k, runtime.BoxList(v))
}
}
}
return ns, nil
}
// NamespaceWrapper wraps a namespace to provide dot-notation access in templates
type NamespaceWrapper struct {
*Namespace
}
// GetAttr provides attribute-style access to namespace values
func (nw *NamespaceWrapper) GetAttr(name string) (interface{}, error) {
val, ok := nw.Get(name)
if !ok {
// Return nil for missing attributes (Jinja2 behavior)
return nil, nil
}
return val, nil
}
// SetAttr provides attribute-style setting of namespace values
func (nw *NamespaceWrapper) SetAttr(name string, value interface{}) error {
nw.Set(name, value)
return nil
}
// maxRangeLength bounds the number of items range() will materialise.
const maxRangeLength = 1000000
// rangeFunction implements the range() global function
// It generates a sequence of numbers similar to Python's range()
func rangeFunction(args ...interface{}) (interface{}, error) {
var start, stop, step int
switch len(args) {
case 1:
// range(stop)
stop = toInt(args[0])
start = 0
step = 1
case 2:
// range(start, stop)
start = toInt(args[0])
stop = toInt(args[1])
step = 1
case 3:
// range(start, stop, step)
start = toInt(args[0])
stop = toInt(args[1])
step = toInt(args[2])
if step == 0 {
return nil, fmt.Errorf("range() step argument must not be zero")
}
default:
return nil, fmt.Errorf("range() takes 1 to 3 arguments, got %d", len(args))
}
// Compute the length before allocating, using unsigned arithmetic so
// extreme bounds cannot overflow into a small number.
var n uint64
if step > 0 && stop > start {
d := uint64(stop) - uint64(start)
n = d / uint64(step)
if d%uint64(step) != 0 {
n++
}
} else if step < 0 && stop < start {
d := uint64(start) - uint64(stop)
m := -uint64(int64(step))
n = d / m
if d%m != 0 {
n++
}
}
if n > maxRangeLength {
return nil, &runtime.SizeError{Msg: fmt.Sprintf("range() too large: %d items (limit %d)", n, maxRangeLength)}
}
// Generate the sequence
result := make([]interface{}, 0, n)
i := start
for k := uint64(0); k < n; k++ {
result = append(result, i)
i += step
}
return result, nil
}
// dictFunction implements the dict() global function
// It creates a dictionary from key-value pairs
func dictFunction(args ...interface{}) (interface{}, error) {
result := make(map[string]interface{})
// Handle different argument patterns
if len(args) == 0 {
return result, nil
}
// If single argument is a map, use it as kwargs
if len(args) == 1 {
if kwargs, ok := args[0].(map[string]interface{}); ok {
for k, v := range kwargs {
result[k] = v
}
return result, nil
}
}
// Otherwise, expect pairs of arguments
if len(args)%2 != 0 {
return nil, fmt.Errorf("dict() requires an even number of arguments when not using keyword arguments")
}
for i := 0; i < len(args); i += 2 {
key, ok := args[i].(string)
if !ok {
return nil, fmt.Errorf("dict() keys must be strings, got %T", args[i])
}
result[key] = args[i+1]
}
return result, nil
}
// cyclerFunction creates a cycler object that cycles through values
func cyclerFunction(args ...interface{}) (interface{}, error) {
if len(args) == 0 {
return nil, fmt.Errorf("cycler() requires at least one argument")
}
return &runtime.Cycler{
Items: args,
Current: 0,
}, nil
}
// joinerFunction creates a joiner object that joins values with separators
func joinerFunction(args ...interface{}) (interface{}, error) {
separator := ", " // default separator
safe := false
if len(args) > 0 {
if m, ok := runtime.AsMarkup(args[0]); ok {
separator, safe = string(m), true
} else if sep, ok := args[0].(string); ok {
separator = sep
}
}
return &runtime.Joiner{
Separator: separator,
Used: false,
Safe: safe,
}, nil
}
// lipsumFunction generates Lorem Ipsum text
func lipsumFunction(args ...interface{}) (interface{}, error) {
paragraphs := 5
sentences := true
minSentences := 4
maxSentences := 6
// Parse arguments
if len(args) > 0 {
if p, ok := args[0].(int); ok {
paragraphs = p
}
}
if len(args) > 1 {
if s, ok := args[1].(bool); ok {
sentences = s
}
}
if len(args) > 2 {
if min, ok := args[2].(int); ok {
minSentences = min
}
}
if len(args) > 3 {
if max, ok := args[3].(int); ok {
maxSentences = max
}
}
if paragraphs > 1000 || minSentences > 1000 || maxSentences > 1000 {
return nil, &runtime.SizeError{Msg: "lipsum() too large"}
}
// Lorem ipsum words
words := []string{
"lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit",
"sed", "do", "eiusmod", "tempor", "incididunt", "ut", "labore", "et", "dolore",
"magna", "aliqua", "enim", "ad", "minim", "veniam", "quis", "nostrud",
"exercitation", "ullamco", "laboris", "nisi", "aliquip", "ex", "ea", "commodo",
"consequat", "duis", "aute", "irure", "in", "reprehenderit", "voluptate",
"velit", "esse", "cillum", "fugiat", "nulla", "pariatur", "excepteur", "sint",
"occaecat", "cupidatat", "non", "proident", "sunt", "culpa", "qui", "officia",
"deserunt", "mollit", "anim", "id", "est", "laborum",
}
var result strings.Builder
for p := 0; p < paragraphs; p++ {
if p > 0 {
result.WriteString("\n\n")
}
if sentences {
// Generate sentences
numSentences := minSentences + (p % (maxSentences - minSentences + 1))
for s := 0; s < numSentences; s++ {
if s > 0 {
result.WriteString(" ")
}
// Generate a sentence (5-15 words)
sentenceLength := 5 + (s % 11)
for w := 0; w < sentenceLength; w++ {
if w > 0 {
result.WriteString(" ")
}
wordIndex := (p*numSentences*sentenceLength + s*sentenceLength + w) % len(words)
word := words[wordIndex]
if w == 0 {
// Capitalize first word
word = capitalizeFirst(word)
}
result.WriteString(word)
}
result.WriteString(".")
}
} else {
// Generate word list
wordCount := 50 + (p * 10)
for w := 0; w < wordCount; w++ {
if w > 0 {
result.WriteString(" ")
}
wordIndex := (p*wordCount + w) % len(words)
result.WriteString(words[wordIndex])
}
}
}
return result.String(), nil
}
// toInt converts an interface to int
func toInt(v interface{}) int {
switch val := v.(type) {
case runtime.RoundedFloat:
return int(val.Value)
case int:
return val
case int64:
return int(val)
case float64:
return int(val)
case string:
// Try to parse string as int
var i int
fmt.Sscanf(val, "%d", &i)
return i
default:
return 0
}
}
// zipFunction combines multiple iterables into tuples
func zipFunction(args ...interface{}) (interface{}, error) {
if len(args) == 0 {
return []interface{}{}, nil
}
// Convert all arguments to slices
slices := make([][]interface{}, len(args))
minLen := -1
for i, arg := range args {
slice, err := makeIterable(arg)
if err != nil {
return nil, fmt.Errorf("zip() argument %d is not iterable: %v", i+1, err)
}
slices[i] = slice
if minLen == -1 || len(slice) < minLen {
minLen = len(slice)
}
}
// Create result tuples
result := make([]interface{}, minLen)
for i := 0; i < minLen; i++ {
tuple := make([]interface{}, len(slices))
for j, slice := range slices {
tuple[j] = slice[i]
}
result[i] = tuple
}
return result, nil
}
// enumerateFunction returns pairs of (index, item) for an iterable
func enumerateFunction(args ...interface{}) (interface{}, error) {
if n := len(args); n > 1 {
if kw, ok := args[n-1].(map[string]interface{}); ok {
args = args[:n-1]
for k, v := range kw {
if k != "start" || len(args) != 1 {
return nil, fmt.Errorf("enumerate() got an unexpected keyword argument %q", k)
}
args = append(args, v)
}
}
}
if len(args) == 0 {
return nil, fmt.Errorf("enumerate() requires at least one argument")
}
if len(args) > 2 {
return nil, fmt.Errorf("enumerate() takes 1 or 2 arguments, got %d", len(args))
}
start := 0
if len(args) == 2 {
v := reflect.ValueOf(args[1])
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
start = int(v.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
start = int(v.Uint())
default:
return nil, fmt.Errorf("enumerate() start must be an integer, got %T", args[1])
}
}
slice, err := makeIterable(args[0])
if err != nil {
return nil, fmt.Errorf("enumerate() argument is not iterable: %v", err)
}
result := make([]interface{}, len(slice))
for i, item := range slice {
result[i] = []interface{}{start + i, item}
}
return result, nil
}
// urlForFunction generates URLs for endpoints (basic implementation)
func urlForFunction(args ...interface{}) (interface{}, error) {
if len(args) == 0 {
return nil, fmt.Errorf("url_for() requires at least one argument (endpoint)")
}
endpoint, ok := args[0].(string)
if !ok {
return nil, fmt.Errorf("url_for() endpoint must be a string")
}
// Basic implementation - in a real application, this would use a URL router
// For now, we'll create simple URLs based on the endpoint name
url := "/" + endpoint
// Handle additional arguments as URL parameters
if len(args) > 1 {
params := make([]string, 0)
for i := 1; i < len(args); i += 2 {
if i+1 < len(args) {
key := fmt.Sprintf("%v", args[i])
value := fmt.Sprintf("%v", args[i+1])
params = append(params, fmt.Sprintf("%s=%s", key, value))
}
}
if len(params) > 0 {
url += "?" + strings.Join(params, "&")
}
}
return url, nil
}
// Helper function to convert interface to iterable slice
func makeIterable(value interface{}) ([]interface{}, error) {
if value == nil {
return []interface{}{}, nil
}
switch v := value.(type) {
case []interface{}:
return v, nil
case []string:
result := make([]interface{}, len(v))
for i, s := range v {
result[i] = s
}
return result, nil
case []int:
result := make([]interface{}, len(v))
for i, n := range v {
result[i] = n
}
return result, nil
case string:
result := make([]interface{}, len(v))
for i, r := range []rune(v) {
result[i] = string(r)
}
return result, nil
default:
// Try reflection for other slice types
rv := reflect.ValueOf(value)
if rv.Kind() == reflect.Slice || rv.Kind() == reflect.Array {
result := make([]interface{}, rv.Len())
for i := 0; i < rv.Len(); i++ {
result[i] = rv.Index(i).Interface()
}
return result, nil
}
return nil, fmt.Errorf("value is not iterable: %T", value)
}
}