scarb-metadata 1.15.1

Structured access to the output of `scarb metadata`
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
#![deny(missing_docs)]
#![warn(rustdoc::broken_intra_doc_links)]
#![deny(rustdoc::private_intra_doc_links)]
#![warn(rust_2018_idioms)]
#![doc = concat!(
    "Structured access to the output of `scarb metadata --format-version ",
    env!("CARGO_PKG_VERSION_MAJOR"),
    "`.
")]
//! Usually used by Scarb extensions and other developer tools.
//!
//! [Scarb](https://docs.swmansion.com/scarb) is a build toolchain and package manager for
//! the [Cairo language](https://www.cairo-lang.org/).
//! See the [Scarb documentation](https://docs.swmansion.com/scarb/docs.html) for details on
//! Scarb itself.
//!
//! With the `command` feature (enabled by default), this crate also exposes an ergonomic interface
//! to collect metadata from Scarb: [`MetadataCommand`].

use std::collections::{BTreeMap, HashMap};
use std::fmt;
use std::ops::Index;
use std::path::PathBuf;

use camino::{Utf8Path, Utf8PathBuf};
#[cfg(feature = "builder")]
use derive_builder::Builder;
use semver::{Version, VersionReq};
use serde::{Deserialize, Serialize};

#[cfg(feature = "command")]
pub use command::*;
pub use version_pin::*;

#[cfg(feature = "command")]
mod command;
mod version_pin;

/// An "opaque" identifier for a package.
/// It is possible to inspect the `repr` field if the need arises,
/// but its precise format is an implementation detail and is subject to change.
///
/// [`Metadata`] can be indexed by [`PackageId`].
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(transparent)]
pub struct PackageId {
    /// The underlying string representation of the ID.
    pub repr: String,
}

impl From<String> for PackageId {
    fn from(repr: String) -> Self {
        Self { repr }
    }
}

impl fmt::Display for PackageId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.repr, f)
    }
}

/// An "opaque" identifier for a source.
/// It is possible to inspect the `repr` field if the need arises,
/// but its precise format is an implementation detail and is subject to change.
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(transparent)]
pub struct SourceId {
    /// The underlying string representation of the ID.
    pub repr: String,
}

impl From<String> for SourceId {
    fn from(repr: String) -> Self {
        Self { repr }
    }
}

impl fmt::Display for SourceId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.repr, f)
    }
}

/// An "opaque" identifier for a compilation unit.
/// It is possible to inspect the `repr` field if the need arises,
/// but its precise format is an implementation detail and is subject to change.
///
/// [`Metadata`] can be indexed by [`CompilationUnitId`].
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(transparent)]
pub struct CompilationUnitId {
    /// The underlying string representation of the ID.
    pub repr: String,
}

impl From<String> for CompilationUnitId {
    fn from(repr: String) -> Self {
        Self { repr }
    }
}

impl fmt::Display for CompilationUnitId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.repr, f)
    }
}

/// An "opaque" identifier for a compilation unit component.
/// It is possible to inspect the `repr` field if the need arises,
/// but its precise format is an implementation detail and is subject to change.
///
/// [`CompilationUnitMetadata`] can be indexed by [`CompilationUnitComponentId`].
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(transparent)]
pub struct CompilationUnitComponentId {
    /// The underlying string representation of the ID.
    pub repr: String,
}

impl From<String> for CompilationUnitComponentId {
    fn from(repr: String) -> Self {
        Self { repr }
    }
}

impl fmt::Display for CompilationUnitComponentId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.repr, f)
    }
}

fn current_profile_default() -> String {
    "release".to_string()
}
fn profiles_default() -> Vec<String> {
    vec!["release".to_string()]
}

/// Top level data structure printed by `scarb metadata`.
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "builder", derive(Builder))]
#[cfg_attr(feature = "builder", builder(setter(into)))]
#[non_exhaustive]
pub struct Metadata {
    /// The metadata format version.
    ///
    /// This struct will not deserialize if version does not match.
    #[cfg_attr(feature = "builder", builder(setter(skip)))]
    pub version: VersionPin,

    /// Path to `scarb` executable.
    pub app_exe: Option<PathBuf>,

    /// Scarb's version.
    pub app_version_info: VersionInfo,

    /// Path to the _target_ (_build_) directory if known by Scarb at the moment of generating
    /// metadata.
    pub target_dir: Option<Utf8PathBuf>,

    /// Path to the manifest of package or workspace that Scarb has been run from.
    ///
    /// ## Compatibility
    ///
    /// With very old Scarb versions (`<0.5.0`), this field may end up being empty path upon
    /// deserializing from `scarb metadata` call.
    /// In this case, fall back to [`WorkspaceMetadata.manifest`][WorkspaceMetadata] field value.
    #[serde(default)]
    pub runtime_manifest: Utf8PathBuf,

    /// Current workspace metadata.
    pub workspace: WorkspaceMetadata,

    /// Metadata of all packages used in this workspace, or just members of it if this is an output
    /// of `scarb metadata --no-deps`.
    ///
    /// In the former case, use [`WorkspaceMetadata::members`] to filter workspace members.
    pub packages: Vec<PackageMetadata>,

    /// List of all Scarb compilation units produced in this workspace.
    pub compilation_units: Vec<CompilationUnitMetadata>,

    /// Name of the currently selected profile
    #[serde(default = "current_profile_default")]
    pub current_profile: String,

    /// List of all available profiles names
    #[serde(default = "profiles_default")]
    pub profiles: Vec<String>,

    /// Additional data not captured by deserializer.
    #[cfg_attr(feature = "builder", builder(default))]
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Current workspace metadata.
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "builder", derive(Builder))]
#[cfg_attr(feature = "builder", builder(setter(into)))]
#[non_exhaustive]
pub struct WorkspaceMetadata {
    /// Path to the manifest file defining this workspace.
    pub manifest_path: Utf8PathBuf,

    /// Path to the directory containing this workspace.
    pub root: Utf8PathBuf,

    /// List of IDs of all packages that are members of this workspace.
    pub members: Vec<PackageId>,

    /// Additional data not captured by deserializer.
    #[cfg_attr(feature = "builder", builder(default))]
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Metadata of single Scarb package.
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "builder", derive(Builder))]
#[cfg_attr(feature = "builder", builder(setter(into)))]
#[non_exhaustive]
pub struct PackageMetadata {
    /// Package ID.
    pub id: PackageId,

    /// Package name as given in `Scarb.toml`.
    pub name: String,

    /// Package version as given in `Scarb.toml`.
    pub version: Version,

    /// Package edition as given in `Scarb.toml`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub edition: Option<String>,

    /// The source of the package.
    pub source: SourceId,

    /// Path to the manifest file defining this package.
    pub manifest_path: Utf8PathBuf,

    /// Path to the directory containing this package.
    pub root: Utf8PathBuf,

    /// List of dependencies of this particular package.
    pub dependencies: Vec<DependencyMetadata>,

    /// Targets provided by the package. (`lib`, `starknet-contract`, etc.).
    pub targets: Vec<TargetMetadata>,

    /// Various metadata fields from `Scarb.toml`.
    #[serde(flatten)]
    pub manifest_metadata: ManifestMetadata,

    /// Compiler experimental features allowed for this package.
    #[serde(default)]
    pub experimental_features: Vec<String>,

    /// Additional data not captured by deserializer.
    #[cfg_attr(feature = "builder", builder(default))]
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Dependency kind.
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub enum DepKind {
    /// Development dependency.
    Dev,
}

/// Scarb package dependency specification.
///
/// Only the `name` field is strictly sourced from `Scarb.toml`, the rest is processed by Scarb
/// when processing this file.
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "builder", derive(Builder))]
#[cfg_attr(feature = "builder", builder(setter(into)))]
#[non_exhaustive]
pub struct DependencyMetadata {
    /// Package name.
    pub name: String,
    /// Package version requirement.
    pub version_req: VersionReq,
    /// Package source.
    pub source: SourceId,
    /// Dependency kind. None denotes normal dependency.
    pub kind: Option<DepKind>,
    /// Features to be enabled for this dependency.
    pub features: Option<Vec<String>>,
    /// Whether to use default features.
    pub default_features: Option<bool>,

    /// Additional data not captured by deserializer.
    #[cfg_attr(feature = "builder", builder(default))]
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Package target information.
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "builder", derive(Builder))]
#[cfg_attr(feature = "builder", builder(setter(into)))]
#[non_exhaustive]
pub struct TargetMetadata {
    /// Target kind: `lib`, `starknet-contract`, etc.
    pub kind: String,
    /// Target name, often this is a default, which is the package name.
    pub name: String,
    /// Path to the main source file of the target.
    pub source_path: Utf8PathBuf,
    /// Unstructured target parameters, excluding default values.
    ///
    /// Default values are omitted because they are unknown to Scarb, they are applied by compilers.
    pub params: serde_json::Value,

    /// Additional data not captured by deserializer.
    #[cfg_attr(feature = "builder", builder(default))]
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Scarb compilation unit information.
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "builder", derive(Builder))]
#[cfg_attr(feature = "builder", builder(setter(into)))]
#[non_exhaustive]
pub struct CompilationUnitMetadata {
    /// Unique ID of this compilation unit.
    pub id: CompilationUnitId,

    /// Main package to be built.
    pub package: PackageId,

    /// Selected target of the main package.
    pub target: TargetMetadata,

    /// Cairo compiler config.
    ///
    /// This is unstructured, because this can rapidly change throughout Scarb lifetime.
    pub compiler_config: serde_json::Value,

    // TODO(mkaput): Perhaps rename this back to `components` in Scarb >=0.3?
    /// List of all components to include in this compilation.
    #[serde(rename = "components_data")]
    pub components: Vec<CompilationUnitComponentMetadata>,

    /// List of all Cairo compiler plugins to load in this compilation.
    #[serde(default)]
    pub cairo_plugins: Vec<CompilationUnitCairoPluginMetadata>,

    /// Items for the Cairo's `#[cfg(...)]` attribute to be enabled in this unit.
    #[serde(default)]
    pub cfg: Vec<Cfg>,

    /// Additional data not captured by deserializer.
    #[cfg_attr(feature = "builder", builder(default))]
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Information to pass to the Cairo compiler about a package that is a component of a compilation
/// unit.
///
/// List of components can be used to construct the `[crate_roots]` section of `cairo_project.toml`.
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "builder", derive(Builder))]
#[cfg_attr(feature = "builder", builder(setter(into)))]
#[non_exhaustive]
pub struct CompilationUnitComponentMetadata {
    /// Package ID.
    pub package: PackageId,
    /// Name of the package to pass to the Cairo compiler.
    ///
    /// This may not be equal to Scarb package name in the future.
    pub name: String,
    /// Path to the root Cairo source file.
    pub source_path: Utf8PathBuf,
    /// Items for the Cairo's `#[cfg(...)]` attribute to be enabled in this component.
    ///
    /// If not specified, the one from `CompilationUnit` will be used.
    #[serde(default)]
    pub cfg: Option<Vec<Cfg>>,
    /// Identifier of this component. It is unique in its compilation unit.
    pub id: Option<CompilationUnitComponentId>,
    /// Identifier of this component as a dependency.
    /// This directly translates to a `discriminator` field in Cairo compiler terminology.
    /// If [`CompilationUnitComponentMetadata.id`] is [`Some`]
    /// then this field is [`None`] for `core` crate **only**.
    pub discriminator: Option<String>,
    /// Dependencies of this component.
    /// Contains libraries and plugins, represented uniquely in the scope of the compilation unit.
    pub dependencies: Option<Vec<CompilationUnitComponentDependencyMetadata>>,

    /// Additional data not captured by deserializer.
    #[cfg_attr(feature = "builder", builder(default))]
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Information about dependency of a component of a compilation unit.
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "builder", derive(Builder))]
#[cfg_attr(feature = "builder", builder(setter(into)))]
#[non_exhaustive]
pub struct CompilationUnitComponentDependencyMetadata {
    /// An id of a component from the same compilation unit that this dependency refers to.
    /// It represents either a library or a plugin. It is guaranteed to be unique
    /// in the scope of the compilation unit.
    pub id: CompilationUnitComponentId,

    /// Additional data not captured by deserializer.
    #[cfg_attr(feature = "builder", builder(default))]
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Information about compiler plugin to load into the Cairo compiler as part of a compilation unit.
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "builder", derive(Builder))]
#[cfg_attr(feature = "builder", builder(setter(into)))]
#[non_exhaustive]
pub struct CompilationUnitCairoPluginMetadata {
    /// Package ID.
    pub package: PackageId,

    /// An id which uniquely identifies the plugin in scope of the compilation unit
    /// amongst other plugins and CU components.
    /// It is used to identify the plugin as a possible dependency of a CU component.
    pub component_dependency_id: Option<CompilationUnitComponentId>,

    /// Whether Scarb will attempt to load prebuilt binaries associated with this plugin.
    pub prebuilt_allowed: Option<bool>,

    /// Additional data not captured by deserializer.
    #[cfg_attr(feature = "builder", builder(default))]
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Various metadata fields from package manifest.
#[derive(Clone, Serialize, Deserialize, Debug, Default, Eq, PartialEq)]
#[cfg_attr(feature = "builder", derive(Builder))]
#[cfg_attr(feature = "builder", builder(setter(into)))]
#[non_exhaustive]
pub struct ManifestMetadata {
    /// List of the people or organizations that are considered the "authors" of the package.
    pub authors: Option<Vec<String>>,
    /// A short blurb about the package.
    pub description: Option<String>,
    /// A URL to a website hosting the crate's documentation.
    pub documentation: Option<String>,
    /// A URL to a site that is the home page for this package.
    pub homepage: Option<String>,
    /// An array of strings that describe this package.
    pub keywords: Option<Vec<String>>,
    /// Name of the software license that the package is released under.
    ///
    /// Should be an [SPDX 2 license expression(opens in a new tab)](https://spdx.github.io/spdx-spec/v2.3/SPDX-license-expressions/),
    /// but this is not validated neither by this crate nor Scarb.
    pub license: Option<String>,
    /// A path to a file containing the text of package's license (relative to its `Scarb.toml`).
    pub license_file: Option<String>,
    /// A path to a file in the package root (relative to its `Scarb.toml`) that contains general
    /// information about the package.
    pub readme: Option<String>,
    /// A URL to the source repository for this package.
    pub repository: Option<String>,
    /// A map of additional internet links related to this package.
    pub urls: Option<BTreeMap<String, String>>,
    /// Various unstructured metadata to be used by external tools.
    pub tool: Option<BTreeMap<String, serde_json::Value>>,
}

/// Scarb's version.
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "builder", derive(Builder))]
#[cfg_attr(feature = "builder", builder(setter(into)))]
#[non_exhaustive]
pub struct VersionInfo {
    /// Version of Scarb.
    pub version: Version,
    /// Version about Git commit of Scarb if known.
    pub commit_info: Option<CommitInfo>,
    /// Version of the Cairo compiler bundled in Scarb.
    pub cairo: CairoVersionInfo,

    /// Additional data not captured by deserializer.
    #[cfg_attr(feature = "builder", builder(default))]
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Cairo's version.
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "builder", derive(Builder))]
#[cfg_attr(feature = "builder", builder(setter(into)))]
#[non_exhaustive]
pub struct CairoVersionInfo {
    /// Version of the Cairo compiler.
    pub version: Version,
    /// Version about Git commit of Cairo if known.
    pub commit_info: Option<CommitInfo>,

    /// Additional data not captured by deserializer.
    #[cfg_attr(feature = "builder", builder(default))]
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Information about the Git repository where Scarb or Cairo was built from.
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "builder", derive(Builder))]
#[cfg_attr(feature = "builder", builder(setter(into)))]
#[non_exhaustive]
pub struct CommitInfo {
    /// Git commit hash, shortened.
    pub short_commit_hash: String,
    /// Git commit hash.
    pub commit_hash: String,
    /// Commit author date if known.
    pub commit_date: Option<String>,
}

/// Option for the `#[cfg(...)]` language attribute.
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
#[serde(untagged)]
pub enum Cfg {
    /// `#[cfg(key: value)`]
    KV(String, String),
    /// `#[cfg(name)`]
    Name(String),
}

impl Metadata {
    /// Returns reference to [`PackageMetadata`] corresponding to the [`PackageId`].
    pub fn get_package(&self, id: &PackageId) -> Option<&PackageMetadata> {
        self.packages.iter().find(|p| p.id == *id)
    }

    /// Checks if the plugin associated with [`CompilationUnitCairoPluginMetadata`] is built-in into Scarb.
    pub fn is_builtin_plugin(&self, plugin: &CompilationUnitCairoPluginMetadata) -> Option<bool> {
        self.get_package(&plugin.package)?
            .targets
            .iter()
            .find(|&target| target.kind == "cairo-plugin")
            .map(|target| {
                target
                    .params
                    .get("builtin")
                    .and_then(|value| value.as_bool())
                    .unwrap_or_default()
            })
    }

    /// Returns reference to [`CompilationUnitMetadata`] corresponding to the [`CompilationUnitId`].
    pub fn get_compilation_unit(&self, id: &CompilationUnitId) -> Option<&CompilationUnitMetadata> {
        self.compilation_units.iter().find(|p| p.id == *id)
    }
}

impl<'a> Index<&'a PackageId> for Metadata {
    type Output = PackageMetadata;

    fn index(&self, idx: &'a PackageId) -> &Self::Output {
        self.get_package(idx)
            .unwrap_or_else(|| panic!("no package with this ID: {idx}"))
    }
}

impl<'a> Index<&'a CompilationUnitId> for Metadata {
    type Output = CompilationUnitMetadata;

    fn index(&self, idx: &'a CompilationUnitId) -> &Self::Output {
        self.get_compilation_unit(idx)
            .unwrap_or_else(|| panic!("no compilation unit with this ID: {idx}"))
    }
}

impl PackageMetadata {
    /// Get value of the `[tool.*]` section in this package's manifest, for specific `tool_name`,
    /// including any transformations applied by Scarb.
    pub fn tool_metadata(&self, tool_name: &str) -> Option<&serde_json::Value> {
        self.manifest_metadata.tool.as_ref()?.get(tool_name)
    }
}

impl TargetMetadata {
    /// Path to the main source directory of the target.
    pub fn source_root(&self) -> &Utf8Path {
        self.source_path
            .parent()
            .expect("Source path is guaranteed to point to a file.")
    }
}

impl CompilationUnitComponentMetadata {
    /// Path to the source directory of the component.
    pub fn source_root(&self) -> &Utf8Path {
        self.source_path
            .parent()
            .expect("Source path is guaranteed to point to a file.")
    }
}

impl<'a> Index<&'a CompilationUnitComponentId> for CompilationUnitMetadata {
    type Output = CompilationUnitComponentMetadata;

    fn index(&self, idx: &'a CompilationUnitComponentId) -> &Self::Output {
        self.components
            .iter()
            .find(|p| p.id.as_ref() == Some(idx))
            .unwrap_or_else(|| panic!("no compilation unit with this ID: {idx}"))
    }
}