cargo-generate 0.25.0

cargo, make me a project
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
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
//! Input from user but after parse

use std::{
    collections::HashMap,
    env,
    path::{Path, PathBuf},
};

use crate::absolute_path::AbsolutePathExt;
use console::style;

use crate::{
    app_config::{AppConfig, FavoriteConfig},
    template_variables::CrateType,
    GenerateArgs, Vcs,
};
use log::warn;

#[derive(Debug)]
#[cfg(test)]
pub struct UserParsedInputBuilder {
    subject: UserParsedInput,
}

#[cfg(test)]
impl UserParsedInputBuilder {
    #[cfg(test)]
    pub(crate) fn for_testing() -> Self {
        use crate::TemplatePath;
        Self {
            subject: UserParsedInput::try_from_args_and_config(
                AppConfig::default(),
                &GenerateArgs {
                    destination: Some(Path::new("/tmp/dest/").to_path_buf()),
                    template_path: TemplatePath {
                        path: Some("/tmp".to_string()),
                        ..TemplatePath::default()
                    },
                    ..GenerateArgs::default()
                },
            )
            .expect("a `--path` template needs no git support"),
        }
    }

    pub const fn with_force(mut self) -> Self {
        self.subject.force = true;
        self
    }

    pub fn build(self) -> UserParsedInput {
        self.subject
    }
}

// Contains parsed information from user.
#[derive(Debug)]
pub struct UserParsedInput {
    name: Option<String>,

    // from where clone or copy template?
    template_location: Source,

    destination: PathBuf,

    // if template_location contains many templates user already specified one
    subfolder: Option<String>,
    // all values that user defined through:
    // 1. environment variables
    // 2. configuration file
    // 3. cli arguments --define
    template_values: HashMap<String, toml::Value>,

    vcs: Vcs,
    pub init: bool,
    overwrite: bool,
    crate_type: CrateType,
    allow_commands: bool,
    silent: bool,
    force: bool,
    test: bool,
    force_git_init: bool,
    //TODO:
    // 1. This structure should be used instead of args
    // 2. This struct can contains internally args and app_config to not confuse
    //    other developer with parsing configuration and args by themself
}

impl UserParsedInput {
    /// Try create `UserParsedInput` reading in order [`AppConfig`] and [`Args`]
    ///
    /// # Panics
    /// This function assume that Args and AppConfig are verified earlier and are logically correct
    /// For example if both `--git` and `--path` are set this function will panic
    ///
    /// # Errors
    ///
    /// Returns an error when the resolved input needs git but this build
    /// was compiled without the `git` cargo feature.
    pub fn try_from_args_and_config(
        app_config: AppConfig,
        args: &GenerateArgs,
    ) -> anyhow::Result<Self> {
        // A *default* degrades silently; an *explicit* `Vcs::Git` bails.
        // Without the feature there is no git to init into, so the sensible
        // default is None — nobody asked for git, nothing should fail.
        #[cfg(feature = "git")]
        const DEFAULT_VCS: Vcs = Vcs::Git;
        #[cfg(not(feature = "git"))]
        const DEFAULT_VCS: Vcs = Vcs::None;

        let destination = args
            .destination
            .as_ref()
            .map(|p| {
                p.as_absolute()
                    .expect("cannot get the absolute path of the destination folder")
                    .to_path_buf()
            })
            .unwrap_or_else(|| env::current_dir().unwrap_or_else(|_| ".".into()));

        let cwd = env::current_dir().unwrap_or_else(|_| ".".into());

        let mut default_values = app_config.values.clone().unwrap_or_default();

        let ssh_identity = app_config
            .defaults
            .as_ref()
            .and_then(|dcfg| dcfg.ssh_identity.clone())
            .or_else(|| {
                args.ssh_identity.as_ref().cloned().or_else(|| {
                    app_config
                        .defaults
                        .as_ref()
                        .and_then(|defaults| defaults.ssh_identity.clone())
                })
            });

        // --git
        if let Some(git_url) = args.template_path.git() {
            let template_location = git_source_from_args(
                git_url.as_ref(),
                args,
                &app_config,
                &cwd,
                ssh_identity.clone(),
            )?;
            return Ok(Self {
                name: args.name.clone(),
                template_location,
                subfolder: args
                    .template_path
                    .subfolder()
                    .map(|s| s.as_ref().to_owned()),
                template_values: default_values,
                vcs: args.vcs.unwrap_or(DEFAULT_VCS),
                init: args.init,
                overwrite: args.overwrite,
                crate_type: CrateType::from(args),
                allow_commands: args.allow_commands,
                silent: args.silent,
                destination,
                force: args.force,
                test: args.template_path.test,
                force_git_init: args.force_git_init,
            });
        }

        // --path
        if let Some(path) = args.template_path.path() {
            return Ok(Self {
                name: args.name.clone(),
                template_location: path.as_ref().into(),
                subfolder: args
                    .template_path
                    .subfolder()
                    .map(|s| s.as_ref().to_owned()),
                template_values: default_values,
                vcs: args.vcs.unwrap_or(DEFAULT_VCS),
                init: args.init,
                overwrite: args.overwrite,
                crate_type: CrateType::from(args),
                allow_commands: args.allow_commands,
                silent: args.silent,
                destination,
                force: args.force,
                test: args.template_path.test,
                force_git_init: args.force_git_init,
            });
        }

        // check if favorite is favorite configuration
        let fav_name = args.template_path.any_path();

        if let Some(fav_cfg) = app_config.get_favorite_cfg(fav_name) {
            assert!(fav_cfg.git.is_none() || fav_cfg.path.is_none());

            let temp_location = match fav_cfg.git.as_ref() {
                Some(git_url) => git_source_from_favorite(git_url, fav_cfg, args, ssh_identity)?,
                None => Source::from(fav_cfg.path.as_ref().unwrap()),
            };

            if let Some(fav_default_values) = &fav_cfg.values {
                default_values.extend(fav_default_values.clone());
            }

            return Ok(Self {
                name: args.name.clone(),
                template_location: temp_location,
                subfolder: args
                    .template_path
                    .subfolder()
                    .map(|s| s.as_ref().to_owned())
                    .or_else(|| fav_cfg.subfolder.clone()),
                template_values: default_values,
                vcs: args.vcs.or(fav_cfg.vcs).unwrap_or(DEFAULT_VCS),
                init: args
                    .init
                    .then_some(true)
                    .or(fav_cfg.init)
                    .unwrap_or_default(),
                overwrite: args
                    .overwrite
                    .then_some(true)
                    .or(fav_cfg.overwrite)
                    .unwrap_or_default(),
                crate_type: CrateType::from(args),
                allow_commands: args.allow_commands,
                silent: args.silent,
                destination,
                force: args.force,
                test: args.template_path.test,
                force_git_init: args.force_git_init,
            });
        }

        // there is no specified favorite in configuration
        // auto_path with no configured favorite name → classify it
        let source = crate::template_source::TemplateSource::classify(fav_name, &app_config, &cwd);
        let clone_opts = clone_opts_from_args(args, ssh_identity);
        let temp_location = source.into_source(&clone_opts)?;

        // Print information about what happened (preserve the existing warn!)
        let location_msg = match &temp_location {
            #[cfg(feature = "git")]
            Source::Git(git_user_input) => {
                format!("git repository: {}", style(git_user_input.url()).bold())
            }
            Source::Local(path) => {
                format!("local path: {}", style(path.display()).bold())
            }
        };
        warn!(
            "Favorite `{}` not found in config, using it as a {}",
            style(&fav_name).bold(),
            location_msg
        );

        Ok(Self {
            name: args.name.clone(),
            template_location: temp_location,
            subfolder: args
                .template_path
                .subfolder()
                .map(|s| s.as_ref().to_owned()),
            template_values: default_values,
            vcs: args.vcs.unwrap_or(DEFAULT_VCS),
            init: args.init,
            overwrite: args.overwrite,
            crate_type: CrateType::from(args),
            allow_commands: args.allow_commands,
            silent: args.silent,
            destination,
            force: args.force,
            test: args.template_path.test,
            force_git_init: args.force_git_init,
        })
    }

    /// Fail when the resolved input asks for a git VCS but this build
    /// has no git support.
    ///
    /// Compiled unconditionally so both configurations run the same
    /// control flow; with the `git` feature `ensure_available` is a
    /// no-op returning `Ok(())`.
    ///
    /// `self.vcs == Vcs::Git` can only be true here when the user asked
    /// for it explicitly — via `Vcs::Git` or a favorite's `vcs` key —
    /// because the fallback without the feature is `Vcs::None`. A
    /// template that requests `vcs = "Git"` in its own
    /// `cargo-generate.toml` is resolved much later, in `generate()`,
    /// and is caught by the `git::feature::init` stub instead.
    ///
    /// `force_git_init` is checked separately: it never reaches the
    /// stub, because the fallback `Vcs::None` makes the init step a
    /// no-op. Left unchecked it would be silently ignored, which is
    /// the one thing an explicitly passed flag must never be.
    ///
    /// # Errors
    ///
    /// Returns an error when git was requested but this build was
    /// compiled without the `git` cargo feature.
    pub fn ensure_git_feature_available(&self) -> anyhow::Result<()> {
        if self.vcs == Vcs::Git {
            crate::git::ensure_available(
                "git VCS initialization (`Vcs::Git`, or `vcs` in a favorite's config)",
            )?;
        }
        if self.force_git_init {
            crate::git::ensure_available("`GenerateArgs::force_git_init`")?;
        }
        Ok(())
    }

    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    pub const fn location(&self) -> &Source {
        &self.template_location
    }

    pub fn subfolder(&self) -> Option<&str> {
        self.subfolder.as_deref()
    }

    pub const fn template_values(&self) -> &HashMap<String, toml::Value> {
        &self.template_values
    }

    pub const fn template_values_mut(&mut self) -> &mut HashMap<String, toml::Value> {
        &mut self.template_values
    }

    pub const fn vcs(&self) -> Vcs {
        self.vcs
    }

    pub const fn init(&self) -> bool {
        self.init
    }

    pub const fn overwrite(&self) -> bool {
        self.overwrite
    }

    pub const fn crate_type(&self) -> CrateType {
        self.crate_type
    }

    pub const fn allow_commands(&self) -> bool {
        self.allow_commands
    }

    pub const fn silent(&self) -> bool {
        self.silent
    }

    pub fn destination(&self) -> &Path {
        self.destination.as_path()
    }

    pub const fn force(&self) -> bool {
        self.force
    }

    pub const fn test(&self) -> bool {
        self.test
    }

    pub const fn force_git_init(&self) -> bool {
        self.force_git_init
    }
}

// Template should be cloned with git
#[cfg(feature = "git")]
#[derive(Debug)]
pub struct GitSource {
    url: String,
    branch: Option<String>,
    tag: Option<String>,
    revision: Option<String>,
    identity: Option<PathBuf>,
    gitconfig: Option<PathBuf>,
    _force_init: bool,
    pub skip_submodules: bool,
}

#[cfg(feature = "git")]
impl GitSource {
    #[allow(clippy::too_many_arguments)]
    fn new(
        url: &impl AsRef<str>,
        branch: Option<&impl AsRef<str>>,
        tag: Option<&impl AsRef<str>>,
        revision: Option<&impl AsRef<str>>,
        identity: Option<PathBuf>,
        gitconfig: Option<PathBuf>,
        force_init: bool,
        skip_submodules: bool,
    ) -> Self {
        Self {
            url: url.as_ref().to_owned(),
            branch: branch.map(|s| s.as_ref().to_owned()),
            tag: tag.map(|s| s.as_ref().to_owned()),
            revision: revision.map(|s| s.as_ref().to_owned()),
            identity,
            gitconfig,
            _force_init: force_init,
            skip_submodules,
        }
    }

    /// Build a `GitSource` from a resolved URL and the cargo-generate
    /// clone options. Used by `TemplateSource::into_source`.
    pub fn with_url_and_clone_opts(
        url: String,
        opts: &crate::template_source::CloneOptions,
    ) -> Self {
        Self::new(
            &url,
            opts.branch.as_ref(),
            opts.tag.as_ref(),
            opts.revision.as_ref(),
            opts.ssh_identity.clone(),
            opts.gitconfig.clone(),
            opts.force_git_init,
            opts.skip_submodules,
        )
    }

    pub fn url(&self) -> &str {
        self.url.as_ref()
    }

    pub fn branch(&self) -> Option<&str> {
        self.branch.as_deref()
    }

    pub fn tag(&self) -> Option<&str> {
        self.tag.as_deref()
    }

    pub fn revision(&self) -> Option<&str> {
        self.revision.as_deref()
    }

    pub fn identity(&self) -> Option<&Path> {
        self.identity.as_deref()
    }

    pub fn gitconfig(&self) -> Option<&Path> {
        self.gitconfig.as_deref()
    }
}

/// Build the [`Source`] for an explicit [`TemplatePath::git`].
///
/// # Errors
///
/// Never errors with the `git` feature enabled.
#[cfg(feature = "git")]
fn git_source_from_args(
    git_url: &str,
    args: &GenerateArgs,
    app_config: &AppConfig,
    cwd: &Path,
    ssh_identity: Option<PathBuf>,
) -> anyhow::Result<Source> {
    let source = crate::template_source::TemplateSource::classify(git_url, app_config, cwd);
    let clone_opts = clone_opts_from_args(args, ssh_identity);
    source.into_git_source(&clone_opts)
}

/// See the `cfg(feature = "git")` twin above.
///
/// # Errors
///
/// Always errors: `--git` cannot be served by this build.
#[cfg(not(feature = "git"))]
fn git_source_from_args(
    _git_url: &str,
    _args: &GenerateArgs,
    _app_config: &AppConfig,
    _cwd: &Path,
    _ssh_identity: Option<PathBuf>,
) -> anyhow::Result<Source> {
    Err(crate::git::feature_disabled("`TemplatePath::git`"))
}

/// Build the [`Source`] for a favorite whose config carries a git URL.
///
/// # Errors
///
/// Never errors with the `git` feature enabled.
#[cfg(feature = "git")]
fn git_source_from_favorite(
    git_url: &str,
    fav_cfg: &FavoriteConfig,
    args: &GenerateArgs,
    ssh_identity: Option<PathBuf>,
) -> anyhow::Result<Source> {
    let branch = args
        .template_path
        .branch()
        .map(|s| s.as_ref().to_owned())
        .or_else(|| fav_cfg.branch.clone());
    let tag = args
        .template_path
        .tag()
        .map(|s| s.as_ref().to_owned())
        .or_else(|| fav_cfg.tag.clone());
    let revision = args
        .template_path
        .revision()
        .map(|s| s.as_ref().to_owned())
        .or_else(|| fav_cfg.revision.clone());

    Ok(Source::from(GitSource::new(
        &git_url,
        branch.as_ref(),
        tag.as_ref(),
        revision.as_ref(),
        ssh_identity,
        None,
        args.force_git_init,
        args.skip_submodules,
    )))
}

/// See the `cfg(feature = "git")` twin above.
///
/// # Errors
///
/// Always errors: a git-backed favorite cannot be served by this build.
#[cfg(not(feature = "git"))]
fn git_source_from_favorite(
    _git_url: &str,
    _fav_cfg: &FavoriteConfig,
    _args: &GenerateArgs,
    _ssh_identity: Option<PathBuf>,
) -> anyhow::Result<Source> {
    Err(crate::git::feature_disabled(
        "a favorite configured with a `git` URL",
    ))
}

fn clone_opts_from_args(
    args: &GenerateArgs,
    ssh_identity: Option<PathBuf>,
) -> crate::template_source::CloneOptions {
    crate::template_source::CloneOptions {
        branch: args.template_path.branch().map(|s| s.as_ref().to_owned()),
        tag: args.template_path.tag().map(|s| s.as_ref().to_owned()),
        revision: args.template_path.revision().map(|s| s.as_ref().to_owned()),
        ssh_identity,
        gitconfig: args.gitconfig.clone(),
        force_git_init: args.force_git_init,
        skip_submodules: args.skip_submodules,
    }
}

/// Where a template comes from.
///
/// # Cargo features
///
/// The `Git` variant requires the `git` cargo feature. Without it the
/// variant does not exist, so a git fetch cannot be expressed at all —
/// deliberate, and the reason this API can be stricter than the
/// `GenerateArgs` entry point, whose shape must stay invariant.
#[derive(Debug)]
pub enum Source {
    #[cfg(feature = "git")]
    Git(GitSource),
    Local(PathBuf),
}

#[cfg(feature = "git")]
impl From<GitSource> for Source {
    fn from(source: GitSource) -> Self {
        Self::Git(source)
    }
}

impl From<PathBuf> for Source {
    fn from(source: PathBuf) -> Self {
        Self::Local(source)
    }
}

impl From<&PathBuf> for Source {
    fn from(source: &PathBuf) -> Self {
        Self::Local(source.clone())
    }
}

impl From<&std::path::Path> for Source {
    fn from(source: &std::path::Path) -> Self {
        Self::Local(PathBuf::from(source))
    }
}

impl From<&str> for Source {
    fn from(source: &str) -> Self {
        Self::Local(PathBuf::from(source))
    }
}

impl From<String> for Source {
    fn from(source: String) -> Self {
        Self::Local(PathBuf::from(source))
    }
}

impl From<&String> for Source {
    fn from(source: &String) -> Self {
        Self::Local(PathBuf::from(source))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Helper to build a `GenerateArgs` with `--git <value>` and resolve via `try_from_args_and_config`,
    /// returning the resolved git URL from the resulting `Source`.
    #[cfg(feature = "git")]
    fn resolve_git_flag(git_value: &str) -> String {
        let args = GenerateArgs {
            destination: Some(PathBuf::from("/tmp")),
            template_path: crate::TemplatePath {
                git: Some(git_value.to_owned()),
                ..crate::TemplatePath::default()
            },
            ..GenerateArgs::default()
        };
        let parsed =
            UserParsedInput::try_from_args_and_config(AppConfig::default(), &args).unwrap();
        match parsed.location() {
            Source::Git(git) => git.url().to_owned(),
            Source::Local(p) => panic!("expected Git location, got Path: {p:?}"),
        }
    }

    #[cfg(feature = "git")]
    #[test]
    fn git_flag_full_url() {
        // cargo generate --git https://github.com/username-on-github/mytemplate.git
        assert_eq!(
            resolve_git_flag("https://github.com/username-on-github/mytemplate.git"),
            "https://github.com/username-on-github/mytemplate.git"
        );
    }

    #[cfg(feature = "git")]
    #[test]
    fn git_flag_org_repo_shorthand() {
        // cargo generate --git username-on-github/mytemplate
        assert_eq!(
            resolve_git_flag("username-on-github/mytemplate"),
            "https://github.com/username-on-github/mytemplate.git"
        );
    }

    #[cfg(feature = "git")]
    #[test]
    fn git_flag_gh_prefix() {
        // cargo generate --git gh:username-on-github/mytemplate
        assert_eq!(
            resolve_git_flag("gh:username-on-github/mytemplate"),
            "https://github.com/username-on-github/mytemplate.git"
        );
    }

    #[cfg(feature = "git")]
    #[test]
    fn git_flag_gl_prefix() {
        // cargo generate --git gl:username-on-gitlab/mytemplate
        assert_eq!(
            resolve_git_flag("gl:username-on-gitlab/mytemplate"),
            "https://gitlab.com/username-on-gitlab/mytemplate.git"
        );
    }

    #[cfg(feature = "git")]
    #[test]
    fn git_flag_bb_prefix() {
        // cargo generate --git bb:username-on-bitbucket/mytemplate
        assert_eq!(
            resolve_git_flag("bb:username-on-bitbucket/mytemplate"),
            "https://bitbucket.org/username-on-bitbucket/mytemplate.git"
        );
    }

    #[cfg(feature = "git")]
    #[test]
    fn git_flag_sr_prefix() {
        // cargo generate --git sr:username-on-sourcehut/mytemplate
        assert_eq!(
            resolve_git_flag("sr:username-on-sourcehut/mytemplate"),
            "https://git.sr.ht/~username-on-sourcehut/mytemplate"
        );
    }

    #[cfg(feature = "git")]
    #[test]
    fn git_flag_relative_path_resolves_to_local_directory() {
        // When --git receives a relative path like `./example-templates/hooks`
        // that exists as a local directory, it must remain a Git location so
        // that branch/tag/ssh-identity options are honoured (git clone accepts
        // file-system paths). It must NOT be expanded to a remote URL.
        // `cargo test` sets cwd to the crate root, so this path resolves.
        let args = GenerateArgs {
            template_path: crate::TemplatePath {
                git: Some("./example-templates/hooks".to_owned()),
                ..crate::TemplatePath::default()
            },
            ..GenerateArgs::default()
        };

        let parsed =
            UserParsedInput::try_from_args_and_config(AppConfig::default(), &args).unwrap();

        match parsed.location() {
            Source::Git(git) => {
                assert!(
                    git.url().ends_with("example-templates/hooks"),
                    "expected url ending in example-templates/hooks, got {}",
                    git.url()
                );
            }
            Source::Local(p) => panic!("expected Git location, got Path: {p:?}"),
        }
    }

    #[cfg(feature = "git")]
    #[test]
    fn git_flag_local_path_takes_precedence_over_org_repo() {
        // When --git receives a value matching the org/repo shape that also
        // exists as a local directory, it must be kept as a Git location rather
        // than expanded to github. `example-templates/hooks` doubles as a real
        // path under the crate root and a valid `org/repo` shape.
        let args = GenerateArgs {
            template_path: crate::TemplatePath {
                git: Some("example-templates/hooks".to_owned()),
                ..crate::TemplatePath::default()
            },
            ..GenerateArgs::default()
        };

        let parsed =
            UserParsedInput::try_from_args_and_config(AppConfig::default(), &args).unwrap();
        match parsed.location() {
            Source::Git(git) => {
                assert!(
                    git.url().ends_with("example-templates/hooks"),
                    "expected url ending in example-templates/hooks, got {}",
                    git.url()
                );
            }
            Source::Local(p) => panic!("expected Git location, got Path: {p:?}"),
        }
    }

    #[cfg(not(feature = "git"))]
    #[test]
    fn git_url_bails_without_the_git_feature() {
        let args = GenerateArgs {
            template_path: crate::TemplatePath {
                git: Some("https://github.com/o/r.git".into()),
                ..crate::TemplatePath::default()
            },
            ..GenerateArgs::default()
        };
        let err = UserParsedInput::try_from_args_and_config(AppConfig::default(), &args)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("TemplatePath::git"),
            "names the field that was set: {err}"
        );
        assert!(err.contains("`git` cargo feature"), "{err}");
    }

    #[cfg(not(feature = "git"))]
    #[test]
    fn remote_bare_argument_bails_without_the_git_feature() {
        let args = GenerateArgs {
            template_path: crate::TemplatePath {
                auto_path: Some("https://github.com/o/r.git".into()),
                ..crate::TemplatePath::default()
            },
            ..GenerateArgs::default()
        };
        let err = UserParsedInput::try_from_args_and_config(AppConfig::default(), &args)
            .unwrap_err()
            .to_string();
        assert!(err.contains("`git` cargo feature"), "{err}");
        assert!(
            !err.contains("TemplatePath::git"),
            "the caller set auto_path, not git: {err}"
        );
    }

    #[cfg(not(feature = "git"))]
    #[test]
    fn git_backed_favorite_bails_without_the_git_feature() {
        use crate::app_config::FavoriteConfig;
        use std::collections::HashMap;

        let mut favorites = HashMap::new();
        favorites.insert(
            "myfave".to_owned(),
            FavoriteConfig {
                git: Some("https://github.com/o/r.git".to_owned()),
                ..FavoriteConfig::default()
            },
        );
        let app_config = AppConfig {
            favorites: Some(favorites),
            ..AppConfig::default()
        };
        let args = GenerateArgs {
            template_path: crate::TemplatePath {
                favorite: Some("myfave".into()),
                ..crate::TemplatePath::default()
            },
            ..GenerateArgs::default()
        };
        let err = UserParsedInput::try_from_args_and_config(app_config, &args)
            .unwrap_err()
            .to_string();
        assert!(err.contains("favorite"), "names the favorite: {err}");
        assert!(err.contains("`git` cargo feature"), "{err}");
    }

    #[cfg(not(feature = "git"))]
    #[test]
    fn explicit_vcs_git_bails_without_the_git_feature() {
        let args = GenerateArgs {
            template_path: crate::TemplatePath {
                path: Some(".".into()),
                ..crate::TemplatePath::default()
            },
            vcs: Some(Vcs::Git),
            ..GenerateArgs::default()
        };
        let parsed =
            UserParsedInput::try_from_args_and_config(AppConfig::default(), &args).unwrap();
        assert!(parsed.ensure_git_feature_available().is_err());
    }

    #[cfg(not(feature = "git"))]
    #[test]
    fn force_git_init_bails_without_the_git_feature() {
        // Explicitly passed git input must never be silently ignored,
        // even though the default VCS degraded to None.
        let args = GenerateArgs {
            template_path: crate::TemplatePath {
                path: Some(".".into()),
                ..crate::TemplatePath::default()
            },
            force_git_init: true,
            ..Default::default()
        };
        let parsed =
            UserParsedInput::try_from_args_and_config(AppConfig::default(), &args).unwrap();
        let err = parsed
            .ensure_git_feature_available()
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("force_git_init"),
            "names the field that was set: {err}"
        );
        assert!(err.contains("`git` cargo feature"), "{err}");
    }

    #[cfg(not(feature = "git"))]
    #[test]
    fn local_path_is_fine_without_the_git_feature() {
        let args = GenerateArgs {
            template_path: crate::TemplatePath {
                path: Some(".".into()),
                ..crate::TemplatePath::default()
            },
            ..GenerateArgs::default()
        };
        let parsed =
            UserParsedInput::try_from_args_and_config(AppConfig::default(), &args).unwrap();
        assert_eq!(parsed.vcs(), Vcs::None, "default VCS degrades to None");
        parsed.ensure_git_feature_available().unwrap();
    }

    #[cfg(feature = "git")]
    #[test]
    fn git_url_is_fine_with_the_git_feature() {
        let args = GenerateArgs {
            template_path: crate::TemplatePath {
                git: Some("https://github.com/o/r.git".into()),
                ..crate::TemplatePath::default()
            },
            ..GenerateArgs::default()
        };
        let parsed =
            UserParsedInput::try_from_args_and_config(AppConfig::default(), &args).unwrap();
        parsed.ensure_git_feature_available().unwrap();
    }
}