-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathspacetime_config.rs
More file actions
3212 lines (2755 loc) · 110 KB
/
spacetime_config.rs
File metadata and controls
3212 lines (2755 loc) · 110 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
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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use anyhow::Context;
use clap::{ArgMatches, Command};
use path_clean::PathClean;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};
use thiserror::Error;
/// The filename for configuration
pub const CONFIG_FILENAME: &str = "spacetime.json";
/// Supported package managers for JavaScript/TypeScript projects
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PackageManager {
Npm,
Pnpm,
Yarn,
Bun,
}
impl fmt::Display for PackageManager {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
PackageManager::Npm => "npm",
PackageManager::Pnpm => "pnpm",
PackageManager::Yarn => "yarn",
PackageManager::Bun => "bun",
};
write!(f, "{s}")
}
}
impl PackageManager {
/// Get the command to run a dev script
pub fn run_dev_command(&self) -> &'static str {
match self {
PackageManager::Npm => "npm run dev",
PackageManager::Pnpm => "pnpm run dev",
PackageManager::Yarn => "yarn dev",
PackageManager::Bun => "bun run dev",
}
}
}
/// Errors that can occur when building or using CommandConfig
#[derive(Debug, Error)]
pub enum CommandConfigError {
#[error("The option `--{arg_name}` is defined in Clap, but not in the config. If this is intentional and the option shouldn't be available in the config, you can exclude it with the `CommandConfigBuilder::exclude` function")]
ClapArgNotDefined { arg_name: String },
#[error("Key '{config_name}' references clap argument '{clap_name}' which doesn't exist in the Command. If the config key should be different than the clap argument, use from_clap()")]
InvalidClapReference { config_name: String, clap_name: String },
#[error("Key '{config_name}' has alias '{alias}' which doesn't exist in the Command")]
InvalidAliasReference { config_name: String, alias: String },
#[error("Excluded key '{key}' doesn't exist in the clap Command")]
InvalidExclusion { key: String },
#[error("Config key '{config_key}' is not supported in the config file. Available keys: {available_keys}")]
UnsupportedConfigKey { config_key: String, available_keys: String },
#[error("Required key '{key}' is missing from the config file or CLI")]
MissingRequiredKey { key: String },
#[error("Failed to convert config value for key '{key}' to type {target_type}")]
ConversionError {
key: String,
target_type: String,
#[source]
source: anyhow::Error,
},
}
/// Project configuration loaded from spacetime.json.
///
/// The root object IS a database entity. `generate` is per-database
/// (inherited by children), and `dev` is root-only.
///
/// Example (simple):
/// ```json
/// {
/// "database": "my-database",
/// "server": "local",
/// "module-path": "./server",
/// "dev": { "run": "pnpm dev" },
/// "generate": [
/// { "language": "typescript", "out-dir": "./src/module_bindings" }
/// ]
/// }
/// ```
///
/// Example (multi-database):
/// ```json
/// {
/// "server": "local",
/// "module-path": "./server",
/// "children": [
/// { "database": "region-1" },
/// { "database": "region-2", "module-path": "./region-server" }
/// ]
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "kebab-case")]
pub struct SpacetimeConfig {
/// Configuration for the dev command. Root-level only, not inherited.
#[serde(skip_serializing_if = "Option::is_none")]
pub dev: Option<DevConfig>,
/// Per-database generate entries. Inherited by children unless overridden.
#[serde(skip_serializing_if = "Option::is_none")]
pub generate: Option<Vec<HashMap<String, Value>>>,
/// Child database entities.
#[serde(skip_serializing_if = "Option::is_none")]
pub children: Option<Vec<SpacetimeConfig>>,
/// Name of the config file from which this target's `database` value was merged.
#[serde(rename = "_source-config", skip_serializing)]
pub source_config: Option<String>,
/// All other entity-level fields (database, module-path, server, etc.)
#[serde(flatten)]
pub additional_fields: HashMap<String, Value>,
}
/// Configuration for `spacetime dev` command.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct DevConfig {
/// The command to run the client development server.
/// This is used by `spacetime dev` to start the client after publishing.
/// Example: "npm run dev", "pnpm dev", "cargo run"
#[serde(skip_serializing_if = "Option::is_none")]
pub run: Option<String>,
}
/// A fully resolved database target after inheritance.
/// Contains all fields needed for both publish and generate operations.
#[derive(Debug, Clone)]
pub struct FlatTarget {
/// All entity-level fields (database, module-path, server, etc.)
pub fields: HashMap<String, Value>,
/// Name of the config file from which this target's `database` value was merged.
pub source_config: Option<String>,
/// Generate entries for this target (inherited or overridden)
pub generate: Option<Vec<HashMap<String, Value>>>,
}
/// Result of loading config from one or more files.
pub struct LoadedConfig {
pub config: SpacetimeConfig,
pub config_dir: PathBuf,
/// Which files contributed to this config
pub loaded_files: Vec<PathBuf>,
/// Whether a dev-specific file (spacetime.dev.json or spacetime.dev.local.json) was loaded
pub has_dev_file: bool,
}
impl SpacetimeConfig {
/// Collect all database targets with parent→child inheritance.
/// Children inherit unset `additional_fields` from their parent.
/// `dev`, `generate`, and `children` are NOT propagated to child targets.
/// Returns `Vec<FlatTarget>` with fully resolved fields.
pub fn collect_all_targets_with_inheritance(&self) -> Vec<FlatTarget> {
self.collect_targets_inner(None)
}
fn collect_targets_inner(&self, parent_fields: Option<&HashMap<String, Value>>) -> Vec<FlatTarget> {
// module-path, bin-path, and js-path are mutually exclusive module sources.
// If a child specifies any one, the other two are not inherited from the parent.
const MODULE_SOURCE_KEYS: &[&str] = &["module-path", "bin-path", "js-path"];
let child_specifies_source = MODULE_SOURCE_KEYS
.iter()
.any(|k| self.additional_fields.contains_key(*k));
// Build this node's fields by inheriting from parent
let mut fields = self.additional_fields.clone();
if let Some(parent) = parent_fields {
for (key, value) in parent {
if fields.contains_key(key) {
continue;
}
// If the child specifies any module source, skip inheriting the others
if child_specifies_source && MODULE_SOURCE_KEYS.contains(&key.as_str()) {
continue;
}
fields.insert(key.clone(), value.clone());
}
}
// Generate is never inherited. It is tied to a specific module and output location:
// inheriting is redundant when the child shares the parent's module (deduplication
// handles it) and dangerous when the child uses a different module (two modules
// would write bindings to the same output directory).
let effective_generate = self.generate.clone();
let target = FlatTarget {
fields: fields.clone(),
source_config: self.source_config.clone(),
generate: effective_generate,
};
let mut result = vec![target];
if let Some(children) = &self.children {
for child in children {
let child_targets = child.collect_targets_inner(Some(&fields));
result.extend(child_targets);
}
}
result
}
/// Iterate through all database targets (self + children recursively).
/// Note: Does NOT apply parent→child inheritance. Use
/// `collect_all_targets_with_inheritance()` for that.
pub fn iter_all_targets(&self) -> Box<dyn Iterator<Item = &SpacetimeConfig> + '_> {
Box::new(
std::iter::once(self).chain(
self.children
.iter()
.flat_map(|children| children.iter())
.flat_map(|child| child.iter_all_targets()),
),
)
}
/// Count total number of targets (self + all descendants)
pub fn count_targets(&self) -> usize {
1 + self
.children
.as_ref()
.map(|children| children.iter().map(|child| child.count_targets()).sum())
.unwrap_or(0)
}
}
/// A unified config that merges clap arguments with config file values.
/// Provides a `get_one::<T>(key)` interface similar to clap's ArgMatches.
/// CLI arguments take precedence over config file values.
#[derive(Debug)]
pub struct CommandConfig<'a> {
/// Schema defining the contract between CLI and config
schema: &'a CommandSchema,
/// Config file values
config_values: HashMap<String, Value>,
/// CLI arguments
matches: &'a ArgMatches,
}
/// Schema that defines the contract between CLI arguments and config file keys.
/// Does not hold ArgMatches - methods take matches as a parameter instead.
#[derive(Debug)]
pub struct CommandSchema {
/// Key definitions
keys: Vec<Key>,
/// Map from config name to clap arg name (for from_clap mapping)
config_to_clap: HashMap<String, String>,
/// Map from config name to alias (for alias mapping)
config_to_alias: HashMap<String, String>,
}
/// Builder for creating a CommandSchema with custom mappings and exclusions.
pub struct CommandSchemaBuilder {
/// Keys defined for this command
keys: Vec<Key>,
/// Set of keys to exclude from being read from the config file
excluded_keys: HashSet<String>,
}
impl CommandSchemaBuilder {
pub fn new() -> Self {
Self {
keys: Vec::new(),
excluded_keys: HashSet::new(),
}
}
/// Add a key definition to the builder.
/// Example: `.key(Key::new("server"))`
pub fn key(mut self, key: Key) -> Self {
self.keys.push(key);
self
}
/// Exclude a key from being read from the config file.
/// This is useful for keys that should only come from CLI arguments.
pub fn exclude(mut self, key: impl Into<String>) -> Self {
self.excluded_keys.insert(key.into());
self
}
/// Build a CommandSchema by validating against the clap Command.
///
/// # Arguments
/// * `command` - The clap Command to validate against
pub fn build(self, command: &Command) -> Result<CommandSchema, CommandConfigError> {
// Collect all clap argument names for validation
let clap_arg_names: HashSet<String> = command
.get_arguments()
.map(|arg| arg.get_id().as_str().to_string())
.collect();
// Check that all the defined keys exist in clap
for key in &self.keys {
if !clap_arg_names.contains(key.clap_arg_name()) {
return Err(CommandConfigError::InvalidClapReference {
config_name: key.config_name().to_string(),
clap_name: key.clap_arg_name().to_string(),
});
}
// Validate alias if present
if let Some(alias) = &key.clap_alias
&& !clap_arg_names.contains(alias)
{
return Err(CommandConfigError::InvalidAliasReference {
config_name: key.config_name().to_string(),
alias: alias.clone(),
});
}
}
// Validate exclusions reference valid clap arguments
for excluded_key in &self.excluded_keys {
if !clap_arg_names.contains(excluded_key) {
return Err(CommandConfigError::InvalidExclusion {
key: excluded_key.clone(),
});
}
}
// A list of clap args that are referenced by the config keys
let mut referenced_clap_args = HashSet::new();
let mut config_to_clap_map = HashMap::new();
let mut config_to_alias_map = HashMap::new();
for key in &self.keys {
let config_name = key.config_name().to_string();
let clap_name = key.clap_arg_name().to_string();
referenced_clap_args.insert(clap_name.clone());
// Track the mapping from config name to clap arg name (if using from_clap)
if key.clap_name.is_some() {
config_to_clap_map.insert(config_name.clone(), clap_name.clone());
}
// Register the alias if present
if let Some(alias) = &key.clap_alias {
referenced_clap_args.insert(alias.clone());
config_to_alias_map.insert(config_name.clone(), alias.clone());
}
}
// Check that all clap arguments are either referenced or excluded
for arg in command.get_arguments() {
let arg_name = arg.get_id().as_str();
// Skip clap's built-in arguments
if arg_name == "help" || arg_name == "version" {
continue;
}
if !referenced_clap_args.contains(arg_name) && !self.excluded_keys.contains(arg_name) {
return Err(CommandConfigError::ClapArgNotDefined {
arg_name: arg_name.to_string(),
});
}
}
Ok(CommandSchema {
keys: self.keys,
config_to_clap: config_to_clap_map,
config_to_alias: config_to_alias_map,
})
}
}
impl Default for CommandSchemaBuilder {
fn default() -> Self {
Self::new()
}
}
impl CommandSchema {
/// Get a value from clap arguments only (not from config).
/// Useful for filtering or checking if a value was provided via CLI.
pub fn get_clap_arg<T: Clone + Send + Sync + 'static>(
&self,
matches: &ArgMatches,
config_name: &str,
) -> Result<Option<T>, CommandConfigError> {
// Check clap with mapped name (if from_clap was used, use that name, otherwise use config name)
let clap_name = self
.config_to_clap
.get(config_name)
.map(|s| s.as_str())
.unwrap_or(config_name);
// Only return the value if it was actually provided by the user, not from defaults
if let Some(source) = matches.value_source(clap_name)
&& source == clap::parser::ValueSource::CommandLine
&& let Some(value) = matches.get_one::<T>(clap_name)
{
return Ok(Some(value.clone()));
}
// Try clap with the alias if it exists
if let Some(alias) = self.config_to_alias.get(config_name)
&& let Some(source) = matches.value_source(alias)
&& source == clap::parser::ValueSource::CommandLine
&& let Some(value) = matches.get_one::<T>(alias)
{
return Ok(Some(value.clone()));
}
Ok(None)
}
/// Check if a value was provided via CLI (not from config).
/// Only returns true if the user explicitly provided the value, not if it came from a default.
pub fn is_from_cli(&self, matches: &ArgMatches, config_name: &str) -> bool {
// Check clap with mapped name
let clap_name = self
.config_to_clap
.get(config_name)
.map(|s| s.as_str())
.unwrap_or(config_name);
// Use value_source to check if the value was actually provided by the user
if let Some(source) = matches.value_source(clap_name)
&& source == clap::parser::ValueSource::CommandLine
{
return true;
}
// Check clap with alias
if let Some(alias) = self.config_to_alias.get(config_name)
&& let Some(source) = matches.value_source(alias)
&& source == clap::parser::ValueSource::CommandLine
{
return true;
}
false
}
/// Get all module-specific keys that were provided via CLI.
pub fn module_specific_cli_args(&self, matches: &ArgMatches) -> Vec<&str> {
self.keys
.iter()
.filter(|k| k.module_specific && self.is_from_cli(matches, k.config_name()))
.map(|k| k.config_name())
.collect()
}
/// Get user-facing CLI flags (e.g. `--bin-path`) for all module-specific options
/// that were explicitly provided via CLI.
pub fn module_specific_cli_flags(&self, command: &Command, matches: &ArgMatches) -> Vec<String> {
self.module_specific_cli_args(matches)
.iter()
.map(|arg| {
let clap_name = self.clap_arg_name_for(arg);
command
.get_arguments()
.find(|a| a.get_id().as_str() == clap_name)
.and_then(|a| a.get_long())
.map(|long| format!("--{long}"))
.unwrap_or_else(|| format!("--{}", clap_name.replace('_', "-")))
})
.collect()
}
/// Validate that module-specific CLI flags are not used when operating on multiple targets.
pub fn validate_no_module_specific_cli_args_for_multiple_targets(
&self,
command: &Command,
matches: &ArgMatches,
target_count: usize,
operation_context: &str,
resolution_hint: &str,
) -> anyhow::Result<()> {
if target_count <= 1 {
return Ok(());
}
let display_args = self.module_specific_cli_flags(command, matches);
if display_args.is_empty() {
return Ok(());
}
anyhow::bail!(
"Cannot use module-specific arguments ({}) when {}. {}",
display_args.join(", "),
operation_context,
resolution_hint
);
}
/// Get all generate-entry-specific keys that were provided via CLI.
pub fn generate_entry_specific_cli_args(&self, matches: &ArgMatches) -> Vec<&str> {
self.keys
.iter()
.filter(|k| k.generate_entry_specific && self.is_from_cli(matches, k.config_name()))
.map(|k| k.config_name())
.collect()
}
/// Get user-facing CLI flags for generate-entry-specific options provided via CLI.
pub fn generate_entry_specific_cli_flags(&self, command: &Command, matches: &ArgMatches) -> Vec<String> {
self.generate_entry_specific_cli_args(matches)
.iter()
.map(|arg| {
let clap_name = self.clap_arg_name_for(arg);
command
.get_arguments()
.find(|a| a.get_id().as_str() == clap_name)
.and_then(|a| a.get_long())
.map(|long| format!("--{long}"))
.unwrap_or_else(|| format!("--{}", clap_name.replace('_', "-")))
})
.collect()
}
/// Validate that generate-entry-specific CLI flags are not used when operating on multiple generate entries.
pub fn validate_no_generate_entry_specific_cli_args(
&self,
command: &Command,
matches: &ArgMatches,
entry_count: usize,
) -> anyhow::Result<()> {
if entry_count <= 1 {
return Ok(());
}
let display_args = self.generate_entry_specific_cli_flags(command, matches);
if display_args.is_empty() {
return Ok(());
}
anyhow::bail!(
"Cannot use generate-entry-specific arguments ({}) when generating for multiple entries. \
Specify a database name to select a single target, or remove these arguments.",
display_args.join(", "),
);
}
/// Get the clap argument name for a config key.
pub fn clap_arg_name_for<'a>(&'a self, config_name: &'a str) -> &'a str {
self.config_to_clap
.get(config_name)
.map(|s| s.as_str())
.unwrap_or(config_name)
}
}
/// Configuration for a single key in the CommandConfig.
#[derive(Debug, Clone)]
pub struct Key {
/// The key name in the config file (e.g., "module-path")
config_name: String,
/// The corresponding clap argument name (e.g., "project-path"), if different
clap_name: Option<String>,
/// Alias for a clap argument, useful for example if we have to deprecate a clap
/// argument and still allow to use it in the CLI args, but not in the config file
clap_alias: Option<String>,
/// Whether this key is module-specific (per-database)
module_specific: bool,
/// Whether this key is generate-entry-specific (per-generate-entry within a database)
generate_entry_specific: bool,
/// Whether this key is required in the config file
required: bool,
}
impl Key {
/// Returns a new Key instance
pub fn new(name: impl Into<String>) -> Self {
Self {
config_name: name.into(),
clap_name: None,
clap_alias: None,
module_specific: false,
generate_entry_specific: false,
required: false,
}
}
/// Map this config key to a different clap argument name. When fetching values
/// the key that is defined should be used.
/// Example: Key::new("module-path").from_clap("project-path")
/// - in this case the value for either project-path in clap or
/// for module-path in the config file will be fetched
pub fn from_clap(mut self, clap_arg_name: impl Into<String>) -> Self {
self.clap_name = Some(clap_arg_name.into());
self
}
/// Add an alias for a clap argument name that also maps to this key.
/// This is useful for backwards compatibility when renaming arguments.
/// Example: Key::new("module-path").alias("project-path")
///
/// This allows both --module-path and --project-path to map to the same config key.
/// The value should then be accessed by using `module-path`
///
/// The difference between from_clap and alias is that from_clap will work by mapping
/// a single value from clap, whereas alias will check both of them in the CLI args
pub fn alias(mut self, alias_name: impl Into<String>) -> Self {
self.clap_alias = Some(alias_name.into());
self
}
/// Mark this key as module-specific. For example, the `js-bin` config option makes sense
/// only when applied to a single module. The `server` config option makes sense for
/// multiple publish targets
pub fn module_specific(mut self) -> Self {
self.module_specific = true;
self
}
/// Mark this key as generate-entry-specific. These keys (like `language`, `out_dir`)
/// only make sense when a single generate entry is targeted. If multiple generate
/// entries exist and this key is provided via CLI, it's an error.
pub fn generate_entry_specific(mut self) -> Self {
self.generate_entry_specific = true;
self
}
/// Mark this key as required in the config file. If a config file is provided but
/// this key is missing, an error will be returned.
pub fn required(mut self) -> Self {
self.required = true;
self
}
/// Get the clap argument name (either the mapped name or the config name)
pub fn clap_arg_name(&self) -> &str {
self.clap_name.as_deref().unwrap_or(&self.config_name)
}
/// Get the config name
pub fn config_name(&self) -> &str {
&self.config_name
}
/// Check if this key is required
pub fn is_required(&self) -> bool {
self.required
}
}
impl<'a> CommandConfig<'a> {
/// Create a new CommandConfig by validating config values against a schema.
///
/// # Arguments
/// * `schema` - The command schema that defines valid keys and types
/// * `config_values` - Values from the config file
/// * `matches` - CLI arguments
///
/// # Errors
/// Returns an error if any config keys are not defined in the schema.
/// Note: Required key validation happens when get_one() is called, not during construction.
pub fn new(
schema: &'a CommandSchema,
config_values: HashMap<String, Value>,
matches: &'a ArgMatches,
) -> Result<Self, CommandConfigError> {
// Normalize keys from kebab-case to snake_case to match clap's Arg::new() convention
let normalized_values: HashMap<String, Value> = config_values
.into_iter()
.map(|(k, v)| (k.replace('-', "_"), v))
.collect();
// Build set of valid config keys from schema
let valid_config_keys: HashSet<String> = schema.keys.iter().map(|k| k.config_name().to_string()).collect();
// Check that all keys in config file are defined in schema
for config_key in normalized_values.keys() {
if !valid_config_keys.contains(config_key) {
return Err(CommandConfigError::UnsupportedConfigKey {
config_key: config_key.clone(),
available_keys: valid_config_keys
.iter()
.map(|s| s.as_str())
.collect::<Vec<_>>()
.join(", "),
});
}
}
Ok(CommandConfig {
schema,
config_values: normalized_values,
matches,
})
}
/// Get a single value from the config as a specific type.
/// First checks clap args (via schema), then falls back to config values.
///
/// Returns:
/// - Ok(Some(T)) if the value exists and can be converted
/// - Ok(None) if the value doesn't exist in either clap or config
/// - Err if conversion fails
pub fn get_one<T: Clone + Send + Sync + serde::de::DeserializeOwned + 'static>(
&self,
key: &str,
) -> Result<Option<T>, CommandConfigError> {
// Try clap arguments first (CLI takes precedence) via schema
let from_cli = self.schema.get_clap_arg::<T>(self.matches, key)?;
if let Some(ref value) = from_cli {
return Ok(Some(value.clone()));
}
// Fall back to config values using the config name
if let Some(value) = self.config_values.get(key) {
serde_json::from_value::<T>(value.clone())
.map_err(|e| CommandConfigError::ConversionError {
key: key.to_string(),
target_type: std::any::type_name::<T>().to_string(),
source: e.into(),
})
.map(Some)
} else {
Ok(None)
}
}
/// Get a config value (from config file only, not merged with CLI).
///
/// This is useful for filtering scenarios where you need to compare
/// CLI values against config file values.
pub fn get_config_value(&self, key: &str) -> Option<&Value> {
self.config_values.get(key)
}
/// Get a path value and resolve it against `config_dir` if it came from config (not CLI).
pub fn get_resolved_path(
&self,
key: &str,
config_dir: Option<&Path>,
) -> Result<Option<PathBuf>, CommandConfigError> {
let path = self.get_one::<PathBuf>(key)?;
let from_cli = self.is_from_cli(key);
Ok(path.map(|p| {
let resolved = if p.is_absolute() || from_cli {
p
} else if let Some(base_dir) = config_dir {
base_dir.join(p)
} else {
p
};
resolved.clean()
}))
}
/// Returns true when this key was explicitly provided via CLI.
pub fn is_from_cli(&self, key: &str) -> bool {
self.schema.is_from_cli(self.matches, key)
}
/// Validate that all required keys are present in either config or CLI.
pub fn validate(&self) -> Result<(), CommandConfigError> {
for key in &self.schema.keys {
if key.is_required()
&& !self.config_values.contains_key(key.config_name())
&& !self.schema.is_from_cli(self.matches, key.config_name())
{
return Err(CommandConfigError::MissingRequiredKey {
key: key.config_name().to_string(),
});
}
}
Ok(())
}
}
impl SpacetimeConfig {
/// Find and load a spacetime.json file (convenience wrapper for no env).
///
/// Searches for spacetime.json starting from the current directory
/// and walking up the directory tree until found or filesystem root is reached.
///
/// Returns `Ok(Some((path, config)))` if found and successfully parsed.
/// Returns `Ok(None)` if not found.
/// Returns `Err` if found but failed to parse.
pub fn find_and_load() -> anyhow::Result<Option<(PathBuf, Self)>> {
Self::find_and_load_from(std::env::current_dir()?)
}
/// Find and load a spacetime.json file starting from a specific directory.
///
/// Searches for spacetime.json starting from `start_dir`
/// and walking up the directory tree until found or filesystem root is reached.
pub fn find_and_load_from(start_dir: PathBuf) -> anyhow::Result<Option<(PathBuf, Self)>> {
Ok(find_and_load_with_env_from(None, start_dir)?.map(|loaded| {
let config_path = loaded.config_dir.join(CONFIG_FILENAME);
(config_path, loaded.config)
}))
}
/// Load a spacetime.json file from a specific path.
///
/// The file must exist and be valid JSON5 format (supports comments).
pub fn load(path: &Path) -> anyhow::Result<Self> {
let content =
std::fs::read_to_string(path).with_context(|| format!("Failed to read config file: {}", path.display()))?;
let config: Self = json5::from_str(&content)
.map_err(|e| anyhow::anyhow!("Failed to parse config file {}: {}", path.display(), e))?;
Ok(config)
}
/// Save the config to a file.
///
/// The config will be serialized as pretty-printed JSON.
pub fn save(&self, path: &Path) -> anyhow::Result<()> {
let json = serde_json::to_string_pretty(self).context("Failed to serialize config")?;
std::fs::write(path, json).with_context(|| format!("Failed to write config file: {}", path.display()))?;
Ok(())
}
/// Create a spacetime.json file in the current directory with the given config.
pub fn create_in_current_dir(&self) -> anyhow::Result<PathBuf> {
let config_path = std::env::current_dir()?.join("spacetime.json");
self.save(&config_path)?;
Ok(config_path)
}
/// Create a configuration with a run command for dev
pub fn with_run_command(run_command: impl Into<String>) -> Self {
Self {
dev: Some(DevConfig {
run: Some(run_command.into()),
}),
..Default::default()
}
}
/// Create a configuration for a specific client language.
/// Determines the appropriate run command based on the language and package manager.
pub fn for_client_lang(client_lang: &str, package_manager: Option<PackageManager>) -> Self {
let run_command = match client_lang.to_lowercase().as_str() {
"typescript" => package_manager.map(|pm| pm.run_dev_command()).unwrap_or("npm run dev"),
"rust" => "cargo run",
"csharp" | "c#" => "dotnet run",
_ => "npm run dev", // default fallback
};
Self {
dev: Some(DevConfig {
run: Some(run_command.to_string()),
}),
..Default::default()
}
}
/// Load configuration from a directory.
/// Returns `None` if no config file exists.
pub fn load_from_dir(dir: &Path) -> anyhow::Result<Option<Self>> {
let config_path = dir.join(CONFIG_FILENAME);
if config_path.exists() {
Self::load(&config_path).map(Some)
} else {
Ok(None)
}
}
/// Save configuration to `spacetime.json` in the specified directory.
pub fn save_to_dir(&self, dir: &Path) -> anyhow::Result<PathBuf> {
let path = dir.join(CONFIG_FILENAME);
self.save(&path)?;
Ok(path)
}
}
/// Find the config directory by walking up from start_dir looking for spacetime.json.
fn find_config_dir(start_dir: PathBuf) -> Option<PathBuf> {
let mut current_dir = start_dir;
loop {
let config_path = current_dir.join("spacetime.json");
if config_path.exists() {
return Some(current_dir);
}
if !current_dir.pop() {
break;
}
}
None
}
/// Load a JSON5 file as a serde_json::Value, or None if the file doesn't exist.
fn load_json_value(path: &Path) -> anyhow::Result<Option<serde_json::Value>> {
if !path.exists() {
return Ok(None);
}
let content =
std::fs::read_to_string(path).with_context(|| format!("Failed to read config file: {}", path.display()))?;
// In one of the releases we mistakenly save _source-config field into the JSON file
// Check if the field exists and remove it. We use text-based removal to preserve
// comments and formatting since json5 crate doesn't support serialization.
remove_source_config_from_text(path, &content);
let value: serde_json::Value = json5::from_str(&content)
.map_err(|e| anyhow::anyhow!("Failed to parse config file {}: {}", path.display(), e))?;
Ok(Some(value))
}
const SOURCE_CONFIG_KEY: &str = "_source-config";
/// Remove _source-config field from JSON text using regex
/// This preserves comments and formatting in the file
fn remove_source_config_from_text(path: &Path, content: &str) {
if !content.contains(SOURCE_CONFIG_KEY) {
return;
}
use regex::Regex;
// Match "_source-config": "value", or "_source-config": "value"
// Handles trailing comma and various whitespace patterns
let re = Regex::new(r#"(?m)^\s*"_source-config"\s*:\s*"[^"]*"\s*,?\s*$\n?"#).unwrap();
let cleaned = re.replace_all(content, "");
// Also remove trailing commas that might be left behind before closing braces
let re_trailing = Regex::new(r#"(?m),(\s*[\]}])"#).unwrap();
let cleaned_content = re_trailing.replace_all(&cleaned, "$1").to_string();
// Validate that the cleaned content is still valid JSON5
// If validation fails, don't save
if json5::from_str::<serde_json::Value>(&cleaned_content).is_err() {
return;
}
// Write the cleaned content back to the file (best effort, ignore errors)
let _ = std::fs::write(path, &cleaned_content);
}
fn mark_source_config(value: &mut serde_json::Value, source_file_name: &str) {
if let Some(obj) = value.as_object_mut() {
if obj.contains_key("database") {
obj.insert(
SOURCE_CONFIG_KEY.to_string(),
serde_json::Value::String(source_file_name.to_string()),
);
}
if let Some(serde_json::Value::Array(children)) = obj.get_mut("children") {
for child in children {
mark_source_config(child, source_file_name);
}
}
}
}
fn overlay_children_arrays(
base_children: &mut [serde_json::Value],
overlay_children: Vec<serde_json::Value>,
source_file_name: &str,
) {
let merge_len = std::cmp::min(base_children.len(), overlay_children.len());
for (idx, overlay_child) in overlay_children.into_iter().enumerate().take(merge_len) {
let base_child = &mut base_children[idx];
match overlay_child {
serde_json::Value::Object(_) if base_child.is_object() => {
// Recursively apply overlay semantics to child objects.
overlay_json(base_child, overlay_child, source_file_name);
}
other => {
// For non-object child entries, replace value directly.
*base_child = other;
}
}
}
}
/// Overlay `overlay` values onto `base`.
/// Most keys use top-level replacement. `children` is merged recursively by index,
/// up to the lower of base/overlay lengths.
fn overlay_json(base: &mut serde_json::Value, mut overlay: serde_json::Value, source_file_name: &str) {
mark_source_config(&mut overlay, source_file_name);
if let (Some(base_obj), Some(overlay_obj)) = (base.as_object_mut(), overlay.as_object()) {
for (key, value) in overlay_obj {
let value_owned = value.clone();
if key == "children" {
match (base_obj.get_mut("children"), value_owned) {
(Some(serde_json::Value::Array(base_children)), serde_json::Value::Array(overlay_children)) => {
overlay_children_arrays(base_children, overlay_children, source_file_name);
}
(_, other) => {
base_obj.insert(key.clone(), other);