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
use serde::Serialize;
use serde::de::DeserializeOwned;
use crate::{ConfigError, TierPatch};
use super::super::{ConfigLoader, PendingCustomLayer, SourceKind, SourceTrace};
impl<T> ConfigLoader<T>
where
T: Serialize + DeserializeOwned,
{
/// Adds a typed sparse patch as a custom layer.
///
/// This keeps sparse overrides typed and avoids maintaining a parallel
/// serializable shadow hierarchy just to build a [`Layer`](crate::Layer).
///
/// # Examples
///
/// ```no_run
/// # #[cfg(feature = "derive")] {
/// # fn main() -> Result<(), tier::ConfigError> {
/// use serde::{Deserialize, Serialize};
/// use tier::{ConfigLoader, TierPatch};
///
/// #[derive(Debug, Clone, Serialize, Deserialize)]
/// struct AppConfig {
/// port: u16,
/// }
///
/// #[derive(Debug, TierPatch, Default)]
/// struct CliPatch {
/// port: Option<u16>,
/// }
///
/// let loaded = ConfigLoader::new(AppConfig { port: 3000 })
/// .patch("typed-cli", &CliPatch { port: Some(7000) })?
/// .load()?;
///
/// assert_eq!(loaded.port, 7000);
/// # Ok(())
/// # }
/// # }
/// ```
pub fn patch<P>(mut self, name: impl Into<String>, patch: &P) -> Result<Self, ConfigError>
where
P: TierPatch,
{
let mut builder = crate::patch::PatchLayerBuilder::from_trace_deferred(SourceTrace {
kind: SourceKind::Custom,
name: name.into(),
location: None,
});
patch.write_layer(&mut builder, "")?;
let layer = builder.finish_deferred();
if !layer.is_empty() {
self.custom_layers
.push(PendingCustomLayer::DeferredPatch(layer));
}
Ok(self)
}
#[cfg(feature = "clap")]
/// Adds a typed `clap`-style sparse override struct as the last CLI layer.
///
/// This is the ergonomic bridge for applications that already parse a
/// typed `clap` CLI and want to feed the parsed values into `tier` without
/// building a manual shadow patch struct.
///
/// `clap` remains responsible for CLI grammar, subcommands, trailing args,
/// and parse-time validation. `tier` only applies the already-parsed typed
/// values as a last-layer configuration patch.
///
/// # Examples
///
/// ```no_run
/// # #[cfg(all(feature = "derive", feature = "clap"))] {
/// # fn main() -> Result<(), tier::ConfigError> {
/// use clap::Parser;
/// use serde::{Deserialize, Serialize};
/// use tier::{ConfigLoader, TierPatch};
///
/// #[derive(Debug, Clone, Serialize, Deserialize)]
/// struct AppConfig {
/// port: u16,
/// token: Option<String>,
/// }
///
/// #[derive(Debug, Parser, TierPatch)]
/// struct AppCli {
/// #[arg(long)]
/// port: Option<u16>,
/// #[arg(long = "db-token")]
/// #[tier(path_expr = tier::path!(AppConfig.token))]
/// token: Option<String>,
/// }
///
/// let cli = AppCli::parse_from(["app", "--port", "8080", "--db-token", "from-cli"]);
/// let loaded = ConfigLoader::new(AppConfig {
/// port: 3000,
/// token: None,
/// })
/// .clap_overrides(&cli)?
/// .load()?;
///
/// assert_eq!(loaded.port, 8080);
/// assert_eq!(loaded.token.as_deref(), Some("from-cli"));
/// # Ok(())
/// # }
/// # }
/// ```
pub fn clap_overrides<P>(mut self, patch: &P) -> Result<Self, ConfigError>
where
P: TierPatch,
{
let mut builder = crate::patch::PatchLayerBuilder::from_trace_deferred(SourceTrace {
kind: SourceKind::Arguments,
name: "typed-clap".to_owned(),
location: None,
});
patch.write_layer(&mut builder, "")?;
let layer = builder.finish_deferred();
if !layer.is_empty() {
self.typed_arg_layers.push(layer);
}
Ok(self)
}
#[cfg(feature = "clap")]
/// Projects a parsed CLI value onto the config-bearing patch portion and
/// applies it as the last CLI layer.
///
/// This is the CLI-first companion to [`ConfigLoader::clap_overrides`].
/// It lets an application keep a full `clap` model with subcommands,
/// positional arguments, or trailing args, while only the selected
/// config-bearing sub-structure participates in `tier` overrides.
///
/// # Examples
///
/// ```no_run
/// # #[cfg(all(feature = "derive", feature = "clap"))] {
/// # fn main() -> Result<(), tier::ConfigError> {
/// use clap::{Parser, Subcommand};
/// use serde::{Deserialize, Serialize};
/// use tier::{ConfigLoader, TierPatch};
///
/// #[derive(Debug, Clone, Serialize, Deserialize)]
/// struct AppConfig {
/// port: u16,
/// }
///
/// #[derive(Debug, Clone, clap::Args, TierPatch, Default)]
/// struct ConfigArgs {
/// #[arg(long)]
/// port: Option<u16>,
/// }
///
/// #[derive(Debug, Clone, Subcommand)]
/// enum Command {
/// Serve {
/// #[arg(last = true)]
/// trailing: Vec<String>,
/// },
/// }
///
/// #[derive(Debug, Clone, Parser)]
/// struct AppCli {
/// #[command(flatten)]
/// config: ConfigArgs,
/// #[command(subcommand)]
/// command: Option<Command>,
/// }
///
/// let cli = AppCli::parse_from(["app", "--port", "8080", "serve", "--", "extra"]);
/// let loaded = ConfigLoader::new(AppConfig { port: 3000 })
/// .clap_overrides_from(&cli, |cli| &cli.config)?
/// .load()?;
///
/// assert_eq!(loaded.port, 8080);
/// # Ok(())
/// # }
/// # }
/// ```
pub fn clap_overrides_from<C, P, F>(self, cli: &C, project: F) -> Result<Self, ConfigError>
where
P: TierPatch,
F: FnOnce(&C) -> &P,
{
self.clap_overrides(project(cli))
}
}