-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathdev.rs
More file actions
2100 lines (1883 loc) · 77 KB
/
dev.rs
File metadata and controls
2100 lines (1883 loc) · 77 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 crate::common_args::ClearMode;
use crate::config::Config;
use crate::generate::Language;
use crate::spacetime_config::{
detect_client_command, find_and_load_with_env_from, CommandConfig, CommandSchema, SpacetimeConfig, CONFIG_FILENAME,
};
use crate::subcommands::init;
use crate::util::{
add_auth_header_opt, database_identity, find_module_path, get_auth_header, get_login_token_or_log_in,
spacetime_reverse_dns, strip_verbatim_prefix, ResponseExt,
};
use crate::{common_args, generate};
use crate::{publish, tasks};
use anyhow::Context;
use clap::parser::ValueSource;
use clap::{Arg, ArgMatches, Command};
use colored::Colorize;
use dialoguer::{theme::ColorfulTheme, Confirm, FuzzySelect, Input};
use futures::stream::{self, StreamExt};
use futures::{AsyncBufReadExt, TryStreamExt};
use ignore::gitignore::{Gitignore, GitignoreBuilder};
use indicatif::{ProgressBar, ProgressStyle};
use notify::{Event, RecommendedWatcher, RecursiveMode, Watcher};
use regex::Regex;
use serde::Deserialize;
use serde_json::json;
use std::borrow::Cow;
use std::collections::HashMap;
use std::fs;
use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use std::sync::mpsc::channel;
use std::time::Duration;
use tabled::{
settings::{object::Columns, Alignment, Modify, Style},
Table, Tabled,
};
use termcolor::{Color, ColorSpec, WriteColor};
use tokio::process::{Child, Command as TokioCommand};
use tokio::task::JoinHandle;
use tokio::time::sleep;
pub fn cli() -> Command {
Command::new("dev")
.about("Start development mode with auto-regenerate client module bindings, auto-rebuild, and auto-publish on file changes.")
.arg(
Arg::new("database")
.help("The database name/identity to publish to (optional, will prompt if not provided)"),
)
// Deprecated: --database flag for backwards compatibility
.arg(
Arg::new("database-flag")
.long("database")
.hide(true)
.help("DEPRECATED: Use positional argument instead"),
)
.arg(
Arg::new("project-path")
.long("project-path")
.value_parser(clap::value_parser!(PathBuf))
.default_value(".")
.help("The path to the project directory"),
)
.arg(
Arg::new("module-bindings-path")
.long("module-bindings-path")
.value_parser(clap::value_parser!(PathBuf))
.default_value("src/module_bindings")
.help("The path to the module bindings directory relative to the project directory, defaults to `<project-path>/src/module_bindings`"),
)
// NOTE: All server templates must have their server code in `spacetimedb/` directory
// This is not a requirement in general, but is a requirement for all templates
// i.e. `spacetime dev` is valid on non-templates.
.arg(
Arg::new("module-path")
.long("module-path")
.value_parser(clap::value_parser!(PathBuf))
.help("Path to the SpacetimeDB server module, relative to current directory. Defaults to `<project-path>/spacetimedb`."),
)
.arg(
Arg::new("client-lang")
.long("client-lang")
.value_parser(clap::value_parser!(Language))
.help("The programming language for the generated client module bindings (e.g., typescript, csharp, rust, unrealcpp). If not specified, it will be detected from the project."),
)
.arg(common_args::server().help("The nickname, host name or URL of the server to publish to"))
.arg(common_args::yes())
.arg(common_args::clear_database())
.arg(
Arg::new("template")
.short('t')
.long("template")
.value_name("TEMPLATE")
.help("Template ID or GitHub repository (owner/repo or URL) for project initialization"),
)
.arg(
Arg::new("run")
.long("run")
.value_name("COMMAND")
.help("Command to run the client development server (overrides spacetime.json config)"),
)
.arg(
Arg::new("server-only")
.long("server-only")
.action(clap::ArgAction::SetTrue)
.help("Only run the server (module) without starting the client"),
)
.arg(
Arg::new("no_config")
.long("no-config")
.action(clap::ArgAction::SetTrue)
.help("Ignore spacetime.json configuration"),
)
.arg(
Arg::new("env")
.long("env")
.value_name("ENV")
.help("Environment name for config file layering (e.g., dev, staging). Defaults to 'dev'."),
)
.arg(
Arg::new("skip_publish")
.long("skip-publish")
.action(clap::ArgAction::SetTrue)
.help("Skip the publish step"),
)
.arg(
Arg::new("skip_generate")
.long("skip-generate")
.action(clap::ArgAction::SetTrue)
.help("Skip the generate step"),
)
}
#[derive(Deserialize)]
struct DatabasesResult {
pub identities: Vec<String>,
}
#[derive(Tabled, Clone)]
struct DatabaseRow {
pub identity: String,
pub name: String,
}
pub async fn exec(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
let project_path = args.get_one::<PathBuf>("project-path").unwrap();
let module_path_from_cli = args.get_one::<PathBuf>("module-path");
let module_bindings_path = args.get_one::<PathBuf>("module-bindings-path").unwrap();
let client_language = args.get_one::<Language>("client-lang");
let clear_database = args
.get_one::<ClearMode>("clear-database")
.copied()
.unwrap_or(ClearMode::OnConflict);
let force = args.get_flag("force");
// If you don't specify a server, we default to your default server
// If you don't have one of those, we default to "maincloud"
let server_from_cli = args.get_one::<String>("server").map(|s| s.as_str());
let default_server_name = config.default_server_name().map(|s| s.to_string());
let mut resolved_server = server_from_cli
.or(default_server_name.as_deref())
.ok_or_else(|| anyhow::anyhow!("Server not specified and no default server configured."))?;
let cwd = std::env::current_dir()?;
let mut project_dir = if project_path.is_absolute() {
project_path.clone()
} else {
cwd.join(project_path)
};
if module_bindings_path.is_absolute() {
anyhow::bail!("Module bindings path must be a relative path");
}
let mut module_bindings_dir = project_dir.join(module_bindings_path);
let mut spacetimedb_dir = match module_path_from_cli {
Some(path) => {
if path.is_absolute() {
path.clone()
} else {
std::env::current_dir()?.join(path)
}
}
None => project_dir.join("spacetimedb"),
};
let no_config = args.get_flag("no_config");
let skip_publish = args.get_flag("skip_publish");
let skip_generate = args.get_flag("skip_generate");
// --env defaults to "dev" for spacetime dev
let env = args.get_one::<String>("env").map(|s| s.as_str()).unwrap_or("dev");
// Load spacetime.json config early so we can use it for determining project
// directories
let mut loaded_config = if no_config {
None
} else {
find_and_load_with_env_from(Some(env), project_dir.clone()).with_context(|| "Failed to load spacetime.json")?
};
// If config was found while starting from a subdirectory (for example from `spacetimedb/`),
// treat the config directory as the project root for all relative defaults.
if let Some(lc) = loaded_config.as_ref() {
project_dir = lc.config_dir.clone();
module_bindings_dir = project_dir.join(module_bindings_path);
if module_path_from_cli.is_none() {
spacetimedb_dir = project_dir.join("spacetimedb");
}
}
let has_any_config_files = loaded_config.is_some();
// Config exists, but default module dir is missing: recover by asking for module-path
// and persisting it on the root config.
if !no_config && has_any_config_files && (!spacetimedb_dir.exists() || !spacetimedb_dir.is_dir()) {
let merged_has_module_path = loaded_config
.as_ref()
.and_then(|lc| lc.config.additional_fields.get("module-path"))
.and_then(|v| v.as_str())
.is_some();
if !merged_has_module_path && module_path_from_cli.is_none() {
let files = loaded_config
.as_ref()
.map(|lc| {
lc.loaded_files
.iter()
.map(|f| strip_verbatim_prefix(f).display().to_string())
.collect::<Vec<_>>()
.join(", ")
})
.unwrap_or_else(|| "spacetime.json".to_string());
println!("{} {}", "Found config files:".yellow().bold(), files.dimmed());
println!(
"{}",
"Could not determine module path because no `module-path` was found and `./spacetimedb` does not exist."
.yellow()
);
let should_provide = Confirm::new()
.with_prompt("Would you like to provide --module-path now?")
.default(true)
.interact()?;
if !should_provide {
anyhow::bail!("Cannot continue without a module path.");
}
let config_dir = loaded_config
.as_ref()
.map(|lc| lc.config_dir.clone())
.ok_or_else(|| anyhow::anyhow!("Missing loaded config directory"))?;
let provided_module_path: String = Input::with_theme(&ColorfulTheme::default())
.with_prompt("Module path")
.default("spacetimedb".to_string())
.validate_with({
let config_dir = config_dir.clone();
move |input: &String| -> Result<(), String> {
let candidate = PathBuf::from(input);
let resolved = if candidate.is_absolute() {
candidate
} else {
config_dir.join(&candidate)
};
if resolved.exists() {
Ok(())
} else {
Err(format!(
"Path does not exist: {} (resolved to {})",
input,
resolved.display()
))
}
}
})
.interact_text()?;
// Save to root `spacetime.json` (not env/local overlays), then reload merged config.
let saved_path = save_root_module_path_to_spacetime_json(&config_dir, &provided_module_path)?;
println!(
"{} Updated {}",
"✓".green(),
strip_verbatim_prefix(&saved_path).display()
);
loaded_config = find_and_load_with_env_from(Some(env), project_dir.clone())
.with_context(|| "Failed to reload spacetime.json after updating module-path")?;
}
}
// If config has a module-path and CLI didn't provide one, resolve spacetimedb_dir from it.
// This handles the case where spacetime.json specifies module-path but has no publish targets.
if module_path_from_cli.is_none()
&& let Some(config_module_path) = loaded_config
.as_ref()
.and_then(|lc| lc.config.additional_fields.get("module-path"))
.and_then(|v| v.as_str())
{
let p = PathBuf::from(config_module_path);
spacetimedb_dir = if p.is_absolute() { p } else { project_dir.join(p) };
}
let spacetime_config = loaded_config.as_ref().map(|lc| &lc.config);
// A config has publish targets if it has a "database" field or children
let has_publish_targets_in_config = spacetime_config
.map(|c| c.additional_fields.contains_key("database") || c.children.is_some())
.unwrap_or(false);
let has_generate_targets_in_config = spacetime_config
.and_then(|c| c.generate.as_ref())
.map(|g| !g.is_empty())
.unwrap_or(false);
let module_path_from_cli_flag = args.value_source("module-path") == Some(ValueSource::CommandLine);
let project_path_from_cli_flag = args.value_source("project-path") == Some(ValueSource::CommandLine);
let module_bindings_path_from_cli_flag =
args.value_source("module-bindings-path") == Some(ValueSource::CommandLine);
if has_publish_targets_in_config && module_path_from_cli_flag {
anyhow::bail!(
"`--module-path` cannot be used when `spacetime.json` contains publish targets. \
Remove `--module-path` or run without publish targets in config."
);
}
if has_generate_targets_in_config
&& (module_path_from_cli_flag || project_path_from_cli_flag || module_bindings_path_from_cli_flag)
{
anyhow::bail!(
"`--module-path`, `--project-path`, and `--module-bindings-path` cannot be used when \
`spacetime.json` contains generate targets. Remove these flags or remove generate targets from config."
);
}
// Fetch the database name if it was passed through a CLI arg
let database_name_from_cli: Option<String> = args
.get_one::<String>("database")
.or_else(|| args.get_one::<String>("database-flag"))
.map(|name| {
if args.get_one::<String>("database-flag").is_some() {
println!(
"{} {}",
"Warning:".yellow().bold(),
"--database flag is deprecated. Use positional argument instead: spacetime dev <database>".dimmed()
);
}
name.clone()
});
let database_name_from_cli_for_init = database_name_from_cli.clone();
// Build publish configs. It is easier to work with one type of data,
// so if we don't have publish configs from the config file, we build a single
// publish config based on the CLI args
let publish_cmd = publish::cli();
let publish_schema = publish::build_publish_schema(&publish_cmd)?;
// Create ArgMatches for publish command
let mut publish_argv: Vec<String> = vec!["publish".to_string()];
if let Some(db) = &database_name_from_cli {
publish_argv.push(db.clone());
}
if let Some(srv) = args.get_one::<String>("server") {
publish_argv.push("--server".to_string());
publish_argv.push(srv.clone());
}
let publish_args = publish_cmd
.clone()
.try_get_matches_from(publish_argv)
.context("Failed to create publish arguments")?;
let mut publish_configs = determine_publish_configs(
database_name_from_cli,
spacetime_config,
&publish_cmd,
&publish_schema,
&publish_args,
resolved_server,
&spacetimedb_dir,
)?;
// Check if we are in a SpacetimeDB project directory, but only if we don't have any
// publish_configs that would specify desired modules
if !has_any_config_files
&& module_path_from_cli.is_none()
&& (!spacetimedb_dir.exists() || !spacetimedb_dir.is_dir())
&& let Some(found_module) = find_module_path(&std::env::current_dir()?)
{
spacetimedb_dir = found_module;
}
if !has_any_config_files && (!spacetimedb_dir.exists() || !spacetimedb_dir.is_dir()) {
println!("{}", "No SpacetimeDB project found in current directory.".yellow());
let should_init = Confirm::new()
.with_prompt("Would you like to initialize a new project?")
.default(true)
.interact()?;
if should_init {
let init_options = init::InitOptions {
local: resolved_server == "local",
template: args.get_one::<String>("template").cloned(),
project_name_default: database_name_from_cli_for_init.clone(),
database_name_default: database_name_from_cli_for_init.clone(),
skip_next_steps: true,
..Default::default()
};
let created_project_path = init::exec_with_options(&mut config, &init_options).await?;
let canonical_created_path = created_project_path
.canonicalize()
.context("Failed to canonicalize created project path")?;
spacetimedb_dir = canonical_created_path.join("spacetimedb");
module_bindings_dir = canonical_created_path.join(module_bindings_path);
project_dir = canonical_created_path.clone();
// If the project was created in a subdirectory, hint the user to cd into it
// and show useful CLI commands they can run from there.
let current_dir = std::env::current_dir().context("Failed to get current directory")?;
let display_path = strip_verbatim_prefix(&canonical_created_path);
if display_path != current_dir {
let rel_path = display_path.strip_prefix(¤t_dir).unwrap_or(display_path);
println!(
"\n{} To interact with your database, open a new terminal and run:",
"Tip:".yellow().bold(),
);
println!(" cd ./{}", rel_path.display());
println!(" spacetime call add Alice");
println!(" spacetime sql \"SELECT * FROM person\"");
println!(" spacetime logs");
println!();
}
if !spacetimedb_dir.exists() {
anyhow::bail!("Project initialization did not create spacetimedb directory");
}
// Clear publish_configs so they're rebuilt after init with the correct
// spacetimedb_dir. Without this, configs built before init contain the
// pre-init (stale) module path and the block below would overwrite the
// correctly-updated spacetimedb_dir.
publish_configs.clear();
} else {
anyhow::bail!("Not in a SpacetimeDB project directory");
}
} else if args.get_one::<String>("template").is_some() {
println!(
"{}",
"Warning: --template option is ignored because a SpacetimeDB project already exists.".yellow()
);
}
if let Some(config) = publish_configs.first() {
// if we have publish configs and we're past spacetimedb_dir manipulation,
// we should set spacetimedb_dir to the path of the first config as this will be
// later used for next steps
if let Some(path) = config
.get_one::<PathBuf>("module_path")
.context("failed to read module_path from config")?
{
spacetimedb_dir = if path.is_absolute() {
path
} else {
project_dir.join(path)
};
}
}
// Refresh layered config after potential init/config creation so downstream behavior
// uses the latest spacetime.json + local/env overlays.
if !no_config {
loaded_config = find_and_load_with_env_from(Some(env), project_dir.clone())
.with_context(|| "Failed to reload spacetime.json after initialization")?;
}
let spacetime_config = loaded_config.as_ref().map(|lc| &lc.config);
let using_spacetime_config = spacetime_config.is_some();
let generate_configs_from_file: Vec<HashMap<String, serde_json::Value>> = {
let mut entries = spacetime_config.and_then(|c| c.generate.clone()).unwrap_or_default();
// Inherit top-level `module-path` into generate entries that don't specify their own.
// Without this, `generate` entries fall back to the hardcoded "spacetimedb" default
// even when the top-level config has a module-path set.
if let Some(top_level_module_path) = spacetime_config
.and_then(|c| c.additional_fields.get("module-path"))
.cloned()
{
for entry in &mut entries {
entry
.entry("module-path".to_string())
.or_insert(top_level_module_path.clone());
}
}
entries
};
// Re-resolve publish targets now that config files may have been created by init.
if publish_configs.is_empty() {
publish_configs = determine_publish_configs(
database_name_from_cli_for_init.clone(),
spacetime_config,
&publish_cmd,
&publish_schema,
&publish_args,
resolved_server,
&spacetimedb_dir,
)?;
}
let use_local = resolved_server == "local";
if !no_config && let Some(path) = create_default_spacetime_config_if_missing(&project_dir)? {
println!("{} Created {}", "✓".green(), strip_verbatim_prefix(&path).display());
}
// If we don't have any publish configs by now, we need to ask the user about the
// database they want to use. This should only happen if no configs are available
// in the config file and no database name has been passed through the CLI
if publish_configs.is_empty() {
println!("\n{}", "Found existing SpacetimeDB project.".green());
println!("Now we need to select a database to publish to.\n");
let selected = if use_local {
generate_database_name()
} else {
// If not logged in before, but login was successful just now, this will have the token
let token = get_login_token_or_log_in(&mut config, Some(resolved_server), !force).await?;
let choice = FuzzySelect::with_theme(&ColorfulTheme::default())
.with_prompt("Database selection")
.items(&["Create new database with random name", "Select from existing databases"])
.default(0)
.interact()?;
if choice == 0 {
generate_database_name()
} else {
select_database(&config, resolved_server, &token).await?
}
};
println!("\n{} {}", "Selected database:".green().bold(), selected.cyan());
println!(
"{} {}",
"Tip:".yellow().bold(),
format!("Use `spacetime dev {}` to skip this question next time", selected).dimmed()
);
let mut config_map = HashMap::new();
config_map.insert("database".to_string(), json!(selected));
config_map.insert("server".to_string(), json!(resolved_server));
publish_configs = vec![CommandConfig::new(&publish_schema, config_map, &publish_args)?];
}
if !no_config {
let db_to_persist = database_name_from_cli_for_init.as_deref().or_else(|| {
publish_configs
.first()
.and_then(|cfg| cfg.get_config_value("database"))
.and_then(|v| v.as_str())
});
if let Some(db_name) = db_to_persist
&& let Some(path) = create_local_spacetime_config_if_missing(&project_dir, db_name)?
{
println!("{} Created {}", "✓".green(), strip_verbatim_prefix(&path).display());
}
}
if !module_bindings_dir.exists() {
// Create the module bindings directory if it doesn't exist
std::fs::create_dir_all(&module_bindings_dir).with_context(|| {
format!(
"Failed to create module bindings path {}",
module_bindings_dir.display()
)
})?;
} else if !module_bindings_dir.is_dir() {
anyhow::bail!(
"Module bindings path {} exists but is not a directory.",
module_bindings_path.display()
);
}
// Check if we need to login to maincloud
// Either because --server maincloud was provided, or because any of the publish configs use maincloud
let needs_maincloud_login = resolved_server == "maincloud"
|| spacetime_config
.map(|c| {
c.iter_all_targets().any(|target| {
target
.additional_fields
.get("server")
.and_then(|v| v.as_str())
.map(|s| s == "maincloud")
.unwrap_or(false)
})
})
.unwrap_or(false);
if needs_maincloud_login && config.spacetimedb_token().is_none() {
let should_login = Confirm::new()
.with_prompt("Would you like to sign in now?")
.default(true)
.interact()?;
if !should_login && server_from_cli.is_some() {
// The user explicitly provided --server maincloud but doesn't want to log in
anyhow::bail!("Login required to publish to maincloud server");
} else if !should_login {
// Print warning saying that without logging in we will use local server regardless
// of what their default server is in their config
println!(
"{} {}",
"Warning:".yellow().bold(),
"Without logging in, the local server will be used regardless of your default server.".dimmed()
);
// Switch the server to local
resolved_server = "local";
} else {
// Login
get_login_token_or_log_in(&mut config, Some(resolved_server), !force).await?;
}
}
// Determine client command: CLI flag > config file > auto-detect (and save)
let server_only = args.get_flag("server-only");
let client_command = if server_only {
None
} else if let Some(cmd) = args.get_one::<String>("run") {
// Explicit CLI flag takes priority
Some(cmd.clone())
} else if no_config {
// --no-config means "don't read or write spacetime config files".
detect_client_command(&project_dir).map(|(cmd, _)| cmd)
} else if let Some(sc) = spacetime_config {
// Reuse already-loaded config instead of loading again
if let Some(ref lc) = loaded_config {
let files: Vec<_> = lc
.loaded_files
.iter()
.map(|f| strip_verbatim_prefix(f).display().to_string())
.collect();
println!("{} Using configuration from {}", "✓".green(), files.join(", "));
}
if sc.dev.as_ref().and_then(|d| d.run.as_ref()).is_none() {
detect_and_save_client_command(&project_dir, Some(sc.clone()))
} else {
sc.dev.as_ref().and_then(|d| d.run.clone())
}
} else {
// No config file - try to detect and create new
detect_and_save_client_command(&project_dir, None)
};
// Extract database names from publish configs for log streaming
let db_names_for_logging: Vec<String> = publish_configs
.iter()
.map(|config| {
config
.get_config_value("database")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow::anyhow!("database is a required field in publish config"))
.map(|s| s.to_string())
})
.collect::<Result<Vec<_>, _>>()?;
// Use first database for client process
let db_name_for_client = &db_names_for_logging[0];
// Extract watch directories from publish configs
let watch_dirs = extract_watch_dirs(&publish_configs, &spacetimedb_dir, &project_dir);
println!("\n{}", "Starting development mode...".green().bold());
if db_names_for_logging.len() == 1 {
println!("Database: {}", db_names_for_logging[0].cyan());
} else {
println!("Databases: {}", db_names_for_logging.join(", ").cyan());
}
// Announce watch directories
if watch_dirs.len() == 1 {
println!(
"Watching for changes in: {}",
strip_verbatim_prefix(watch_dirs.iter().next().unwrap())
.display()
.to_string()
.cyan()
);
} else {
let watch_dirs_vec: Vec<_> = watch_dirs.iter().collect();
println!("Watching for changes in {} directories:", watch_dirs.len());
for dir in &watch_dirs_vec {
println!(" - {}", strip_verbatim_prefix(dir).display().to_string().cyan());
}
}
// Safety prompt: warn if any selected database target is defined in spacetime.json.
// spacetime.local.json is gitignored and personal, so it's fine for dev use.
if let Some(ref lc) = loaded_config {
let database_sources = resolve_database_sources(&lc.config);
let databases_from_main_config: Vec<String> = db_names_for_logging
.iter()
.filter(|db| {
database_sources
.get((*db).as_str())
.is_some_and(|src| src.as_deref() == Some("spacetime.json"))
})
.cloned()
.collect();
if !databases_from_main_config.is_empty() && !force {
eprintln!(
"{} Database(s) `{}` are defined in spacetime.json (usually reserved for production databases).",
"Warning:".yellow().bold(),
databases_from_main_config.join(", ")
);
let should_continue = Confirm::new()
.with_prompt("Do you want to proceed with publishing in dev mode?")
.default(true)
.interact()?;
if !should_continue {
anyhow::bail!("Aborted.");
}
}
}
if let Some(ref cmd) = client_command {
println!("Client command: {}", cmd.cyan());
}
println!("{}", "Press Ctrl+C to stop".dimmed());
println!();
let loaded_config_dir = loaded_config.as_ref().map(|lc| lc.config_dir.clone());
generate_build_and_publish(
&config,
&project_dir,
loaded_config_dir.as_deref(),
&spacetimedb_dir,
&module_bindings_dir,
client_language,
clear_database,
&publish_configs,
&generate_configs_from_file,
using_spacetime_config,
server_from_cli,
force,
skip_publish,
skip_generate,
)
.await?;
// Sleep for a second to allow the database to be published on Maincloud
sleep(Duration::from_secs(1)).await;
// Start log streams for all targets
let use_prefix = db_names_for_logging.len() > 1;
let mut log_handles = Vec::new();
for config_entry in &publish_configs {
let db_name = config_entry
.get_config_value("database")
.and_then(|v| v.as_str())
.expect("database is a required field");
let server_opt = config_entry.get_one::<String>("server")?;
let server_for_db = server_opt.as_deref().unwrap_or(resolved_server);
let db_identity = database_identity(&config, db_name, Some(server_for_db)).await?;
let prefix = if use_prefix { Some(db_name.to_string()) } else { None };
let handle = start_log_stream(
config.clone(),
db_identity.to_hex().to_string(),
Some(server_for_db),
prefix,
)
.await?;
log_handles.push(handle);
}
// Start the client development server if configured
let server_opt_client = publish_configs
.first()
.and_then(|c| c.get_one::<String>("server").ok().flatten());
let server_for_client = server_opt_client.as_deref().unwrap_or(resolved_server);
let server_host_url = config.get_host_url(Some(server_for_client))?;
let mut client_handle = if let Some(ref cmd) = client_command {
let mut child = start_client_process(cmd, &project_dir, db_name_for_client, &server_host_url)?;
// Give the process a moment to fail fast (e.g., command not found, missing deps)
sleep(Duration::from_millis(200)).await;
match child.try_wait() {
Ok(Some(status)) if !status.success() => {
anyhow::bail!(
"Client command '{}' failed immediately with exit code: {}",
cmd,
status
.code()
.map(|c| c.to_string())
.unwrap_or_else(|| "unknown".to_string())
);
}
Err(e) => {
anyhow::bail!("Failed to check client process status: {}", e);
}
_ => {} // Still running or exited successfully (unusual but ok)
}
Some(child)
} else {
None
};
let gitignore = build_gitignore_matcher(&project_dir, &spacetimedb_dir);
let (tx, rx) = channel();
let mut watcher: RecommendedWatcher = Watcher::new(
move |res: Result<Event, notify::Error>| {
if let Ok(event) = res
&& matches!(
event.kind,
notify::EventKind::Modify(_) | notify::EventKind::Create(_) | notify::EventKind::Remove(_)
)
&& event.paths.iter().any(|p| !should_ignore_path(p, &gitignore))
{
let _ = tx.send(());
}
},
notify::Config::default().with_poll_interval(Duration::from_millis(500)),
)?;
// Watch all directories
for watch_dir in &watch_dirs {
watcher.watch(watch_dir, RecursiveMode::Recursive)?;
}
let mut debounce_timer;
loop {
// Use recv_timeout so we can periodically check if the client process exited
match rx.recv_timeout(Duration::from_secs(1)) {
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break Ok(()),
Ok(()) => {
debounce_timer = std::time::Instant::now();
while debounce_timer.elapsed() < Duration::from_millis(300) {
if rx.recv_timeout(Duration::from_millis(100)).is_ok() {
debounce_timer = std::time::Instant::now();
}
}
println!("\n{}", "File change detected, rebuilding...".yellow());
match generate_build_and_publish(
&config,
&project_dir,
loaded_config_dir.as_deref(),
&spacetimedb_dir,
&module_bindings_dir,
client_language,
clear_database,
&publish_configs,
&generate_configs_from_file,
using_spacetime_config,
server_from_cli,
force,
skip_publish,
skip_generate,
)
.await
{
Ok(_) => {}
Err(e) => {
eprintln!("{} {}", "Error:".red().bold(), e);
println!("{}", "Waiting for next change...".dimmed());
}
}
}
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
// No rebuild yet. Check if the client process has exited.
let Some(ref mut child) = client_handle else {
continue;
};
match child.try_wait() {
Ok(None) => {}
Ok(Some(status)) => {
client_handle = None;
let code = status
.code()
.map(|c| c.to_string())
.unwrap_or_else(|| "unknown".to_string());
println!(
"\n{} {}. {}",
"Client process exited with code".yellow(),
code,
"File watcher is still active.".dimmed()
);
}
Err(e) => {
client_handle = None;
eprintln!(
"\n{} Failed to check client process status: {}",
"Warning:".yellow().bold(),
e
);
}
}
}
};
}
}
fn determine_publish_configs<'a>(
database_name: Option<String>,
spacetime_config: Option<&SpacetimeConfig>,
publish_cmd: &Command,
publish_schema: &'a CommandSchema,
publish_args: &'a ArgMatches,
resolved_server: &str,
default_module_path: &Path,
) -> anyhow::Result<Vec<CommandConfig<'a>>> {
// Build publish configs. It is easier to work with one type of data,
// so if we don't have publish configs from the config file, we build a single
// publish config based on the CLI args
let mut publish_configs: Vec<CommandConfig> = vec![];
if let Some(config) = spacetime_config {
// Get and filter publish configs if the config has database targets
if config.additional_fields.contains_key("database") || config.children.is_some() {
publish_configs = publish::get_filtered_publish_configs(config, publish_cmd, publish_schema, publish_args)?;
}
}
if !publish_configs.is_empty() {
return Ok(publish_configs);
}
// If we still have no configs, it means that filtering by the database name filtered out
// all configs, we assume the user wants to run with a different DB
if let Some(ref db_name) = database_name {
let mut config_map = HashMap::new();
config_map.insert("database".to_string(), json!(db_name));
config_map.insert("server".to_string(), json!(resolved_server));
config_map.insert("module-path".to_string(), json!(default_module_path.to_string_lossy()));
Ok(vec![CommandConfig::new(publish_schema, config_map, publish_args)?])
} else {
// If there is no provided database name nor publish configs return no
// configs, we will handle it by asking user for a database or auto-generate one
Ok(vec![])
}
}
/// Upserts all SPACETIMEDB_DB_NAME and SPACETIMEDB_HOST variants into `.env.local`,
/// preserving comments/formatting and leaving unrelated keys unchanged.
fn upsert_env_db_names_and_hosts(env_path: &Path, server_host_url: &str, database_name: &str) -> anyhow::Result<()> {
// Framework-agnostic variants (same list for both DB_NAME and HOST)
let prefixes = [
"SPACETIMEDB", // generic / backend
"VITE_SPACETIMEDB", // Vite
"NEXT_PUBLIC_SPACETIMEDB", // Next.js
"REACT_APP_SPACETIMEDB", // CRA
"EXPO_PUBLIC_SPACETIMEDB", // Expo
"PUBLIC_SPACETIMEDB", // SvelteKit
];
let mut contents = if env_path.exists() {
fs::read_to_string(env_path)?
} else {
String::new()
};
let original_contents = contents.clone();
for prefix in prefixes {
for (suffix, value) in [("DB_NAME", database_name), ("HOST", server_host_url)] {
let key = format!("{prefix}_{suffix}");
let re = Regex::new(&format!(r"(?m)^(?P<prefix>\s*{key}\s*=\s*)(?P<val>.*)$"))?;
if re.is_match(&contents) {
contents = re.replace_all(&contents, format!("${{prefix}}{value}")).to_string();
} else {
if !contents.is_empty() && !contents.ends_with('\n') {
contents.push('\n');
}
contents.push_str(&format!("{key}={value}\n"));
}
}
}
if !contents.ends_with('\n') {
contents.push('\n');
}
if contents != original_contents {
fs::write(env_path, contents)?;
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn generate_build_and_publish(
config: &Config,
project_dir: &Path,
config_dir: Option<&Path>,
spacetimedb_dir: &Path,