forklaunch 1.15.0

Launch faster with forklaunch
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
use std::{
    collections::HashMap,
    fs,
    io::Write,
    path::{Path, PathBuf},
};

use anyhow::{Context, Result};
use regex::Regex;
use serde::{Deserialize, Serialize};

use crate::core::rendered_template::RenderedTemplatesCache;

#[derive(Debug, Serialize)]
pub(crate) struct Env {
    #[serde(rename = "DB_NAME", skip_serializing_if = "Option::is_none")]
    pub(crate) db_name: Option<String>,
    #[serde(rename = "DB_HOST", skip_serializing_if = "Option::is_none")]
    pub(crate) db_host: Option<String>,
    #[serde(rename = "DB_USER", skip_serializing_if = "Option::is_none")]
    pub(crate) db_user: Option<String>,
    #[serde(rename = "DB_PASSWORD", skip_serializing_if = "Option::is_none")]
    pub(crate) db_password: Option<String>,
    #[serde(rename = "DB_PORT", skip_serializing_if = "Option::is_none")]
    pub(crate) db_port: Option<String>,
    #[serde(rename = "REDIS_URL", skip_serializing_if = "Option::is_none")]
    pub(crate) redis_url: Option<String>,
    #[serde(rename = "S3_URL", skip_serializing_if = "Option::is_none")]
    pub(crate) s3_url: Option<String>,
    #[serde(rename = "S3_BUCKET", skip_serializing_if = "Option::is_none")]
    pub(crate) s3_bucket: Option<String>,
    #[serde(rename = "S3_REGION", skip_serializing_if = "Option::is_none")]
    pub(crate) s3_region: Option<String>,
    #[serde(rename = "S3_ACCESS_KEY_ID", skip_serializing_if = "Option::is_none")]
    pub(crate) s3_access_key: Option<String>,
    #[serde(
        rename = "S3_SECRET_ACCESS_KEY",
        skip_serializing_if = "Option::is_none"
    )]
    pub(crate) s3_secret_key: Option<String>,
    #[serde(rename = "KAFKA_BROKERS", skip_serializing_if = "Option::is_none")]
    pub(crate) kafka_brokers: Option<String>,
    #[serde(rename = "KAFKA_CLIENT_ID", skip_serializing_if = "Option::is_none")]
    pub(crate) kafka_client_id: Option<String>,
    #[serde(rename = "KAFKA_GROUP_ID", skip_serializing_if = "Option::is_none")]
    pub(crate) kafka_group_id: Option<String>,
    #[serde(rename = "NODE_ENV", skip_serializing_if = "Option::is_none")]
    pub(crate) env: Option<String>,
    #[serde(
        rename = "OTEL_EXPORTER_OTLP_ENDPOINT",
        skip_serializing_if = "Option::is_none"
    )]
    pub(crate) otel_exporter_otlp_endpoint: Option<String>,
    #[serde(rename = "OTEL_SERVICE_NAME", skip_serializing_if = "Option::is_none")]
    pub(crate) otel_service_name: Option<String>,
    #[serde(rename = "QUEUE_NAME", skip_serializing_if = "Option::is_none")]
    pub(crate) queue_name: Option<String>,
    #[serde(rename = "HOST", skip_serializing_if = "Option::is_none")]
    pub(crate) host: Option<String>,
    #[serde(rename = "PROTOCOL", skip_serializing_if = "Option::is_none")]
    pub(crate) protocol: Option<String>,
    #[serde(rename = "PORT", skip_serializing_if = "Option::is_none")]
    pub(crate) port: Option<String>,
    #[serde(rename = "VERSION", skip_serializing_if = "Option::is_none")]
    pub(crate) version: Option<String>,
    #[serde(rename = "DOCS_PATH", skip_serializing_if = "Option::is_none")]
    pub(crate) docs_path: Option<String>,
    #[serde(
        rename = "BETTER_AUTH_BASE_PATH",
        skip_serializing_if = "Option::is_none"
    )]
    pub(crate) better_auth_base_path: Option<String>,
    #[serde(rename = "BETTER_AUTH_SECRET", skip_serializing_if = "Option::is_none")]
    pub(crate) better_auth_secret: Option<String>,
    #[serde(rename = "CORS_ORIGINS", skip_serializing_if = "Option::is_none")]
    pub(crate) cors_origins: Option<String>,
    #[serde(rename = "STRIPE_API_KEY", skip_serializing_if = "Option::is_none")]
    pub(crate) stripe_api_key: Option<String>,
    #[serde(rename = "TWILIO_ACCOUNT_SID", skip_serializing_if = "Option::is_none")]
    pub(crate) twilio_account_sid: Option<String>,
    #[serde(rename = "TWILIO_AUTH_TOKEN", skip_serializing_if = "Option::is_none")]
    pub(crate) twilio_auth_token: Option<String>,
    #[serde(rename = "TWILIO_FROM_NUMBER", skip_serializing_if = "Option::is_none")]
    pub(crate) twilio_from_number: Option<String>,
    #[serde(rename = "HMAC_SECRET_KEY", skip_serializing_if = "Option::is_none")]
    pub(crate) hmac_secret_key: Option<String>,
    #[serde(
        rename = "JWKS_PUBLIC_KEY_URL",
        skip_serializing_if = "Option::is_none"
    )]
    pub(crate) jwks_public_key_url: Option<String>,
    #[serde(flatten, default)]
    pub(crate) additional_env_vars: HashMap<String, String>,
}

impl<'de> Deserialize<'de> for Env {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(field_identifier, rename_all = "SCREAMING_SNAKE_CASE")]
        enum Field {
            DbName,
            DbHost,
            DbUser,
            DbPassword,
            DbPort,
            RedisUrl,
            KafkaBrokers,
            KafkaClientId,
            KafkaGroupId,
            Env,
            OtelExporterOtlpEndpoint,
            OtelServiceName,
            QueueName,
            Host,
            Protocol,
            Port,
            Version,
            DocsPath,
            BetterAuthSecret,
            BetterAuthBasePath,
            HmacSecretKey,
            JwksPublicKeyUrl,
            Other(String),
        }

        struct EnvVisitor;

        impl<'de> serde::de::Visitor<'de> for EnvVisitor {
            type Value = Env;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("struct Env")
            }

            fn visit_map<V>(self, mut map: V) -> Result<Env, V::Error>
            where
                V: serde::de::MapAccess<'de>,
            {
                let mut env = Env {
                    db_name: None,
                    db_host: None,
                    db_user: None,
                    db_password: None,
                    db_port: None,
                    redis_url: None,
                    s3_url: None,
                    s3_bucket: None,
                    s3_region: None,
                    s3_access_key: None,
                    s3_secret_key: None,
                    kafka_brokers: None,
                    kafka_client_id: None,
                    kafka_group_id: None,
                    env: None,
                    otel_exporter_otlp_endpoint: None,
                    otel_service_name: None,
                    queue_name: None,
                    host: None,
                    protocol: None,
                    port: None,
                    version: None,
                    docs_path: None,
                    better_auth_secret: None,
                    better_auth_base_path: None,
                    cors_origins: None,
                    stripe_api_key: None,
                    twilio_account_sid: None,
                    twilio_auth_token: None,
                    twilio_from_number: None,
                    hmac_secret_key: None,
                    jwks_public_key_url: None,
                    additional_env_vars: HashMap::new(),
                };

                while let Some(key) = map.next_key::<Field>()? {
                    match key {
                        Field::DbName => env.db_name = Some(map.next_value()?),
                        Field::DbHost => env.db_host = Some(map.next_value()?),
                        Field::DbUser => env.db_user = Some(map.next_value()?),
                        Field::DbPassword => env.db_password = Some(map.next_value()?),
                        Field::DbPort => env.db_port = Some(map.next_value()?),
                        Field::RedisUrl => env.redis_url = Some(map.next_value()?),
                        Field::KafkaBrokers => env.kafka_brokers = Some(map.next_value()?),
                        Field::KafkaClientId => env.kafka_client_id = Some(map.next_value()?),
                        Field::KafkaGroupId => env.kafka_group_id = Some(map.next_value()?),
                        Field::Env => env.env = Some(map.next_value()?),
                        Field::OtelExporterOtlpEndpoint => {
                            env.otel_exporter_otlp_endpoint = Some(map.next_value()?)
                        }
                        Field::OtelServiceName => env.otel_service_name = Some(map.next_value()?),
                        Field::QueueName => env.queue_name = Some(map.next_value()?),
                        Field::Host => env.host = Some(map.next_value()?),
                        Field::Protocol => env.protocol = Some(map.next_value()?),
                        Field::Port => env.port = Some(map.next_value()?),
                        Field::Version => env.version = Some(map.next_value()?),
                        Field::DocsPath => env.docs_path = Some(map.next_value()?),
                        Field::BetterAuthSecret => env.better_auth_secret = Some(map.next_value()?),
                        Field::BetterAuthBasePath => {
                            env.better_auth_base_path = Some(map.next_value()?)
                        }
                        Field::HmacSecretKey => env.hmac_secret_key = Some(map.next_value()?),
                        Field::JwksPublicKeyUrl => {
                            env.jwks_public_key_url = Some(map.next_value()?)
                        }
                        Field::Other(key) => {
                            env.additional_env_vars.insert(key, map.next_value()?);
                        }
                    }
                }

                Ok(env)
            }
        }

        deserializer.deserialize_map(EnvVisitor)
    }
}

/// Reads a project's `.env.local` out of the rendered templates cache,
/// treating an absent file as an empty environment rather than an error.
///
/// `*.env.local` is gitignored in generated applications, so a fresh
/// checkout legitimately has none. Unwrapping the `Option` here made every
/// `forklaunch change` subcommand abort with an opaque
/// `called Option::unwrap() on a None value` panic. The callers all insert
/// the result back into the cache, so the file is created on the way out.
pub(crate) fn read_env_local_or_default(
    rendered_templates_cache: &RenderedTemplatesCache,
    env_local_path: &Path,
) -> Result<Env> {
    let content = rendered_templates_cache
        .get(env_local_path)?
        .map(|template| template.content)
        .unwrap_or_default();

    serde_envfile::from_str::<Env>(&content)
        .with_context(|| format!("Failed to parse {}", env_local_path.display()))
}

#[derive(Debug, Clone)]
pub(crate) struct EnvFile {
    pub(crate) variables: HashMap<String, String>,
}

/// Index of the first unescaped closing quote, or None. Double-quoted
/// values honor backslash escapes; single-quoted values are verbatim.
fn find_closing_quote(s: &str, quote_char: char) -> Option<usize> {
    let mut escaped = false;
    for (idx, ch) in s.char_indices() {
        if escaped {
            escaped = false;
            continue;
        }
        if quote_char == '"' && ch == '\\' {
            escaped = true;
            continue;
        }
        if ch == quote_char {
            return Some(idx);
        }
    }
    None
}

/// Strip an inline comment from an UNQUOTED value: everything from the
/// first whitespace-followed-by-`#` onward is dropped (e.g.
/// `DOCKER_HOST=docker # ⚠ REJECTED — replace` parses as `docker`).
/// A `#` with no preceding whitespace is part of the value (passwords,
/// URLs with fragments). Quoted values never pass through here.
fn strip_inline_comment(rest: &str) -> &str {
    let bytes = rest.as_bytes();
    for (idx, &b) in bytes.iter().enumerate() {
        if b == b'#' && (idx == 0 || bytes[idx - 1].is_ascii_whitespace()) {
            return &rest[..idx];
        }
    }
    rest
}

/// Extract a value that may be quoted (verbatim, possibly multiline) or
/// unquoted (inline comments stripped).
///
/// Quoted values are taken verbatim up to the first unescaped closing
/// quote; anything after the closing quote on the same line (e.g. a
/// trailing ` # comment`) is ignored. For multiline values `*i` is
/// advanced to the closing-quote line so the caller's `i += 1` lands on
/// the next key correctly.
pub(crate) fn extract_env_value(lines: &[&str], i: &mut usize, rest: &str) -> String {
    if rest.starts_with('"') || rest.starts_with('\'') {
        let quote_char = rest.chars().next().unwrap();
        let inner = &rest[1..];
        if let Some(close) = find_closing_quote(inner, quote_char) {
            // Single-line quoted value; trailing content after the close
            // (comments, stray text) is intentionally discarded.
            return inner[..close].to_string();
        }
        // Multiline: consume verbatim until a line containing the closing
        // quote. Content after the close on that final line is discarded.
        let mut value_lines = vec![inner.to_string()];
        *i += 1;
        while *i < lines.len() {
            let next_line = lines[*i];
            if let Some(close) = find_closing_quote(next_line, quote_char) {
                value_lines.push(next_line[..close].to_string());
                break;
            }
            value_lines.push(next_line.to_string());
            *i += 1;
        }
        value_lines.join("\n")
    } else {
        strip_inline_comment(rest).trim().to_string()
    }
}

/// An item parsed from an env file — either a section header comment or a key-value pair.
#[derive(Debug)]
pub(crate) enum EnvFileItem {
    SectionHeader(String),
    KeyValue(String, String),
}

/// Parses an env file preserving section header comment lines
/// (e.g. `# application` or `# matching-service (uuid)`) so callers can reconstruct
/// the full file content with scope information intact.
pub(crate) fn parse_env_file_items(path: &Path) -> Result<Vec<EnvFileItem>> {
    if !path.exists() {
        return Ok(Vec::new());
    }

    let content = fs::read_to_string(path)
        .with_context(|| format!("Failed to read env file: {}", path.display()))?;

    Ok(parse_env_items_from_str(&content))
}

/// String-based variant of `parse_env_file_items` for content fetched over
/// the wire (e.g. `config set` pulling the current scope before merging).
pub(crate) fn parse_env_items_from_str(content: &str) -> Vec<EnvFileItem> {
    let lines: Vec<&str> = content.lines().collect();
    let mut items: Vec<EnvFileItem> = Vec::new();
    let mut i = 0;

    while i < lines.len() {
        let line = lines[i].trim();

        if line.is_empty() {
            i += 1;
            continue;
        }

        if line.starts_with('#') {
            items.push(EnvFileItem::SectionHeader(line.to_string()));
            i += 1;
            continue;
        }

        if let Some(eq_pos) = line.find('=') {
            let key = line[..eq_pos].trim().to_string();
            let rest = line[eq_pos + 1..].trim();
            if !key.is_empty() {
                let value = extract_env_value(&lines, &mut i, rest);
                items.push(EnvFileItem::KeyValue(key, value));
            }
        }

        i += 1;
    }

    items
}

pub(crate) fn load_env_file(path: &Path) -> Result<HashMap<String, String>> {
    if !path.exists() {
        return Ok(HashMap::new());
    }

    let content = fs::read_to_string(path)
        .with_context(|| format!("Failed to read env file: {}", path.display()))?;

    let mut variables = HashMap::new();
    let lines: Vec<&str> = content.lines().collect();
    let mut i = 0;

    // Same extraction semantics as parse_env_file_items: quoted values are
    // verbatim (multiline supported, trailing comments after the closing
    // quote ignored); unquoted values have inline ` # ...` comments stripped.
    while i < lines.len() {
        let line = lines[i].trim();

        if line.is_empty() || line.starts_with('#') {
            i += 1;
            continue;
        }

        if let Some(eq_pos) = line.find('=') {
            let key = line[..eq_pos].trim().to_string();
            let rest = line[eq_pos + 1..].trim();
            if !key.is_empty() {
                let value = extract_env_value(&lines, &mut i, rest);
                variables.insert(key, value);
            }
        }

        i += 1;
    }

    Ok(variables)
}

pub(crate) fn find_env_files(project_path: &Path) -> Result<Vec<PathBuf>> {
    let mut env_files = Vec::new();

    if !project_path.exists() {
        return Ok(env_files);
    }

    let env_regex = Regex::new(r"^\.env(\.[a-zA-Z0-9_-]+)*$")?;

    if let Ok(entries) = fs::read_dir(project_path) {
        for entry in entries {
            if let Ok(entry) = entry {
                if let Some(file_name) = entry.file_name().to_str() {
                    if env_regex.is_match(file_name) && entry.path().is_file() {
                        env_files.push(entry.path());
                    }
                }
            }
        }
    }

    env_files.sort_by(|a, b| {
        let a_name = a.file_name().unwrap().to_str().unwrap();
        let b_name = b.file_name().unwrap().to_str().unwrap();

        let get_priority = |name: &str| match name {
            ".env.local" => 0,
            ".env.development" => 1,
            ".env.production" => 2,
            ".env.test" => 3,
            ".env" => 4,
            _ => 5,
        };

        get_priority(a_name).cmp(&get_priority(b_name))
    });

    Ok(env_files)
}

pub(crate) fn load_project_env_files(project_path: &Path) -> Result<Vec<EnvFile>> {
    let env_file_paths = find_env_files(project_path)?;
    let mut env_files = Vec::new();

    for path in env_file_paths {
        let variables = load_env_file(&path)?;
        env_files.push(EnvFile { variables });
    }

    Ok(env_files)
}

pub(crate) fn is_env_var_defined(project_path: &Path, var_name: &str) -> Result<bool> {
    let env_files = load_project_env_files(project_path)?;
    for env_file in env_files {
        if env_file.variables.contains_key(var_name) {
            return Ok(true);
        }
    }

    if let Ok(workspace_root) = find_workspace_root(project_path) {
        let cascading_env_paths = get_cascading_env_paths(project_path, &workspace_root)?;

        for env_path in cascading_env_paths {
            if let Ok(variables) = load_env_file(&env_path) {
                if variables.contains_key(var_name) {
                    return Ok(true);
                }
            }
        }
    }

    Ok(false)
}

pub(crate) fn get_target_env_file(project_path: &Path) -> Result<PathBuf> {
    let env_local = project_path.join(".env.local");
    let env_default = project_path.join(".env");

    if env_local.exists() {
        Ok(env_local)
    } else if env_default.exists() {
        Ok(env_default)
    } else {
        Ok(env_local)
    }
}

pub(crate) fn add_env_vars_to_file(file_path: &Path, vars: &HashMap<String, String>) -> Result<()> {
    let mut content = String::new();

    if file_path.exists() {
        content = fs::read_to_string(file_path)
            .with_context(|| format!("Failed to read env file: {}", file_path.display()))?;

        if !content.is_empty() && !content.ends_with('\n') {
            content.push('\n');
        }
    }

    let existing_vars = load_env_file(file_path)?;

    for (key, value) in vars {
        if !existing_vars.contains_key(key) {
            content.push_str(&format!("{}={}\n", key, value));
        }
    }

    let mut file = fs::File::create(file_path)
        .with_context(|| format!("Failed to create env file: {}", file_path.display()))?;

    file.write_all(content.as_bytes())
        .with_context(|| format!("Failed to write to env file: {}", file_path.display()))?;

    Ok(())
}

pub(crate) fn find_workspace_root(start_path: &Path) -> Result<PathBuf> {
    let mut current_path = start_path.canonicalize()?;

    loop {
        let manifest_path = current_path.join(".forklaunch").join("manifest.toml");
        if manifest_path.exists() {
            return Ok(current_path);
        }

        match current_path.parent() {
            Some(parent) => current_path = parent.to_path_buf(),
            None => {
                return Err(anyhow::anyhow!(
                    "Could not find workspace root (no .forklaunch/manifest.toml found)"
                ));
            }
        }
    }
}

pub(crate) fn get_modules_path(workspace_root: &Path) -> Result<PathBuf> {
    let manifest_path = workspace_root.join(".forklaunch").join("manifest.toml");

    if !manifest_path.exists() {
        return Err(anyhow::anyhow!(
            "Manifest file not found: {}",
            manifest_path.display()
        ));
    }

    let manifest_content = fs::read_to_string(&manifest_path)
        .with_context(|| format!("Failed to read manifest: {}", manifest_path.display()))?;

    let manifest: toml::Value =
        toml::from_str(&manifest_content).with_context(|| "Failed to parse manifest.toml")?;

    let modules_path = manifest
        .get("modules_path")
        .and_then(|v| v.as_str())
        .unwrap_or(".");

    Ok(workspace_root.join(modules_path))
}

pub(crate) fn get_cascading_env_paths(
    project_path: &Path,
    workspace_root: &Path,
) -> Result<Vec<PathBuf>> {
    let mut env_paths = Vec::new();

    let env_regex = Regex::new(r"^\.env(\.[a-zA-Z0-9_-]+)*$")?;

    let mut current_path = project_path.canonicalize()?;
    let normalized_workspace_root = workspace_root.canonicalize()?;

    while current_path.starts_with(&normalized_workspace_root) {
        if let Ok(entries) = fs::read_dir(&current_path) {
            let mut current_dir_env_files = Vec::new();

            for entry in entries {
                if let Ok(entry) = entry {
                    if let Some(file_name) = entry.file_name().to_str() {
                        if env_regex.is_match(file_name) && entry.path().is_file() {
                            current_dir_env_files.push(entry.path());
                        }
                    }
                }
            }

            current_dir_env_files.sort_by(|a, b| {
                let a_name = a.file_name().unwrap().to_str().unwrap();
                let b_name = b.file_name().unwrap().to_str().unwrap();

                let get_priority = |name: &str| match name {
                    ".env.local" => 0,
                    ".env" => 1,
                    ".env.development" => 2,
                    ".env.production" => 3,
                    ".env.test" => 4,
                    _ => 5,
                };

                get_priority(a_name).cmp(&get_priority(b_name))
            });

            env_paths.extend(current_dir_env_files);
        }

        if current_path == normalized_workspace_root {
            break;
        }

        match current_path.parent() {
            Some(parent) => current_path = parent.to_path_buf(),
            None => break,
        }
    }

    env_paths.reverse();

    Ok(env_paths)
}

#[cfg(test)]
mod tests {
    use tempfile::TempDir;

    use super::*;

    // `*.env.local` is gitignored in generated applications, so a fresh
    // checkout has none. Every `forklaunch change` subcommand used to unwrap
    // the missing file and panic; a missing file must read as an empty Env.
    #[test]
    fn test_read_env_local_or_default_missing_file_is_empty_not_a_panic() {
        let temp_dir = TempDir::new().unwrap();
        let env_local_path = temp_dir.path().join(".env.local");
        let cache = RenderedTemplatesCache::new();

        let env = read_env_local_or_default(&cache, &env_local_path).unwrap();

        assert!(env.queue_name.is_none());
        assert!(env.db_name.is_none());
        assert!(env.additional_env_vars.is_empty());
        // Round-trips to an empty file that the caller can then populate.
        assert_eq!(serde_envfile::to_string(&env).unwrap(), "");
    }

    #[test]
    fn test_read_env_local_or_default_reads_existing_file_and_keeps_unknown_vars() {
        let temp_dir = TempDir::new().unwrap();
        let env_local_path = temp_dir.path().join(".env.local");
        fs::write(
            &env_local_path,
            "DB_NAME=app-dev\nAPP_BASE_DOMAIN=example.test\n",
        )
        .unwrap();
        let cache = RenderedTemplatesCache::new();

        let env = read_env_local_or_default(&cache, &env_local_path).unwrap();

        // NOTE: serde_envfile lower-cases keys on read and upper-cases them on
        // write, so nothing lands in the named fields and everything round
        // trips through `additional_env_vars`. That is pre-existing behaviour;
        // what matters here is that an existing file is read and every
        // variable in it survives the round trip.
        assert_eq!(
            env.additional_env_vars.get("db_name"),
            Some(&"app-dev".to_string())
        );
        assert_eq!(
            env.additional_env_vars.get("app_base_domain"),
            Some(&"example.test".to_string())
        );

        let round_tripped = serde_envfile::to_string(&env).unwrap();
        assert!(round_tripped.contains("DB_NAME"));
        assert!(round_tripped.contains("APP_BASE_DOMAIN"));
    }

    #[test]
    fn test_load_env_file() {
        let temp_dir = TempDir::new().unwrap();
        let env_path = temp_dir.path().join(".env");

        fs::write(
            &env_path,
            "KEY1=value1\nKEY2=\"value2\"\n# Comment\nKEY3=value3",
        )
        .unwrap();

        let vars = load_env_file(&env_path).unwrap();
        assert_eq!(vars.get("KEY1"), Some(&"value1".to_string()));
        assert_eq!(vars.get("KEY2"), Some(&"value2".to_string()));
        assert_eq!(vars.get("KEY3"), Some(&"value3".to_string()));
        assert_eq!(vars.len(), 3);
    }

    #[test]
    fn test_load_env_file_strips_inline_comments_and_keeps_quotes_verbatim() {
        let temp_dir = TempDir::new().unwrap();
        let env_path = temp_dir.path().join(".env");

        fs::write(
            &env_path,
            concat!(
                "DOCKER_HOST=docker # ⚠ REJECTED — replace with production value\n",
                "QUOTED=\"keep # this\" # but drop this\n",
                "GLUED=pa#ss\n",
                "PEM=\"-----BEGIN\nabc\n-----END\"\n",
                "AFTER=ok\n",
            ),
        )
        .unwrap();

        let vars = load_env_file(&env_path).unwrap();
        assert_eq!(vars.get("DOCKER_HOST"), Some(&"docker".to_string()));
        assert_eq!(vars.get("QUOTED"), Some(&"keep # this".to_string()));
        assert_eq!(vars.get("GLUED"), Some(&"pa#ss".to_string()));
        assert_eq!(
            vars.get("PEM"),
            Some(&"-----BEGIN\nabc\n-----END".to_string())
        );
        assert_eq!(vars.get("AFTER"), Some(&"ok".to_string()));
        assert_eq!(vars.len(), 5);
    }

    #[test]
    fn test_extract_env_value_plain() {
        let lines = vec!["KEY=hello"];
        let mut i = 0;
        assert_eq!(extract_env_value(&lines, &mut i, "hello"), "hello");
        assert_eq!(i, 0); // no advancement for plain values
    }

    #[test]
    fn test_extract_env_value_plain_strips_inline_comment() {
        let lines = vec!["KEY=hello # a comment"];
        let mut i = 0;
        assert_eq!(
            extract_env_value(&lines, &mut i, "hello # a comment"),
            "hello"
        );
        assert_eq!(i, 0);
    }

    #[test]
    fn test_extract_env_value_hash_without_space_is_part_of_value() {
        // Passwords / URL fragments keep a glued '#'.
        let lines = vec!["KEY=pa#ss"];
        let mut i = 0;
        assert_eq!(extract_env_value(&lines, &mut i, "pa#ss"), "pa#ss");
    }

    #[test]
    fn test_extract_env_value_quoted_with_trailing_comment() {
        // The deploy template's exact shape: a quoted value followed by an
        // annotation. Must NOT be treated as a multiline opener.
        let lines = vec![
            "DOCKER_HOST=\"docker\" # ⚠ REJECTED — replace with production value",
            "NEXT=untouched",
        ];
        let mut i = 0;
        assert_eq!(
            extract_env_value(
                &lines,
                &mut i,
                "\"docker\" # ⚠ REJECTED — replace with production value"
            ),
            "docker"
        );
        assert_eq!(i, 0); // must not swallow the next line
    }

    #[test]
    fn test_extract_env_value_quoted_keeps_hash_verbatim() {
        let lines = vec!["KEY=\"value # not a comment\""];
        let mut i = 0;
        assert_eq!(
            extract_env_value(&lines, &mut i, "\"value # not a comment\""),
            "value # not a comment"
        );
    }

    #[test]
    fn test_extract_env_value_double_quoted_escaped_quote() {
        let lines = vec![r#"KEY="say \"hi\"""#];
        let mut i = 0;
        assert_eq!(
            extract_env_value(&lines, &mut i, r#""say \"hi\"""#),
            r#"say \"hi\""#
        );
    }

    #[test]
    fn test_extract_env_value_single_line_double_quoted() {
        let lines = vec!["KEY=\"hello world\""];
        let mut i = 0;
        assert_eq!(
            extract_env_value(&lines, &mut i, "\"hello world\""),
            "hello world"
        );
        assert_eq!(i, 0);
    }

    #[test]
    fn test_extract_env_value_single_line_single_quoted() {
        let lines = vec!["KEY='hello world'"];
        let mut i = 0;
        assert_eq!(
            extract_env_value(&lines, &mut i, "'hello world'"),
            "hello world"
        );
        assert_eq!(i, 0);
    }

    #[test]
    fn test_extract_env_value_multiline_double_quoted() {
        let lines = vec![
            "KEY=\"line one",
            "line two",
            "line three\"",
            "NEXT=something",
        ];
        let mut i = 0;
        let val = extract_env_value(&lines, &mut i, "\"line one");
        assert_eq!(val, "line one\nline two\nline three");
        assert_eq!(i, 2);
    }

    #[test]
    fn test_extract_env_value_multiline_single_quoted() {
        let lines = vec!["KEY='-----BEGIN", "abc", "-----END'"];
        let mut i = 0;
        let val = extract_env_value(&lines, &mut i, "'-----BEGIN");
        assert_eq!(val, "-----BEGIN\nabc\n-----END");
        assert_eq!(i, 2);
    }

    #[test]
    fn test_parse_env_file_items_simple() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("test.env");
        fs::write(&path, "A=1\nB=2\n").unwrap();

        let items = parse_env_file_items(&path).unwrap();
        assert_eq!(items.len(), 2);
        assert!(matches!(&items[0], EnvFileItem::KeyValue(k, v) if k == "A" && v == "1"));
        assert!(matches!(&items[1], EnvFileItem::KeyValue(k, v) if k == "B" && v == "2"));
    }

    #[test]
    fn test_parse_env_file_items_preserves_section_headers() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("test.env");
        fs::write(&path, "# application\nA=1\n# my-service (abc-123)\nB=2\n").unwrap();

        let items = parse_env_file_items(&path).unwrap();
        assert_eq!(items.len(), 4);
        assert!(matches!(&items[0], EnvFileItem::SectionHeader(h) if h == "# application"));
        assert!(matches!(&items[1], EnvFileItem::KeyValue(k, v) if k == "A" && v == "1"));
        assert!(
            matches!(&items[2], EnvFileItem::SectionHeader(h) if h == "# my-service (abc-123)")
        );
        assert!(matches!(&items[3], EnvFileItem::KeyValue(k, v) if k == "B" && v == "2"));
    }

    #[test]
    fn test_parse_env_file_items_skips_blank_lines() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("test.env");
        fs::write(&path, "\n# section\n\nA=1\n\nB=2\n").unwrap();

        let items = parse_env_file_items(&path).unwrap();
        assert_eq!(items.len(), 3);
        assert!(matches!(&items[0], EnvFileItem::SectionHeader(_)));
        assert!(matches!(&items[1], EnvFileItem::KeyValue(k, _) if k == "A"));
        assert!(matches!(&items[2], EnvFileItem::KeyValue(k, _) if k == "B"));
    }

    #[test]
    fn test_parse_env_file_items_multiline_value() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("test.env");
        fs::write(&path, "KEY=\"line one\nline two\"\nOTHER=val\n").unwrap();

        let items = parse_env_file_items(&path).unwrap();
        assert_eq!(items.len(), 2);
        assert!(
            matches!(&items[0], EnvFileItem::KeyValue(k, v) if k == "KEY" && v == "line one\nline two")
        );
        assert!(matches!(&items[1], EnvFileItem::KeyValue(k, v) if k == "OTHER" && v == "val"));
    }

    #[test]
    fn test_parse_env_file_items_nonexistent_returns_empty() {
        let items = parse_env_file_items(std::path::Path::new("/nonexistent/file.env")).unwrap();
        assert!(items.is_empty());
    }

    #[test]
    fn test_add_env_vars_to_file() {
        let temp_dir = TempDir::new().unwrap();
        let env_path = temp_dir.path().join(".env");

        let mut vars = HashMap::new();
        vars.insert("NEW_VAR".to_string(), "new_value".to_string());
        vars.insert("ANOTHER_VAR".to_string(), "another_value".to_string());

        add_env_vars_to_file(&env_path, &vars).unwrap();

        let loaded_vars = load_env_file(&env_path).unwrap();
        assert_eq!(loaded_vars.get("NEW_VAR"), Some(&"new_value".to_string()));
        assert_eq!(
            loaded_vars.get("ANOTHER_VAR"),
            Some(&"another_value".to_string())
        );
    }
}