Skip to content

Commit a4eceb7

Browse files
author
developerworks
committed
补齐源码注释和 doctest
1 parent 9abf9c3 commit a4eceb7

24 files changed

Lines changed: 3272 additions & 0 deletions

src/cli.rs

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,45 @@ pub enum ConfigCommand {
8484
/// # Returns
8585
///
8686
/// Returns `Ok(())` after the selected subcommand completes.
87+
///
88+
/// # Examples
89+
///
90+
/// ```no_run
91+
/// use clap::{Parser, Subcommand};
92+
/// use confique::Config;
93+
/// use rust_config_tree::{ConfigCommand, ConfigSchema, handle_config_command};
94+
/// use schemars::JsonSchema;
95+
///
96+
/// #[derive(Parser)]
97+
/// struct Cli {
98+
/// #[command(subcommand)]
99+
/// command: Command,
100+
/// }
101+
///
102+
/// #[derive(Subcommand)]
103+
/// enum Command {
104+
/// #[command(flatten)]
105+
/// Config(ConfigCommand),
106+
/// }
107+
///
108+
/// #[derive(Config, JsonSchema)]
109+
/// struct AppConfig {
110+
/// #[config(default = [])]
111+
/// include: Vec<std::path::PathBuf>,
112+
/// }
113+
///
114+
/// impl ConfigSchema for AppConfig {
115+
/// fn include_paths(layer: &<Self as Config>::Layer) -> Vec<std::path::PathBuf> {
116+
/// layer.include.clone().unwrap_or_default()
117+
/// }
118+
/// }
119+
///
120+
/// handle_config_command::<Cli, AppConfig>(
121+
/// ConfigCommand::ConfigValidate,
122+
/// std::path::Path::new("config.yaml"),
123+
/// )?;
124+
/// # Ok::<(), rust_config_tree::ConfigError>(())
125+
/// ```
87126
pub fn handle_config_command<C, S>(command: ConfigCommand, config_path: &Path) -> ConfigResult<()>
88127
where
89128
C: CommandFactory,
@@ -127,6 +166,20 @@ where
127166
/// # Returns
128167
///
129168
/// This function writes to stdout and returns no value.
169+
///
170+
/// # Examples
171+
///
172+
/// ```no_run
173+
/// use clap::Parser;
174+
/// use clap_complete::aot::Shell;
175+
/// use rust_config_tree::print_shell_completion;
176+
///
177+
/// #[derive(Parser)]
178+
/// #[command(name = "myapp")]
179+
/// struct Cli {}
180+
///
181+
/// print_shell_completion::<Cli>(Shell::Bash);
182+
/// ```
130183
pub fn print_shell_completion<C>(shell: Shell)
131184
where
132185
C: CommandFactory,
@@ -150,6 +203,21 @@ where
150203
///
151204
/// Returns `Ok(())` after the completion file is generated and any required
152205
/// startup file has been updated.
206+
///
207+
/// # Examples
208+
///
209+
/// ```no_run
210+
/// use clap::Parser;
211+
/// use clap_complete::aot::Shell;
212+
/// use rust_config_tree::install_shell_completion;
213+
///
214+
/// #[derive(Parser)]
215+
/// #[command(name = "myapp")]
216+
/// struct Cli {}
217+
///
218+
/// install_shell_completion::<Cli>(Shell::Zsh)?;
219+
/// # Ok::<(), rust_config_tree::ConfigError>(())
220+
/// ```
153221
pub fn install_shell_completion<C>(shell: Shell) -> ConfigResult<()>
154222
where
155223
C: CommandFactory,
@@ -185,9 +253,19 @@ where
185253

186254
/// Resolves the current user's home directory from environment variables.
187255
///
256+
/// # Arguments
257+
///
258+
/// This function has no arguments.
259+
///
188260
/// # Returns
189261
///
190262
/// Returns the home directory when `HOME` or `USERPROFILE` is set.
263+
///
264+
/// # Examples
265+
///
266+
/// ```no_run
267+
/// // Internal helper; use `install_shell_completion` to resolve install paths.
268+
/// ```
191269
fn home_dir() -> Option<PathBuf> {
192270
std::env::var_os("HOME")
193271
.map(PathBuf::from)
@@ -218,6 +296,12 @@ impl ShellInstallTarget {
218296
/// # Returns
219297
///
220298
/// Returns the shell-specific install target.
299+
///
300+
/// # Examples
301+
///
302+
/// ```no_run
303+
/// // Internal helper; use `install_shell_completion` to construct targets.
304+
/// ```
221305
fn new(shell: Shell, home_dir: &Path) -> ConfigResult<Self> {
222306
let target = match shell {
223307
Shell::Bash => Self {
@@ -276,6 +360,12 @@ impl ShellInstallTarget {
276360
///
277361
/// Returns the startup-file block body, or `None` when the shell does not
278362
/// need startup-file changes.
363+
///
364+
/// # Examples
365+
///
366+
/// ```no_run
367+
/// // Internal helper; use `install_shell_completion` to generate rc blocks.
368+
/// ```
279369
fn rc_block_body(&self, generated_path: &Path, completion_dir: &Path) -> Option<String> {
280370
let generated_path = generated_path.to_str()?;
281371
let completion_dir = completion_dir.to_str()?;
@@ -320,6 +410,23 @@ impl ShellInstallTarget {
320410
/// # Returns
321411
///
322412
/// Returns `Ok(())` after the startup file has been written.
413+
///
414+
/// # Examples
415+
///
416+
/// ```
417+
/// use std::fs;
418+
/// use clap_complete::aot::Shell;
419+
/// use rust_config_tree::upsert_managed_block;
420+
///
421+
/// let path = std::env::temp_dir().join("rust-config-tree-upsert-doctest.rc");
422+
/// upsert_managed_block("myapp", Shell::Bash, &path, "body\n")?;
423+
///
424+
/// let content = fs::read_to_string(&path)?;
425+
/// assert!(content.contains("# >>> myapp bash completions >>>"));
426+
/// assert!(content.contains("body"));
427+
/// # let _ = fs::remove_file(path);
428+
/// # Ok::<(), std::io::Error>(())
429+
/// ```
323430
pub fn upsert_managed_block(
324431
bin_name: &str,
325432
shell: Shell,

src/config.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,25 @@ pub trait ConfigSchema: Config + Sized {
5050
/// # Returns
5151
///
5252
/// Returns include paths declared by `layer`.
53+
///
54+
/// # Examples
55+
///
56+
/// ```
57+
/// use confique::Config;
58+
/// use rust_config_tree::ConfigSchema;
59+
///
60+
/// #[derive(Config)]
61+
/// struct AppConfig {
62+
/// #[config(default = [])]
63+
/// include: Vec<std::path::PathBuf>,
64+
/// }
65+
///
66+
/// impl ConfigSchema for AppConfig {
67+
/// fn include_paths(layer: &<Self as Config>::Layer) -> Vec<std::path::PathBuf> {
68+
/// layer.include.clone().unwrap_or_default()
69+
/// }
70+
/// }
71+
/// ```
5372
fn include_paths(layer: &<Self as Config>::Layer) -> Vec<PathBuf>;
5473

5574
/// Overrides the generated template file path for a split nested section.
@@ -70,6 +89,32 @@ pub trait ConfigSchema: Config + Sized {
7089
///
7190
/// Returns `Some(path)` to override the generated file path, or `None` to
7291
/// use the default section path.
92+
///
93+
/// # Examples
94+
///
95+
/// ```
96+
/// use confique::Config;
97+
/// use rust_config_tree::ConfigSchema;
98+
///
99+
/// #[derive(Config)]
100+
/// struct AppConfig {
101+
/// #[config(default = [])]
102+
/// include: Vec<std::path::PathBuf>,
103+
/// }
104+
///
105+
/// impl ConfigSchema for AppConfig {
106+
/// fn include_paths(layer: &<Self as Config>::Layer) -> Vec<std::path::PathBuf> {
107+
/// layer.include.clone().unwrap_or_default()
108+
/// }
109+
///
110+
/// fn template_path_for_section(section_path: &[&str]) -> Option<std::path::PathBuf> {
111+
/// match section_path {
112+
/// ["server"] => Some(std::path::PathBuf::from("config/server.yaml")),
113+
/// _ => None,
114+
/// }
115+
/// }
116+
/// }
117+
/// ```
73118
fn template_path_for_section(section_path: &[&str]) -> Option<PathBuf> {
74119
let _ = section_path;
75120
None

src/config_env.rs

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,29 @@ impl ConfiqueEnvProvider {
3838
///
3939
/// - `S`: Config schema whose metadata declares environment variable names.
4040
///
41+
/// # Arguments
42+
///
43+
/// This function has no arguments.
44+
///
4145
/// # Returns
4246
///
4347
/// Returns a provider that emits only environment variables declared by `S`.
48+
///
49+
/// # Examples
50+
///
51+
/// ```
52+
/// use confique::Config;
53+
/// use rust_config_tree::ConfiqueEnvProvider;
54+
///
55+
/// #[derive(Config)]
56+
/// struct AppConfig {
57+
/// #[config(env = "APP_MODE", default = "demo")]
58+
/// mode: String,
59+
/// }
60+
///
61+
/// let provider = ConfiqueEnvProvider::new::<AppConfig>();
62+
/// # let _ = provider;
63+
/// ```
4464
pub fn new<S>() -> Self
4565
where
4666
S: Config,
@@ -69,6 +89,22 @@ impl ConfiqueEnvProvider {
6989

7090
/// Supplies Figment data and source labels for schema-declared environment variables.
7191
impl Provider for ConfiqueEnvProvider {
92+
/// Builds metadata used by Figment source tracing.
93+
///
94+
/// # Arguments
95+
///
96+
/// - `self`: Environment provider whose path-to-variable mapping should be
97+
/// exposed in metadata.
98+
///
99+
/// # Returns
100+
///
101+
/// Returns Figment metadata that renders schema paths as native env names.
102+
///
103+
/// # Examples
104+
///
105+
/// ```no_run
106+
/// let _ = ();
107+
/// ```
72108
fn metadata(&self) -> Metadata {
73109
let path_to_env = Arc::clone(&self.path_to_env);
74110

@@ -79,12 +115,44 @@ impl Provider for ConfiqueEnvProvider {
79115
})
80116
}
81117

118+
/// Reads configured environment variables into Figment data.
119+
///
120+
/// # Arguments
121+
///
122+
/// - `self`: Environment provider wrapping the filtered Figment env source.
123+
///
124+
/// # Returns
125+
///
126+
/// Returns Figment data grouped by profile, or a Figment error.
127+
///
128+
/// # Examples
129+
///
130+
/// ```no_run
131+
/// let _ = ();
132+
/// ```
82133
fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
83134
self.env.data()
84135
}
85136
}
86137

87138
/// Recursively maps schema field paths to their declared environment variables.
139+
///
140+
/// # Arguments
141+
///
142+
/// - `meta`: `confique` metadata node to inspect.
143+
/// - `prefix`: Dot-separated field path prefix for `meta`.
144+
/// - `env_to_path`: Output map from uppercase environment names to field paths.
145+
/// - `path_to_env`: Output map from field paths to declared environment names.
146+
///
147+
/// # Returns
148+
///
149+
/// Returns no value; both output maps are updated in place.
150+
///
151+
/// # Examples
152+
///
153+
/// ```no_run
154+
/// let _ = ();
155+
/// ```
88156
fn collect_env_mapping(
89157
meta: &'static Meta,
90158
prefix: &str,

src/config_format.rs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,16 @@ impl ConfigFormat {
3232
/// # Returns
3333
///
3434
/// Returns the inferred [`ConfigFormat`].
35+
///
36+
/// # Examples
37+
///
38+
/// ```
39+
/// use rust_config_tree::ConfigFormat;
40+
///
41+
/// assert_eq!(ConfigFormat::from_path("config.toml"), ConfigFormat::Toml);
42+
/// assert_eq!(ConfigFormat::from_path("config.json5"), ConfigFormat::Json);
43+
/// assert_eq!(ConfigFormat::from_path("config.unknown"), ConfigFormat::Yaml);
44+
/// ```
3545
pub fn from_path(path: impl AsRef<Path>) -> Self {
3646
match path.as_ref().extension().and_then(OsStr::to_str) {
3747
Some("toml") => Self::Toml,
@@ -42,6 +52,20 @@ impl ConfigFormat {
4252
}
4353

4454
/// Builds the YAML renderer options used by default templates.
55+
///
56+
/// # Arguments
57+
///
58+
/// This function has no arguments.
59+
///
60+
/// # Returns
61+
///
62+
/// Returns YAML format options shared by generated templates.
63+
///
64+
/// # Examples
65+
///
66+
/// ```no_run
67+
/// let _ = ();
68+
/// ```
4569
pub(crate) fn yaml_options() -> confique::yaml::FormatOptions {
4670
let mut options = confique::yaml::FormatOptions::default();
4771
options.indent = 2;
@@ -52,6 +76,20 @@ pub(crate) fn yaml_options() -> confique::yaml::FormatOptions {
5276
}
5377

5478
/// Builds the TOML renderer options used by default templates.
79+
///
80+
/// # Arguments
81+
///
82+
/// This function has no arguments.
83+
///
84+
/// # Returns
85+
///
86+
/// Returns TOML format options shared by generated templates.
87+
///
88+
/// # Examples
89+
///
90+
/// ```no_run
91+
/// let _ = ();
92+
/// ```
5593
pub(crate) fn toml_options() -> confique::toml::FormatOptions {
5694
let mut options = confique::toml::FormatOptions::default();
5795
options.general.comments = true;
@@ -61,6 +99,20 @@ pub(crate) fn toml_options() -> confique::toml::FormatOptions {
6199
}
62100

63101
/// Builds the JSON5 renderer options used by default templates.
102+
///
103+
/// # Arguments
104+
///
105+
/// This function has no arguments.
106+
///
107+
/// # Returns
108+
///
109+
/// Returns JSON5 format options shared by generated templates.
110+
///
111+
/// # Examples
112+
///
113+
/// ```no_run
114+
/// let _ = ();
115+
/// ```
64116
pub(crate) fn json5_options() -> confique::json5::FormatOptions {
65117
let mut options = confique::json5::FormatOptions::default();
66118
options.indent = 2;

0 commit comments

Comments
 (0)