zuzu-rust 0.1.0

Rust implementation of ZuzuScript
Documentation
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
=encoding utf8

=head1 NAME

std/config - High-level configuration loading, merging, and querying.

=head1 SYNOPSIS

  from std/config import Config;
  from std/io import Path;

  let cfg := Config.load( [
    Path.join( [ "config", "base.toml" ] ),
    Path.join( [ "config", "local.json" ] ),
  ] );

  cfg.merge_flat(
    {
      "APP__port": "8080",
      "APP__debug": "true",
    },
    {
      prefix: "APP__",
      separator: "__",
      coerce: true,
    },
  );

  let host := cfg @ "/database/host";
  let port := cfg.get( "/port", 3000 );

=head1 IMPLEMENTATION SUPPORT

This module is supported by zuzu.pl, zuzu-rust, and zuzu-js on Node and
Electron. It is partially supported by zuzu-js in the browser: environment
override and multi-format branch selection coverage passes, but the main
filesystem-backed configuration coverage is unsupported.

=head1 DESCRIPTION

This module provides a C<Config> object for application-style
configuration loading and overlaying.

Use C<Config.from_data(...)> when you want to wrap an already-built
Zuzu value instead of loading from files.

It is intentionally geared toward patterns common in higher-level config
frameworks:

=over

=item *

load one or more files with format auto-detection,

=item *

deep-merge config layers,

=item *

apply flat overlays such as env-style C<FOO__BAR__BAZ> keys,

=item *

query config using ZPath and the C<@>, C<@@>, and C<@?> operators.

=back

The object itself is path-aware, so this works directly:

  let city := cfg @ "/service/address/city";

=head1 EXPORTS

=head2 Classes

=over

=item C<Config>

Static methods:

=over

=item * C<from_data(data, options?)>

Parameters: C<data> is configuration data and C<options> controls
metadata. Returns: C<Config>. Wraps data in a config object.

=item * C<parse(text, format, options?)>

Parameters: C<text> is config text, C<format> is a format name, and
C<options> configures parsing. Returns: C<Config>. Parses text into a
config object.

=item * C<load(path_or_paths, options?)>

Parameters: C<path_or_paths> is one source or an array of sources.
Returns: C<Config>. Loads and layers config files.

=item * C<detect_format(path_or_name, fallback?)>

Parameters: C<path_or_name> is a path-like value and C<fallback> is
optional. Returns: C<String> or C<null>. Detects the config format.

=back

Instance methods:

=over

=item * C<type()>, C<can_have_named_children()>, C<can_have_indexed_children()>, C<can_have_named_indexed_children()>, C<children()>, C<attributes()>

Parameters: none. Returns: ZPath node metadata. Provides the inherited
node API used when a C<Config> is queried as a path root.

=item * C<do_action_on_child(child, action)>, C<ref_on_child(child)>

Parameters: C<child> is a selected node and C<action> is a path action.
Returns: value or C<Function>. Provides inherited mutation and reference
support for path assignments.

=item * C<to_data()>, C<clone()>

Parameters: none. Returns: value or C<Config>. Returns raw data or a
copy of the config.

=item * C<source()>, C<format()>, C<layers()>

Parameters: none. Returns: value. Returns config source metadata.

=item * C<get(path, fallback?)>, C<get_all(path)>, C<select(path)>

Parameters: C<path> is a path expression and C<fallback> is optional.
Returns: value or C<Array>. Reads config values.

=item * C<exists(path)>, C<require(path, message?)>

Parameters: C<path> is a path expression and C<message> is optional.
Returns: C<Boolean> or value. Tests for or requires a config value.

=item * C<query(path)>, C<first(path, fallback?)>

Parameters: C<path> is a path expression and C<fallback> is optional.
Returns: C<Array> or value. Queries config values.

=item * C<assign_first(path, value, op?)>

Parameters: C<path> selects values, C<value> is assigned, and C<op> is
optional. Returns: value. Updates the first match.

=item * C<assign_all(path, value, op?)>

Parameters: C<path> selects values, C<value> is assigned, and C<op> is
optional. Returns: value. Updates every match.

=item * C<assign_maybe(path, value, op?)>

Parameters: C<path> selects values, C<value> is assigned, and C<op> is
optional. Returns: C<Boolean>. Updates the first match when present.

=item * C<ref_first(path)>, C<ref_all(path)>, C<ref_maybe(path)>

Parameters: C<path> is a path expression. Returns: C<Function>,
C<Array>, or C<null>. Returns reference-like accessors.

=item * C<merge(data_or_config, options?)>, C<overlay(data_or_config, options?)>

Parameters: C<data_or_config> is incoming data and C<options> controls
merge behaviour. Returns: C<Config>. Merges configuration data.

=item * C<merge_flat(values, options?)>, C<merge_env(values, options?)>

Parameters: C<values> is flat config data and C<options> controls key
mapping. Returns: C<Config>. Merges flat or environment-style values.

=item * C<set(path, value)>, C<set_default(path, value)>

Parameters: C<path> is a simple path and C<value> is any value. Returns:
C<Config>. Sets or defaults a config value.

=item * C<encode(format?, options?)>, C<save(path, options?)>

Parameters: C<format>, C<path>, and C<options> control output. Returns:
C<String> or C<Config>. Encodes or saves configuration data.

=item * C<load_file(path, options?)>

Parameters: C<path> is a config source and C<options> controls parsing.
Returns: C<Config>. Loads one additional config file into the object.

=back

=back

=head1 NOTES

=over

=item *

C<merge> performs a deep merge for dictionaries.

=item *

Arrays are replaced by default; pass C<< { array_merge: "append" } >>
to append instead.

=item *

C<set> and C<set_default> create missing parent dictionaries, but only
for simple absolute paths such as C</server/port>. They intentionally do
not try to create missing nodes for complex selectors or filters.

=back

=head1 COPYRIGHT AND LICENCE

B<< std/config >> is copyright Toby Inkster.

It is free software; you may redistribute it and/or modify it under
the terms of either the Artistic License 1.0 or the GNU General Public
License version 2.

=cut

from std/cache/lru import Cache;
from std/path/z import ZPath;
from std/path/z/node import Node;
from std/string import join, split, substr, trim;


const _PATH_CACHE := new Cache( capacity: 50 );

function _opt ( options, key, fallback := null ) {
	if ( options instanceof Dict and options.exists(key) ) {
		return options.get(key);
	}
	return fallback;
}

function _unwrap_config_value ( value ) {
	if (
		value ≢ null and
		value can raw and
		value can query and
		value can merge
	) {
		return value.raw();
	}
	return value;
}

function _stringify_pathish ( pathish ) {
	from std/io import Path;
	if ( pathish instanceof Path ) {
		return pathish.to_String();
	}
	return "" _ pathish;
}

function _normalize_format ( raw_format ) {
	if ( raw_format ≡ null ) {
		return null;
	}

	let fmt := lc( "" _ raw_format );
	if ( fmt ≡ "yml" ) {
		return "yaml";
	}
	return fmt;
}

function _detect_format_from_name ( source, fallback := null ) {
	let text := lc( _stringify_pathish(source) );
	let dot := null;
	let i := length text - 1;
	while ( i >= 0 ) {
		let ch := substr( text, i, 1 );
		if ( ch ≡ "." ) {
			dot := i;
			last;
		}
		if ( ch ≡ "/" or ch ≡ "\\" ) {
			last;
		}
		i--;
	}

	if ( dot ≡ null or dot = length text - 1 ) {
		return fallback;
	}

	return _normalize_format( substr( text, dot + 1 ) ) ?: fallback;
}

function _codec_for_format ( raw_format, options? ) {
	let format := _normalize_format(raw_format);
	if ( _opt( options, "codec", null ) ≢ null ) {
		return _opt( options, "codec", null );
	}

	if ( format ≡ "json" ) {
		from std/data/json import JSON;
		return new JSON();
	}
	if ( format ≡ "yaml" ) {
		from std/data/yaml import YAML;
		return new YAML();
	}
	if ( format ≡ "toml" ) {
		from std/data/toml import TOML;
		return new TOML();
	}
	if ( format ≡ "ini" ) {
		from std/data/ini import INI;
		return new INI();
	}
	if ( format ≡ "toon" ) {
		from std/data/toon import TOON;
		return new TOON();
	}

	die `std/config does not know how to handle format '${format}'`;
}

function _ensure_path_object ( source ) {
	from std/io import Path;
	return source instanceof Path ? source : new Path( "" _ source );
}

function _compile_path ( pathish ) {
	if ( pathish instanceof ZPath ) {
		return pathish;
	}
	if (
		pathish can query and
		pathish can first and
		pathish can exists and
		pathish can assign_first and
		pathish can ref_first
	) {
		return pathish;
	}

	let expression := "" _ pathish;
	return _PATH_CACHE.get(
		expression,
		fn path_text -> new ZPath( path: path_text ),
	);
}

function _coerce_scalar_text ( raw_value, options? ) {
	if ( not _opt( options, "coerce", false ) ) {
		return raw_value;
	}

	if ( not( raw_value instanceof String ) ) {
		return raw_value;
	}

	let text := trim(raw_value);
	let lowered := lc(text);

	if ( lowered ≡ "true" ) {
		return true;
	}
	if ( lowered ≡ "false" ) {
		return false;
	}
	if ( lowered ≡ "null" or lowered ≡ "~" ) {
		return null;
	}
	if ( text ~ /^-?[0-9]+$/ ) {
		return int(text);
	}
	if ( text ~ /^-?(?:[0-9]+\.[0-9]+|\.[0-9]+)$/ ) {
		return 0 + text;
	}
	if (
		length text >= 2 and
		(
			(
				substr( text, 0, 1 ) ≡ "{" and
				substr( text, length text - 1, 1 ) ≡ "}"
			) or
			(
				substr( text, 0, 1 ) ≡ "[" and
				substr( text, length text - 1, 1 ) ≡ "]"
			)
		)
	) {
		try {
			from std/data/json import JSON;
			return new JSON().decode(text);
		}
		catch {
		}
	}

	return raw_value;
}

function _merge_values ( left, right, options? ) {
	let left_value := _unwrap_config_value(left);
	let right_value := _unwrap_config_value(right);

	if ( left_value instanceof Dict and right_value instanceof Dict ) {
		for ( let key in right_value.keys() ) {
			if ( left_value.exists(key) ) {
				left_value{(key)} := _merge_values(
					left_value.get(key),
					right_value.get(key),
					options,
				);
			}
			else {
				left_value{(key)} := right_value.get(key);
			}
		}
		return left_value;
	}

	if (
		left_value instanceof Array and
		right_value instanceof Array and
		_opt( options, "array_merge", "replace" ) ≡ "append"
	) {
		for ( let item in right_value ) {
			left_value.push(item);
		}
		return left_value;
	}

	return right_value;
}

function _simple_path_parts ( raw_path ) {
	let text := "" _ raw_path;
	if ( text ≡ "" ) {
		return [];
	}
	if ( substr( text, 0, 1 ) ≡ "/" ) {
		text := substr( text, 1 );
	}
	if ( text ≡ "" ) {
		return [];
	}

	let parts := [];
	for ( let part in split( text, "/" ) ) {
		next if part ≡ "";
		die `std/config simple path cannot contain complex selector '${part}'`
			if part ~ /[\*\[\]#@\(\)]/;
		parts.push(part);
	}
	return parts;
}

function _ensure_root_dict ( current ) {
	if ( current ≡ null ) {
		return {};
	}
	if ( current instanceof Dict ) {
		return current;
	}
	die "std/config expected Dict root for simple path mutation";
}

class Config extends Node {
	let _source := null;
	let _format := null;
	let _layers := [];

	method __build__ () {
		self.set_raw( self.raw ≡ null ? {}: self.raw );
		_layers := _layers ≡ null ? []: _layers;
		self._build_id();
	}

	static method detect_format ( source, fallback := null ) {
		return _detect_format_from_name( source, fallback );
	}

	static method from_data ( data, options? ) {
		return new Config(
			raw: _unwrap_config_value(data),
			_source: _opt( options, "source", null ),
			_format: _normalize_format( _opt( options, "format", null ) ),
			_layers: _opt( options, "layers", [] ),
		);
	}

	static method parse ( text, format, options? ) {
		let codec := _codec_for_format( format, options );
		let layer_source := _opt( options, "source", null );
		let decoded := codec.decode(text);
		return new Config(
			raw: decoded,
			_source: layer_source,
			_format: _normalize_format(format),
			_layers: [
				{
					source: layer_source,
					format: _normalize_format(format),
				},
			],
		);
	}

	static method load ( sources, options? ) {
		let cfg := new Config( raw: {}, _layers: [] );
		for ( let source in ( sources instanceof Array ? sources : [ sources ] ) ) {
			cfg.load_file( source, options );
		}
		return cfg;
	}

	method source () {
		return _source;
	}

	method format () {
		return _format;
	}

	method layers () {
		return _layers;
	}

	method to_data () {
		return self.raw;
	}

	method clone () {
		let cloned := new Config( raw: _merge_values( {}, self.raw, {} ) );
		cloned._layers := _layers.to_Array();
		cloned._source := _source;
		cloned._format := _format;
		return cloned;
	}

	method _delegate_node () {
		return Node.from_root( self.raw );
	}

	method type () {
		return self._delegate_node().type();
	}

	method can_have_named_children () {
		return self._delegate_node().can_have_named_children();
	}

	method can_have_indexed_children () {
		return self._delegate_node().can_have_indexed_children();
	}

	method can_have_named_indexed_children () {
		return self._delegate_node().can_have_named_indexed_children();
	}

	method children () {
		let out := [];
		for ( let child in self._delegate_node().children() ) {
			out.push(
				Node.wrap(
					child.raw(),
					self,
					child.key(),
					child.ix(),
				),
			);
		}
		return out;
	}

	method attributes () {
		let out := [];
		for ( let child in self._delegate_node().attributes() ) {
			out.push(
				Node.wrap(
					child.raw(),
					self,
					child.key(),
					child.ix(),
				),
			);
		}
		return out;
	}

	method do_action_on_child ( child, action ) {
		return super( child, action ) if action{op} ne ":=";

		let container := self.raw;
		if ( container instanceof Dict ) {
			let key := child.key();
			die "Path assignment expects string dict key" if key ≡ null;
			container{(key)} := action{value};
			return action{value};
		}
		if ( container instanceof Array ) {
			let ix := child.ix();
			die "Path assignment expects numeric array index" if ix ≡ null;
			container[ix] := action{value};
			return action{value};
		}
		if ( container instanceof PairList ) {
			let key := child.key();
			die "Path assignment expects string pairlist key" if key ≡ null;
			container.set( key, action{value} );
			return action{value};
		}
		return super( child, action );
	}

	method ref_on_child ( child ) {
		let container := self.raw;
		if ( container instanceof Dict ) {
			let key := child.key();
			die "Path assignment expects string dict key" if key ≡ null;
			return \ container{(key)};
		}
		if ( container instanceof Array ) {
			let ix := child.ix();
			die "Path assignment expects numeric array index" if ix ≡ null;
			return \ container[ix];
		}
		if ( container instanceof PairList ) {
			let key := child.key();
			die "Path assignment expects string pairlist key" if key ≡ null;
			return \ container{(key)};
		}
		return super(child);
	}

	method query ( pathish ) {
		return _compile_path(pathish).query(self);
	}

	method select ( pathish ) {
		return self.query(pathish);
	}

	method get_all ( pathish ) {
		return self.query(pathish);
	}

	method first ( pathish, fallback? ) {
		return _compile_path(pathish).first( self, fallback );
	}

	method get ( pathish, fallback? ) {
		return self.first( pathish, fallback );
	}

	method exists ( pathish ) {
		return _compile_path(pathish).exists(self);
	}

	method require ( pathish, message? ) {
		if ( self.exists(pathish) ) {
			return self.get(pathish);
		}
		die(
			message ?:
			`std/config required setting not found at '${pathish}'`
		);
	}

	method assign_first ( pathish, value, op := ":=", weak := false ) {
		return _compile_path(pathish).assign_first( self, value, op, weak );
	}

	method assign_all ( pathish, value, op := ":=", weak := false ) {
		return _compile_path(pathish).assign_all( self, value, op, weak );
	}

	method assign_maybe ( pathish, value, op := ":=", weak := false ) {
		return _compile_path(pathish).assign_maybe( self, value, op, weak );
	}

	method ref_first ( pathish ) {
		return _compile_path(pathish).ref_first(self);
	}

	method ref_all ( pathish ) {
		return _compile_path(pathish).ref_all(self);
	}

	method ref_maybe ( pathish ) {
		return _compile_path(pathish).ref_maybe(self);
	}

	method merge ( other, options? ) {
		let incoming := _unwrap_config_value(other);
		self.set_raw( _merge_values( self.raw, incoming, options ) );
		return self;
	}

	method overlay ( other, options? ) {
		return self.merge( other, options );
	}

	method merge_flat ( values, options? ) {
		return self if not( values instanceof Dict );

		let prefix := "" _ _opt( options, "prefix", "" );
		let separator := "" _ _opt( options, "separator", "__" );
		let downcase := _opt( options, "lowercase", false );

		for ( let key in values.keys() ) {
			let name := "" _ key;
			if ( prefix ≢ "" ) {
				next if substr( name, 0, length prefix ) ne prefix;
				name := substr( name, length prefix );
			}
			next if name ≡ "";

			let parts := [];
			for ( let part in split( name, separator ) ) {
				next if part ≡ "";
				parts.push( downcase ? lc(part) : part );
			}
			next if parts.length() = 0;

			self.set(
				"/" _ join( "/", parts ),
				_coerce_scalar_text( values.get(key), options ),
			);
		}

		return self;
	}

	method merge_env ( values, options? ) {
		return self.merge_flat( values, options );
	}

	method set ( pathish, value ) {
		let parts := _simple_path_parts(pathish);
		if ( parts.length() = 0 ) {
			self.set_raw(value);
			return value;
		}

		self.set_raw( _ensure_root_dict( self.raw ) );
		let cursor := self.raw;
		let i := 0;
		while ( i < parts.length() - 1 ) {
			let key := parts[i];
			if ( not cursor.exists(key) or cursor.get(key) ≡ null ) {
				cursor{(key)} := {};
			}
			else if ( not( cursor.get(key) instanceof Dict ) ) {
				die `std/config cannot create child path below non-Dict setting '${key}'`;
			}
			cursor := cursor.get(key);
			i++;
		}

		cursor{(parts[parts.length() - 1])} := value;
		return value;
	}

	method set_default ( pathish, value ) {
		if ( not self.exists(pathish) or self.get(pathish) ≡ null ) {
			return self.set( pathish, value );
		}
		return self.get(pathish);
	}

	method encode ( format?, options? ) {
		let chosen := _normalize_format(
			format ?: _format ?: "json"
		);
		return _codec_for_format( chosen, options ).encode( self.raw );
	}

	method save ( destination, options? ) {
		let path := _ensure_path_object(destination);
		let chosen := _normalize_format(
			_opt( options, "format", null ) ?:
			Config.detect_format( path, _format ?: "json" )
		);
		_codec_for_format( chosen, options ).dump( path, self.raw );
		return path;
	}

	method load_file ( source, options? ) {
		let path := _ensure_path_object(source);
		if ( _opt( options, "optional", false ) and not path.exists() ) {
			return self;
		}

		let chosen := _normalize_format(
			_opt( options, "format", null ) ?:
			Config.detect_format(path)
		);
		die `std/config could not determine format for '${path}'`
			if chosen ≡ null;

		let decoded := _codec_for_format( chosen, options ).load(path);
		self.merge( decoded, options );

		_source := path.to_String();
		_format := chosen;
		_layers.push(
			{
				source: _source,
				format: chosen,
			},
		);
		return self;
	}
}