cargo-telar 0.2.2

Cargo subcommand for Telar apps: dev server with hot reload, and packaging into native installers.
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
//! Reading a project's configuration: `telar.toml`, `[package.metadata.telar]` and the manifest fields the bundlers need.

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

use clap::ValueEnum;
use serde::Deserialize;

pub(crate) use telar_project::{DevSection, TelarSection, WindowSection};
use telar_project::{ManifestError, RendererBackend, TelarManifest};

/// The three words the `--backend` flag takes.
///
/// A CLI vocabulary, not a config one: [`telar_project::RendererBackend`] is the same three words parsed by serde out of `telar.toml`, and this is what clap parses out of an argument. They convert; they are not one type because `ValueEnum` cannot be derived for a type from another crate.
#[derive(Clone, Copy, ValueEnum)]
pub(crate) enum BackendArg {
    Auto,
    Hardware,
    Software,
}

impl From<BackendArg> for RendererBackend {
    fn from(arg: BackendArg) -> Self {
        match arg {
            BackendArg::Auto => Self::Auto,
            BackendArg::Hardware => Self::Hardware,
            BackendArg::Software => Self::Software,
        }
    }
}

#[derive(Deserialize, Default)]
pub(crate) struct CargoWorkspace {
    pub(crate) package: Option<CargoWorkspacePackage>,
}
// `[workspace.package]` — the values a member inherits with `field.workspace = true`.
#[derive(Deserialize, Default, Clone)]
pub(crate) struct CargoWorkspacePackage {
    #[serde(default)]
    pub(crate) version: Option<String>,
    #[serde(default)]
    pub(crate) authors: Vec<String>,
    #[serde(default)]
    pub(crate) description: Option<String>,
}
#[derive(Deserialize, Default)]
pub(crate) struct CargoManifest {
    pub(crate) workspace: Option<CargoWorkspace>,
    pub(crate) package: Option<CargoPackage>,
    pub(crate) lib: Option<CargoLib>,
    // Only the names are read: what a feature turns on is cargo's business, and all this has to know is whether the package named one.
    #[serde(default)]
    pub(crate) features: BTreeMap<String, toml::Value>,
}
#[derive(Deserialize, Default)]
pub(crate) struct CargoLib {
    #[serde(default, rename = "crate-type")]
    pub(crate) crate_type: Vec<String>,
}
#[derive(Deserialize, Default)]
pub(crate) struct CargoPackage {
    pub(crate) name: String,
    #[serde(default)]
    pub(crate) version: Inheritable<String>,
    #[serde(default)]
    pub(crate) authors: Inheritable<Vec<String>>,
    #[serde(default)]
    pub(crate) description: Inheritable<String>,
    pub(crate) metadata: Option<CargoPackageMetadata>,
}

// Inherited is kept apart from absent because only the inherited case has an answer in the workspace manifest; collapsing the two let a member's real version reach a `.deb` as the hardcoded fallback.
#[derive(Default, Debug, PartialEq)]
pub(crate) enum Inheritable<T> {
    #[default]
    Absent,
    FromWorkspace,
    Set(T),
}

impl<'de, T: serde::de::DeserializeOwned> Deserialize<'de> for Inheritable<T> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = toml::Value::deserialize(deserializer)?;
        if value.get("workspace").and_then(toml::Value::as_bool) == Some(true) {
            return Ok(Self::FromWorkspace);
        }
        T::deserialize(value)
            .map(Self::Set)
            .map_err(serde::de::Error::custom)
    }
}

impl<T: Clone> Inheritable<T> {
    fn resolve(&self, inherited: impl FnOnce() -> Option<T>) -> Option<T> {
        match self {
            Self::Set(value) => Some(value.clone()),
            Self::FromWorkspace => inherited(),
            Self::Absent => None,
        }
    }
}
#[derive(Deserialize, Default)]
pub(crate) struct CargoPackageMetadata {
    pub(crate) android: Option<AndroidMetadata>,
}
#[derive(Deserialize, Default)]
pub(crate) struct AndroidMetadata {
    pub(crate) package: Option<String>,
}

fn find_package_dir_in_workspace(workspace_root: &Path, package_name: &str) -> Option<PathBuf> {
    telar_project::workspace_member_dirs(workspace_root)
        .into_iter()
        .find(|member| {
            read_package_manifest_in(member).is_some_and(|package| package.name == package_name)
        })
}

pub(crate) fn find_package_dir(args: &[String]) -> PathBuf {
    let package_name = args
        .windows(2)
        .find(|pair| pair[0] == "-p" || pair[0] == "--package")
        .map(|pair| pair[1].as_str());

    if let Some(name) = package_name {
        let cwd = std::env::current_dir().unwrap_or_default();
        if let Some(root) = telar_project::find_workspace_root(&cwd)
            && let Some(dir) = find_package_dir_in_workspace(&root, name)
        {
            return dir;
        }
    }

    let mut dir = std::env::current_dir().unwrap_or_default();
    loop {
        if dir.join("Cargo.toml").exists() {
            return dir;
        }
        match dir.parent() {
            Some(parent) => dir = parent.to_path_buf(),
            None => return std::env::current_dir().unwrap_or_default(),
        }
    }
}

fn read_manifest_in(dir: &Path) -> Option<CargoManifest> {
    let content = std::fs::read_to_string(dir.join("Cargo.toml")).ok()?;
    toml::from_str(&content).ok()
}

pub(crate) fn read_package_manifest_in(dir: &Path) -> Option<CargoPackage> {
    read_manifest_in(dir)?.package
}

pub(crate) fn read_package_manifest(args: &[String]) -> Option<CargoPackage> {
    read_package_manifest_in(&find_package_dir(args))
}

pub(crate) struct ResolvedPackage {
    pub(crate) workspace_root: PathBuf,
    pub(crate) package_dir: PathBuf,
    pub(crate) package: Option<CargoPackage>,
    // Read once here rather than per getter, since a member that inherits one field usually inherits several.
    pub(crate) workspace_package: Option<CargoWorkspacePackage>,
    // Hot reload dlopens the package's own cdylib, and without `crate-type = ["cdylib", ..]` cargo never emits one, so the dylib build is dead weight and the runner falls back to process restart.
    pub(crate) produces_cdylib: bool,
    // What the frontend selection reads before deciding it may turn the package's defaults off.
    pub(crate) features: BTreeMap<String, toml::Value>,
}

impl ResolvedPackage {
    // Falls back to cargo's default "app" binary name when the manifest can't be read.
    pub(crate) fn name(&self) -> String {
        self.package
            .as_ref()
            .map(|p| p.name.clone())
            .unwrap_or_else(|| "app".to_string())
    }

    pub(crate) fn version(&self) -> String {
        self.package
            .as_ref()
            .and_then(|p| {
                p.version
                    .resolve(|| self.workspace_package.as_ref()?.version.clone())
            })
            .unwrap_or_else(|| "0.1.0".to_string())
    }

    // Debian's `Maintainer` and Cargo's `authors` share the `Name <email>` shape, so the manifest is the one source. There is no honest default: a placeholder address ships inside the package.
    pub(crate) fn maintainer(&self) -> Option<String> {
        self.package
            .as_ref()
            .and_then(|p| {
                p.authors
                    .resolve(|| Some(self.workspace_package.as_ref()?.authors.clone()))
            })
            .and_then(|authors| authors.first().cloned())
            .or_else(maintainer_from_env)
    }

    pub(crate) fn description(&self) -> Option<String> {
        self.package.as_ref().and_then(|p| {
            p.description
                .resolve(|| self.workspace_package.as_ref()?.description.clone())
        })
    }

    /// Whether the package's `default` turns `wanted` on, in either spelling and through however many of its own features it takes to get there.
    fn default_names(&self, wanted: &str) -> bool {
        let enabled = closure(&self.features, feature_list(self.features.get(DEFAULT)));
        enabled.contains(wanted) || enabled.contains(&format!("telar/{wanted}"))
    }

    /// Whether this package runs in the terminal without being told to: its `default` names the terminal frontend and nothing that opens a window.
    ///
    /// What `--target tui` says outright, for a project that already said it in its manifest — and what a `cargo telar dev` there needs to know, or it goes looking for a window to hot-reload behind.
    pub(crate) fn defaults_to_terminal(&self) -> bool {
        self.default_names("tui")
            && !["desktop", "web", "web-dom", "android"]
                .iter()
                .any(|frontend| self.default_names(frontend))
    }

    /// Whether this package can be built for the browser at all — its `default` names one of the two web
    /// frontends, or it declares a feature for one that a `--target web` build would reach. What decides
    /// whether `[profile.web]` (see [`WEB_PROFILE_TOML`]) is this project's problem to have.
    pub(crate) fn targets_web(&self) -> bool {
        self.features.contains_key("web")
            || self.features.contains_key("web-dom")
            || self.default_names("web")
            || self.default_names("web-dom")
    }

    /// How this package reaches `wanted`, which is the frontend feature a `--target` asked for.
    pub(crate) fn frontend_feature(&self, wanted: &str) -> FrontendFeature {
        if self.default_names(wanted) {
            return FrontendFeature::AlreadyDefault;
        }
        if !self.features.contains_key(wanted) {
            return FrontendFeature::Telar(format!("telar/{wanted}"));
        }
        let name = self.name();
        let mut named = vec![format!("{name}/{wanted}")];
        named.extend(
            feature_list(self.features.get(DEFAULT))
                .into_iter()
                .filter(|feature| !enables_frontend(&self.features, feature))
                .map(|feature| match feature.contains('/') {
                    true => feature,
                    false => format!("{name}/{feature}"),
                }),
        );
        FrontendFeature::Package(named)
    }
}

/// How a build reaches the frontend a `--target` named.
///
/// A project says which frontend it builds in its `default` — that is what `cargo telar new` writes into it — so naming another one means turning that default off. Adding it on top instead is what made `--target tui` compile a desktop stack beside the terminal one: harmless on a machine that can build both, and the whole of the failure on one that cannot.
pub(crate) enum FrontendFeature {
    /// The package's `default` already turns it on, so the build says nothing and keeps every default it has.
    AlreadyDefault,
    /// The package declares a feature for it. The rest of its `default` is re-named alongside, because `--no-default-features` is the only lever cargo has and it takes the whole list — only the *other* frontends in there are dropped.
    Package(Vec<String>),
    /// The package names no such feature, so the dependency's is what turns the frontend on and the defaults stay as they are. What lets any project build for a target without first declaring one.
    Telar(String),
}

impl FrontendFeature {
    /// Appends what cargo needs to build exactly this frontend.
    pub(crate) fn push_to(&self, args: &mut Vec<String>) {
        match self {
            Self::AlreadyDefault => {}
            Self::Package(features) => {
                args.push("--no-default-features".to_string());
                args.push("--features".to_string());
                args.push(features.join(","));
            }
            Self::Telar(feature) => {
                args.push("--features".to_string());
                args.push(feature.clone());
            }
        }
    }
}

const DEFAULT: &str = "default";

/// Every frontend a package can name a feature for, in the spelling `telar` gives it. What a retained default is filtered against, so `--target tui` drops the other targets out of `default` and keeps everything else in it.
const FRONTENDS: [&str; 6] = ["desktop", "tui", "web", "web-dom", "android", "headless"];

fn feature_list(value: Option<&toml::Value>) -> Vec<String> {
    value
        .and_then(toml::Value::as_array)
        .map(|entries| {
            entries
                .iter()
                .filter_map(|entry| entry.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default()
}

/// Every feature `roots` turn on, including the ones reached through another of the package's own — a `default` that names one feature which names a frontend is still a project that chose that frontend.
fn closure(features: &BTreeMap<String, toml::Value>, roots: Vec<String>) -> BTreeSet<String> {
    let mut seen = BTreeSet::new();
    let mut queue = roots;
    while let Some(feature) = queue.pop() {
        if !seen.insert(feature.clone()) {
            continue;
        }
        queue.extend(feature_list(features.get(&feature)));
    }
    seen
}

fn enables_frontend(features: &BTreeMap<String, toml::Value>, feature: &str) -> bool {
    closure(features, vec![feature.to_string()])
        .iter()
        .any(|enabled| FRONTENDS.contains(&enabled.trim_start_matches("telar/")))
}

// Cargo.lock only pins what some workspace feature reaches, so a feature named only on the command line resolves against whatever copy of the crates.io index this machine last fetched.
pub(crate) const TOOLING_FEATURES: [&str; 6] = [
    "telar/dev",
    "telar/hot-reload",
    "telar/previews",
    "telar/preview",
    "telar/preview-headless",
    "telar/preview-snapshots",
];

pub(crate) fn tooling_feature_entry() -> String {
    let features = TOOLING_FEATURES
        .map(|feature| format!("\"{feature}\""))
        .join(", ");
    format!("tooling = [{features}]")
}

fn names_feature(features: &BTreeMap<String, toml::Value>, wanted: &str) -> bool {
    let weak = wanted.replacen('/', "?/", 1);
    features
        .values()
        .flat_map(|value| feature_list(Some(value)))
        .any(|feature| feature == wanted || feature == weak)
}

pub(crate) fn unlocked_tooling_note(
    declared: &[BTreeMap<String, toml::Value>],
    injected: &[&str],
) -> Option<String> {
    let unlocked: Vec<String> = injected
        .iter()
        .filter(|feature| {
            !declared
                .iter()
                .any(|features| names_feature(features, feature))
        })
        .map(|feature| format!("`{feature}`"))
        .collect();
    if unlocked.is_empty() {
        return None;
    }
    Some(format!(
        "[cargo-telar] warning: no `[features]` entry in this workspace names {}, so Cargo.lock does not pin what it brings in and a telar upgrade can fail to resolve it. Add this under the app's `[features]`:\n    {}",
        unlocked.join(", "),
        tooling_feature_entry()
    ))
}

pub(crate) fn warn_if_tooling_unlocked(args: &[String], injected: &[&str]) {
    let dir = find_package_dir(args);
    let root = telar_project::find_workspace_root(&dir).unwrap_or(dir);
    let declared: Vec<_> = telar_project::workspace_member_dirs(&root)
        .iter()
        .filter_map(|member| read_manifest_in(member))
        .map(|manifest| manifest.features)
        .collect();
    if let Some(note) = unlocked_tooling_note(&declared, injected) {
        eprintln!("{note}");
    }
}

/// What a package that declares no optional `telar-devtools` is told: the overlay is the application's own dependency, never `telar`'s, so nothing else would explain why a dev session runs without it.
pub(crate) fn missing_devtools_note(package: &str) -> String {
    let devtools = telar_project::DEVTOOLS_PACKAGE;
    format!(
        "`{package}` declares no optional `{devtools}` dependency, so no devtools overlay is built in. Add it with `cargo add -p {package} {devtools} --optional`."
    )
}

/// What a package that declares no optional `telar-workshop` is told when `cargo telar preview` falls back to the page that lists every preview.
pub(crate) fn missing_workshop_note(package: &str) -> String {
    let workshop = telar_project::WORKSHOP_PACKAGE;
    format!(
        "`{package}` declares no optional `{workshop}` dependency, so previews open in a plain page instead of the workshop. Add it with `cargo add -p {package} {workshop} --optional`."
    )
}

/// A `telar` feature that is a crate of its own now, and the feature groups of that crate it stood for.
struct MovedFeature {
    feature: &'static str,
    package: &'static str,
    groups: &'static [&'static str],
}

const COMPONENTS: &str = "telar-components";

/// A plugin with no `.rsx` tags, so moving to it adds nothing to a `prelude`.
const WATCH: &str = "telar-watch";

const MOVED_FEATURES: [MovedFeature; 7] = [
    MovedFeature {
        feature: "components",
        package: COMPONENTS,
        groups: &["overlays", "chrome", "advanced"],
    },
    MovedFeature {
        feature: "components-base",
        package: COMPONENTS,
        groups: &[],
    },
    MovedFeature {
        feature: "components-overlays",
        package: COMPONENTS,
        groups: &["overlays"],
    },
    MovedFeature {
        feature: "components-chrome",
        package: COMPONENTS,
        groups: &["chrome"],
    },
    MovedFeature {
        feature: "components-advanced",
        package: COMPONENTS,
        groups: &["advanced"],
    },
    MovedFeature {
        feature: "navigate",
        package: "telar-navigate",
        groups: &[],
    },
    MovedFeature {
        feature: "watch",
        package: WATCH,
        groups: &[],
    },
];

const DEPENDENCY_TABLES: [&str; 3] = ["dependencies", "dev-dependencies", "build-dependencies"];

/// The moved `telar` features `manifest` turns on: in a `telar` dependency's `features`, or in a `[features]` entry naming `telar/<feature>`. `workspace_dependencies` answers for a `telar = { workspace = true }`, whose features the workspace's own entry carries.
pub(crate) fn moved_telar_features(
    manifest: &toml::Table,
    workspace_dependencies: Option<&toml::Table>,
) -> BTreeSet<&'static str> {
    let targets = manifest
        .get("target")
        .and_then(toml::Value::as_table)
        .into_iter()
        .flat_map(|targets| targets.values())
        .filter_map(toml::Value::as_table);
    let tables: Vec<&toml::Table> = std::iter::once(manifest)
        .chain(targets)
        .flat_map(|scope| DEPENDENCY_TABLES.iter().filter_map(|t| scope.get(*t)))
        .filter_map(toml::Value::as_table)
        .collect();

    let mut keys = BTreeSet::from(["telar".to_string()]);
    let mut named: Vec<String> = Vec::new();
    for (key, dependency) in tables.iter().flat_map(|table| table.iter()) {
        let package = dependency.get("package").and_then(toml::Value::as_str);
        if package.unwrap_or(key) != "telar" {
            continue;
        }
        keys.insert(key.clone());
        named.extend(feature_list(dependency.get("features")));
        if dependency.get("workspace").and_then(toml::Value::as_bool) == Some(true) {
            named.extend(feature_list(
                workspace_dependencies
                    .and_then(|deps| deps.get(key))
                    .and_then(|dependency| dependency.get("features")),
            ));
        }
    }
    let features = manifest.get("features").and_then(toml::Value::as_table);
    for entry in features
        .into_iter()
        .flat_map(|features| features.values())
        .flat_map(|value| feature_list(Some(value)))
    {
        if let Some((dependency, feature)) = entry.split_once('/')
            && keys.contains(dependency.trim_end_matches('?'))
        {
            named.push(feature.to_string());
        }
    }
    MOVED_FEATURES
        .iter()
        .map(|moved| moved.feature)
        .filter(|feature| named.iter().any(|name| name == feature))
        .collect()
}

/// What to run instead of naming `moved`, for `package`, whose prelude is `prelude` today.
///
/// Cargo's own error says only that `telar` has no such feature, which is true and leaves the author to find out where the widgets went. The `[telar] prelude` line repeats the entries already there, so pasting it over the old one loses nothing.
pub(crate) fn moved_features_hint(
    package: &str,
    moved: &BTreeSet<&str>,
    prelude: &[telar_project::PreludeEntry],
) -> Option<String> {
    if moved.is_empty() {
        return None;
    }
    let moved: Vec<&MovedFeature> = MOVED_FEATURES
        .iter()
        .filter(|m| moved.contains(m.feature))
        .collect();
    let mut commands: Vec<String> = Vec::new();
    let mut entries: Vec<String> = prelude.iter().map(ToString::to_string).collect();
    for crate_package in [COMPONENTS, "telar-navigate", WATCH] {
        let wanted: Vec<&&MovedFeature> = moved
            .iter()
            .filter(|m| m.package == crate_package)
            .collect();
        if wanted.is_empty() {
            continue;
        }
        let groups: BTreeSet<&str> = wanted
            .iter()
            .flat_map(|m| m.groups.iter().copied())
            .collect();
        let features = match groups.is_empty() {
            true => String::new(),
            false => format!(
                " --features {}",
                groups.into_iter().collect::<Vec<_>>().join(",")
            ),
        };
        commands.push(format!("cargo add -p {package} {crate_package}{features}"));
        let crate_name = crate_package.replace('-', "_");
        if crate_package != WATCH && !entries.contains(&crate_name) {
            entries.push(crate_name);
        }
    }
    let features = moved
        .iter()
        .map(|m| format!("`{}`", m.feature))
        .collect::<Vec<_>>()
        .join(", ");
    let mut hint = format!(
        "`{package}` turns on `telar` features that are crates of their own now: {features}. Drop them from its `telar` dependency, then run:\n    {}",
        commands.join("\n    ")
    );
    if entries.len() > prelude.len() {
        let quoted = entries
            .iter()
            .map(|entry| format!("\"{entry}\""))
            .collect::<Vec<_>>()
            .join(", ");
        hint.push_str(&format!(
            "\nand name their tags in its telar.toml:\n    [telar]\n    prelude = [{quoted}]"
        ));
    }
    Some(hint)
}

/// [`moved_features_hint`] for the package at `dir`, reading its manifest, its workspace's `[workspace.dependencies]` and its prelude.
pub(crate) fn moved_features_hint_for(dir: &Path) -> Option<String> {
    let manifest: toml::Table = std::fs::read_to_string(dir.join("Cargo.toml"))
        .ok()?
        .parse()
        .ok()?;
    let workspace: Option<toml::Table> = telar_project::find_workspace_root(dir)
        .and_then(|root| std::fs::read_to_string(root.join("Cargo.toml")).ok())
        .and_then(|content| content.parse().ok());
    let workspace_dependencies = workspace
        .as_ref()
        .and_then(|root| root.get("workspace"))
        .and_then(|workspace| workspace.get("dependencies"))
        .and_then(toml::Value::as_table);
    let moved = moved_telar_features(&manifest, workspace_dependencies);
    let package = manifest
        .get("package")
        .and_then(|package| package.get("name"))
        .and_then(toml::Value::as_str)?;
    let prelude = telar_project::resolve_prelude(dir).unwrap_or_default();
    moved_features_hint(package, &moved, &prelude)
}

/// Prints [`moved_features_hint_for`] for every member of the workspace `args` select.
pub(crate) fn warn_if_features_moved(args: &[String]) {
    let dir = find_package_dir(args);
    let root = telar_project::find_workspace_root(&dir).unwrap_or(dir);
    for member in telar_project::workspace_member_dirs(&root) {
        if let Some(hint) = moved_features_hint_for(&member) {
            eprintln!("[cargo-telar] warning: {hint}");
        }
    }
}

// dpkg reads the maintainer from `DEBFULLNAME`/`DEBEMAIL`, so honour the same pair: cargo stopped emitting `authors` years ago, and refusing every manifest without it would rule out most projects.
fn maintainer_from_env() -> Option<String> {
    maintainer_from(
        std::env::var("DEBFULLNAME").ok(),
        std::env::var("DEBEMAIL").ok(),
    )
}

fn maintainer_from(name: Option<String>, email: Option<String>) -> Option<String> {
    let email = email?;
    let email = email.trim();
    if email.is_empty() {
        return None;
    }
    match name {
        Some(name) if !name.trim().is_empty() => Some(format!("{} <{email}>", name.trim())),
        _ => Some(email.to_string()),
    }
}

// Resolved in a single pass, so the packaging paths stop re-deriving them at each call site.
pub(crate) fn resolve_package(args: &[String]) -> ResolvedPackage {
    let dir = find_package_dir(args);
    let workspace_root = telar_project::find_workspace_root(&dir).unwrap_or_else(|| dir.clone());
    let manifest = read_manifest_in(&dir);
    let produces_cdylib = manifest
        .as_ref()
        .and_then(|m| m.lib.as_ref())
        .is_some_and(|lib| lib.crate_type.iter().any(|kind| kind == "cdylib"));
    // The member's own manifest when it is also the workspace root, so a single-crate project inherits from itself without a second read.
    let workspace_package = if workspace_root == dir {
        manifest.as_ref()
    } else {
        None
    }
    .and_then(|m| m.workspace.as_ref())
    .and_then(|w| w.package.clone())
    .or_else(|| read_manifest_in(&workspace_root)?.workspace?.package);
    let features = manifest
        .as_ref()
        .map(|m| m.features.clone())
        .unwrap_or_default();
    ResolvedPackage {
        workspace_root,
        package_dir: dir,
        package: manifest.and_then(|m| m.package),
        workspace_package,
        produces_cdylib,
        features,
    }
}

// Shared by the Android package id and macOS bundle id defaults, which are otherwise distinct.
pub(crate) fn default_app_id(name: &str) -> String {
    format!("com.example.{name}")
}

#[derive(Deserialize)]
struct ManifestTelarOnly {
    package: Option<PackageTelarOnly>,
}
#[derive(Deserialize)]
struct PackageTelarOnly {
    metadata: Option<MetadataTelarOnly>,
}
#[derive(Deserialize)]
struct MetadataTelarOnly {
    telar: Option<TelarSection>,
}

// Only `package.metadata.telar` is held to the telar schema; the rest of Cargo.toml is cargo's. Absent is `Ok(None)`, present but invalid is an error, as it is for telar.toml.
pub(crate) fn read_manifest_telar(dir: &Path) -> Result<Option<TelarSection>, ManifestError> {
    let path = dir.join("Cargo.toml");
    let Ok(content) = std::fs::read_to_string(&path) else {
        return Ok(None);
    };
    let parsed =
        toml::from_str::<ManifestTelarOnly>(&content).map_err(|e| ManifestError::Invalid {
            path,
            message: e.to_string(),
        })?;
    Ok(parsed
        .package
        .and_then(|p| p.metadata)
        .and_then(|m| m.telar))
}

/// The `[profile.web]` entry `cargo telar new`/`init` writes for a web target, and what `doctor` and
/// `build --target web` point at when a project is missing it. Kept as one string so the three call sites
/// can never drift apart on what the fix is.
pub(crate) const WEB_PROFILE_TOML: &str =
    "[profile.web]\ninherits = \"release\"\nopt-level = \"z\"\npanic = \"abort\"\n";

/// Whether `workspace_root`'s Cargo.toml declares `[profile.web]`. Cargo only reads `[profile.*]` from the
/// manifest at the root of the build — a workspace root, or a standalone package's own manifest when it
/// is not part of one — so that is the one file worth checking regardless of which member is building.
pub(crate) fn has_web_profile(workspace_root: &Path) -> bool {
    let Ok(content) = std::fs::read_to_string(workspace_root.join("Cargo.toml")) else {
        return false;
    };
    let Ok(value) = toml::from_str::<toml::Value>(&content) else {
        return false;
    };
    value
        .get("profile")
        .and_then(|profile| profile.get("web"))
        .is_some()
}

// Lowest to highest: built-in defaults, `[package.metadata.telar]`, `telar.toml`. The CLI flags are layered on by each command.
//
// A key the schema does not recognise in either file is an error: a project that misspelled one has configured nothing, and carrying on would run a build the author did not ask for.
pub(crate) fn try_load_config(dir: &Path) -> Result<TelarSection, ManifestError> {
    let manifest = read_manifest_telar(dir)?.unwrap_or_default();
    Ok(merge_config(manifest, TelarManifest::load(dir)?.telar))
}

pub(crate) fn load_config(args: &[String]) -> TelarSection {
    match try_load_config(&find_package_dir(args)) {
        Ok(config) => config,
        Err(e) => {
            eprintln!("[cargo-telar] {e}");
            std::process::exit(2);
        }
    }
}

fn merge_opt<T>(base: Option<T>, over: Option<T>, merge: impl FnOnce(T, T) -> T) -> Option<T> {
    match (base, over) {
        (Some(b), Some(o)) => Some(merge(b, o)),
        (b, o) => o.or(b),
    }
}

fn merge_window(base: WindowSection, over: WindowSection) -> WindowSection {
    WindowSection {
        title: over.title.or(base.title),
        width: over.width.or(base.width),
        height: over.height.or(base.height),
        decorations: over.decorations.or(base.decorations),
        resizable: over.resizable.or(base.resizable),
        transparent: over.transparent.or(base.transparent),
        fullscreen: over.fullscreen.or(base.fullscreen),
        position: over.position.or(base.position),
    }
}

fn merge_dev(base: DevSection, over: DevSection) -> DevSection {
    DevSection {
        window: merge_opt(base.window, over.window, merge_window),
        devtools: over.devtools.or(base.devtools),
    }
}

fn merge_config(base: TelarSection, over: TelarSection) -> TelarSection {
    TelarSection {
        backend: over.backend.or(base.backend),
        dev: merge_dev(base.dev, over.dev),
        // Everything else is read from the package's own `telar.toml` by whoever needs it, never from `[package.metadata.telar]`, so a merge would only invent a precedence nothing reads.
        ..over
    }
}

pub(crate) fn backend_as_str(backend: RendererBackend) -> &'static str {
    match backend {
        RendererBackend::Auto => "auto",
        RendererBackend::Hardware => "hardware",
        RendererBackend::Software => "software",
    }
}

pub(crate) fn split_android_flag(args: Vec<String>) -> (bool, Vec<String>) {
    let android = args.contains(&"--android".to_string());
    let rest = args.into_iter().filter(|a| a != "--android").collect();
    (android, rest)
}

/// Says so when this binary is not the one the project it is about to build was written against.
///
/// The two halves agree through the artifact format, not through version numbers, so a difference here is usually harmless: same format, compatible output, nothing to do. What it must not be is *invisible*. When the formats do differ the macro refuses with a message naming a command, and the one fact that would explain it — that the installed CLI is not this project's — is the one nobody is told. Hence a note rather than a warning: most of the time it is not the problem.
pub(crate) fn foreign_version_note(project_telar: &str) -> Option<String> {
    let ours = env!("CARGO_PKG_VERSION");
    if project_telar == ours {
        return None;
    }
    Some(format!(
        "[cargo-telar] note: this project builds telar {project_telar}, and this is cargo-telar {ours}. If a build refuses what was transpiled, the versions are why: cargo install cargo-telar --version {project_telar} --force"
    ))
}

/// The same, said once per invocation however many passes ask.
pub(crate) fn warn_if_foreign_version(project_telar: &str) {
    static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
    if let Some(note) = foreign_version_note(project_telar)
        && !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed)
    {
        eprintln!("{note}");
    }
}

#[cfg(test)]
#[path = "config_test.rs"]
mod tests;