repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_ctx/src/cmd_ctx_mpnf_params.rs
crate/cmd_ctx/src/cmd_ctx_mpnf_params.rs
use std::{collections::BTreeMap, fmt::Debug, future::IntoFuture}; use futures::{future::LocalBoxFuture, FutureExt}; use interruptible::Interruptibility; use own::{OwnedOrMutRef, OwnedOrRef}; use peace_params::ParamsValue; use peace_profile_model::Profile; use peace_resource_rt::internal::WorkspaceParamsFile; use peace_rt_model::{ params::{ProfileParamsOpt, WorkspaceParamsOpt}, Workspace, WorkspaceInitializer, }; use typed_builder::TypedBuilder; use crate::{ CmdCtxBuilderSupport, CmdCtxBuilderSupportMulti, CmdCtxMpnf, CmdCtxMpnfFields, CmdCtxTypes, ProfileFilterFn, }; /// A command that works with multiple profiles, not scoped to a flow. /// /// ```bash /// path/to/repo/.peace/envman /// |- πŸ“ workspace_params.yaml # βœ… can read or write `WorkspaceParams` /// | /// |- 🌏 internal_dev_a # βœ… can list multiple `Profile`s /// | |- πŸ“ profile_params.yaml # βœ… can read multiple `ProfileParams` /// | | /// | |- .. # ❌ cannot read or write `Flow` information /// | /// |- 🌏 customer_a_dev # βœ… /// | |- πŸ“ profile_params.yaml # βœ… /// | /// |- 🌏 customer_a_prod # βœ… /// | |- πŸ“ profile_params.yaml # βœ… /// | /// |- 🌏 workspace_init # βœ… can list multiple `Profile`s /// |- πŸ“ profile_params.yaml # ❌ cannot read profile params of different underlying type /// ``` /// /// ## Capabilities /// /// This kind of command can: /// /// * Read or write workspace parameters. /// * Read or write multiple profiles' parameters &ndash; as long as they are of /// the same type (same `struct`). /// /// This kind of command cannot: /// /// * Read or write flow parameters -- see [`CmdCtxMpsf`]. /// * Read or write flow state -- see [`CmdCtxMpsf`]. /// /// [`CmdCtxMpsf`]: crate::CmdCtxMpsf #[derive(Debug, TypedBuilder)] #[builder(build_method(vis="", name=build_partial))] pub struct CmdCtxMpnfParams<'ctx, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Output endpoint to return values / errors, and write progress /// information to. /// /// See [`OutputWrite`]. /// /// [`OutputWrite`]: peace_rt_model_core::OutputWrite #[builder(setter(prefix = "with_"))] pub output: OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, /// The interrupt channel receiver if this `CmdExecution` is interruptible. #[builder(setter(prefix = "with_"), default = Interruptibility::NonInterruptible)] pub interruptibility: Interruptibility<'static>, /// Workspace that the `peace` tool runs in. #[builder(setter(prefix = "with_"))] pub workspace: OwnedOrRef<'ctx, Workspace>, /// Function to filter the profiles that are accessible by this command. #[builder(setter( prefix = "with_", transform = |f: impl Fn(&Profile) -> bool + 'static| Some(ProfileFilterFn(Box::new(f)))), default = None )] pub profile_filter_fn: Option<ProfileFilterFn>, /// Workspace params. // // NOTE: When updating this mutator, also update it for all the other `CmdCtx*Params` types. #[builder( setter(prefix = "with_"), via_mutators(init = WorkspaceParamsOpt::default()), mutators( /// Sets the value at the given workspace params key. /// /// # Parameters /// /// * `key`: The key to store the given value against. /// * `value`: The value to store at the given key. This is an /// `Option` so that you may remove a value if desired. /// /// # Type Parameters /// /// * `V`: The serializable type stored at the given key. pub fn with_workspace_param<V>( &mut self, key: CmdCtxTypesT::WorkspaceParamsKey, value: Option<V>, ) where V: ParamsValue, { let _ = self.workspace_params.insert(key, value); } ) )] #[builder(setter(prefix = "with_"))] pub workspace_params: WorkspaceParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::WorkspaceParamsKey>, /// Profile params for each profile. // // NOTE: When updating this mutator, also update it for all the other `CmdCtx*Params` types. #[builder( setter(prefix = "with_"), via_mutators(init = BTreeMap::new()), mutators( /// Sets the value at the given profile params key for a given profile. /// /// # Parameters /// /// * `key`: The key to store the given value against. /// * `value`: The value to store at the given key. This is an /// `Option` so that you may remove a value if desired. /// /// # Type Parameters /// /// * `V`: The serializable type stored at the given key. pub fn with_profile_param<V>( &mut self, profile: &Profile, key: CmdCtxTypesT::ProfileParamsKey, value: Option<V>, ) where V: ParamsValue, { match self.profile_to_profile_params.get_mut(profile) { Some(profile_params) => { let _ = profile_params.insert(key, value); } None => { let mut profile_params = ProfileParamsOpt::new(); let _ = profile_params.insert(key, value); self.profile_to_profile_params.insert(profile.clone(), profile_params); } } } ) )] pub profile_to_profile_params: BTreeMap<Profile, ProfileParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::ProfileParamsKey>>, } // Use one of the following to obtain the generated type signature: // // ```sh // cargo expand -p peace_cmd_ctx cmd_ctx_mpnf_params // ``` // // Sublime text command: // // **LSP-rust-analyzer: Expand Macro Recursively** while the caret is on the // `TypedBuilder` derive. #[allow(non_camel_case_types)] impl<'ctx, CmdCtxTypesT, __interruptibility, __profile_filter_fn> CmdCtxMpnfParamsBuilder< 'ctx, CmdCtxTypesT, ( (OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>,), __interruptibility, (OwnedOrRef<'ctx, Workspace>,), __profile_filter_fn, (WorkspaceParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::WorkspaceParamsKey>,), ( BTreeMap< Profile, ProfileParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::ProfileParamsKey>, >, ), ), > where CmdCtxTypesT: CmdCtxTypes, CmdCtxMpnfParams<'ctx, CmdCtxTypesT>: for<'__typed_builder_lifetime_for_default> ::typed_builder::NextFieldDefault< ( &'__typed_builder_lifetime_for_default OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, __interruptibility, ), Output = Interruptibility<'static>, >, CmdCtxMpnfParams<'ctx, CmdCtxTypesT>: for<'__typed_builder_lifetime_for_default> ::typed_builder::NextFieldDefault< ( &'__typed_builder_lifetime_for_default OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, &'__typed_builder_lifetime_for_default Interruptibility<'static>, &'__typed_builder_lifetime_for_default OwnedOrRef<'ctx, Workspace>, __profile_filter_fn, ), Output = Option<ProfileFilterFn>, >, { pub async fn build(self) -> Result<CmdCtxMpnf<'ctx, CmdCtxTypesT>, CmdCtxTypesT::AppError> { let CmdCtxMpnfParams { output, interruptibility, workspace, profile_filter_fn, workspace_params: workspace_params_provided, profile_to_profile_params: profile_to_profile_params_provided, } = self.build_partial(); let workspace_params_type_reg = CmdCtxBuilderSupport::params_type_reg_initialize::<CmdCtxTypesT::WorkspaceParamsKey>(); let profile_params_type_reg = CmdCtxBuilderSupport::params_type_reg_initialize::<CmdCtxTypesT::ProfileParamsKey>(); let workspace_dirs = workspace.dirs(); let storage = workspace.storage(); let workspace_params_file = WorkspaceParamsFile::from(workspace_dirs.peace_app_dir()); let workspace_params = CmdCtxBuilderSupport::workspace_params_merge( storage, &workspace_params_type_reg, workspace_params_provided, &workspace_params_file, ) .await?; let profiles = CmdCtxBuilderSupportMulti::<CmdCtxTypesT>::profiles_from_peace_app_dir( workspace_dirs.peace_app_dir(), profile_filter_fn.as_ref(), ) .await?; let (profile_dirs, profile_history_dirs) = CmdCtxBuilderSupportMulti::<CmdCtxTypesT>::profile_and_history_dirs_read( &profiles, workspace_dirs, ); let mut dirs_to_create = vec![ AsRef::<std::path::Path>::as_ref(workspace_dirs.workspace_dir()), AsRef::<std::path::Path>::as_ref(workspace_dirs.peace_dir()), AsRef::<std::path::Path>::as_ref(workspace_dirs.peace_app_dir()), ]; profile_dirs .values() .map(AsRef::<std::path::Path>::as_ref) .chain( profile_history_dirs .values() .map(AsRef::<std::path::Path>::as_ref), ) .for_each(|dir| dirs_to_create.push(dir)); // Create directories and write init parameters to storage. #[cfg(target_arch = "wasm32")] { WorkspaceInitializer::dirs_create(storage, dirs_to_create).await?; } #[cfg(not(target_arch = "wasm32"))] { WorkspaceInitializer::dirs_create(dirs_to_create).await?; let workspace_dir = workspace_dirs.workspace_dir(); std::env::set_current_dir(workspace_dir).map_err( #[cfg_attr(coverage_nightly, coverage(off))] |error| { peace_rt_model::Error::Native(peace_rt_model::NativeError::CurrentDirSet { workspace_dir: workspace_dir.clone(), error, }) }, )?; } // profile_params_deserialize let profile_to_profile_params = CmdCtxBuilderSupportMulti::<CmdCtxTypesT>::profile_params_deserialize( &profile_dirs, profile_to_profile_params_provided, storage, &profile_params_type_reg, ) .await?; let interruptibility_state = interruptibility.into(); // Serialize params to `PeaceAppDir`. CmdCtxBuilderSupport::workspace_params_serialize( &workspace_params, storage, &workspace_params_file, ) .await?; // profile_params_serialize CmdCtxBuilderSupportMulti::<CmdCtxTypesT>::profile_params_serialize( &profile_to_profile_params, &profile_dirs, storage, ) .await?; // No mapping function registration because there are no flow params to // deserialize. let cmd_ctx_mpnf = CmdCtxMpnf { output, fields: CmdCtxMpnfFields { interruptibility_state, workspace, profiles, profile_dirs, profile_history_dirs, workspace_params_type_reg, workspace_params, profile_params_type_reg, profile_to_profile_params, }, }; Ok(cmd_ctx_mpnf) } } #[allow(non_camel_case_types)] impl<'ctx, CmdCtxTypesT, __interruptibility, __profile_filter_fn> IntoFuture for CmdCtxMpnfParamsBuilder< 'ctx, CmdCtxTypesT, ( (OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>,), __interruptibility, (OwnedOrRef<'ctx, Workspace>,), __profile_filter_fn, (WorkspaceParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::WorkspaceParamsKey>,), ( BTreeMap< Profile, ProfileParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::ProfileParamsKey>, >, ), ), > where CmdCtxTypesT: CmdCtxTypes, CmdCtxMpnfParams<'ctx, CmdCtxTypesT>: for<'__typed_builder_lifetime_for_default> ::typed_builder::NextFieldDefault< ( &'__typed_builder_lifetime_for_default OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, __interruptibility, ), Output = Interruptibility<'static>, >, CmdCtxMpnfParams<'ctx, CmdCtxTypesT>: for<'__typed_builder_lifetime_for_default> ::typed_builder::NextFieldDefault< ( &'__typed_builder_lifetime_for_default OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, &'__typed_builder_lifetime_for_default Interruptibility<'static>, &'__typed_builder_lifetime_for_default OwnedOrRef<'ctx, Workspace>, __profile_filter_fn, ), Output = Option<ProfileFilterFn>, >, __interruptibility: 'ctx, __profile_filter_fn: 'ctx, { /// Future that returns the `CmdCtxMpnf`. /// /// This is boxed since [TAIT] is not yet available ([rust#63063]). /// /// [TAIT]: https://rust-lang.github.io/impl-trait-initiative/explainer/tait.html /// [rust#63063]: https://github.com/rust-lang/rust/issues/63063 type IntoFuture = LocalBoxFuture<'ctx, Result<CmdCtxMpnf<'ctx, CmdCtxTypesT>, CmdCtxTypesT::AppError>>; type Output = <Self::IntoFuture as std::future::Future>::Output; fn into_future(self) -> Self::IntoFuture { self.build().boxed_local() } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_ctx/src/profile_selection.rs
crate/cmd_ctx/src/profile_selection.rs
use own::OwnedOrRef; use peace_profile_model::Profile; /// How the `CmdCtx` knows which `Profile` to use. /// /// This is applicable to single flow `CmdCtx`s: [`CmdCtxSpsf`] and /// [`CmdCtxMpsf`] /// /// [`CmdCtxSpsf`]: crate::CmdCtxSpsf /// [`CmdCtxMpsf`]: crate::CmdCtxMpsf #[derive(Clone, Debug, PartialEq, Eq)] pub enum ProfileSelection<'f, WorkspaceParamsK> { /// A `Profile` is selected. Specified(Profile), /// The `Profile` will be read from workspace params using the provided key /// during command context build. FromWorkspaceParam(OwnedOrRef<'f, WorkspaceParamsK>), }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_ctx/src/cmd_ctx_spnf_params.rs
crate/cmd_ctx/src/cmd_ctx_spnf_params.rs
use std::future::IntoFuture; use futures::{future::LocalBoxFuture, FutureExt}; use interruptible::Interruptibility; use own::{OwnedOrMutRef, OwnedOrRef}; use peace_params::ParamsValue; use peace_resource_rt::{ internal::{ProfileParamsFile, WorkspaceParamsFile}, paths::{ProfileDir, ProfileHistoryDir}, }; use peace_rt_model::{ params::{ProfileParamsOpt, WorkspaceParamsOpt}, Workspace, WorkspaceInitializer, }; use typed_builder::TypedBuilder; use crate::{CmdCtxBuilderSupport, CmdCtxSpnf, CmdCtxSpnfFields, CmdCtxTypes, ProfileSelection}; /// A command that works with a single profile, not scoped to a flow. /// /// ```bash /// path/to/repo/.peace/envman /// |- πŸ“ workspace_params.yaml # βœ… can read or write `WorkspaceParams` /// | /// |- 🌏 internal_dev_a # βœ… can read `Profile` /// | |- πŸ“ profile_params.yaml # βœ… can read or write `ProfileParams` /// | | /// | |- 🌊 .. # ❌ cannot read or write Flow information /// | /// |- 🌏 .. # ❌ cannot read or write other `Profile` information /// ``` /// /// ## Capabilities /// /// This kind of command can: /// /// * Read or write workspace parameters. /// * Read or write a single profile's parameters. For multiple profiles, see /// [`CmdCtxMpnf`]. /// /// This kind of command cannot: /// /// * Read or write flow parameters or state -- see [`CmdCtxSpsf`] or /// [`CmdCtxMpsf`]. /// /// [`CmdCtxMpnf`]: crate::CmdCtxMpnf /// [`CmdCtxMpsf`]: crate::CmdCtxMpsf /// [`CmdCtxSpsf`]: crate::CmdCtxSpsf #[derive(Debug, TypedBuilder)] #[builder(build_method(vis="", name=build_partial))] pub struct CmdCtxSpnfParams<'ctx, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Output endpoint to return values / errors, and write progress /// information to. /// /// See [`OutputWrite`]. /// /// [`OutputWrite`]: peace_rt_model_core::OutputWrite #[builder(setter(prefix = "with_"))] pub output: OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, /// The interrupt channel receiver if this `CmdExecution` is interruptible. #[builder(setter(prefix = "with_"), default = Interruptibility::NonInterruptible)] pub interruptibility: Interruptibility<'static>, /// Workspace that the `peace` tool runs in. #[builder(setter(prefix = "with_"))] pub workspace: OwnedOrRef<'ctx, Workspace>, /// The profile this command operates on. #[builder(setter(prefix = "with_"))] pub profile_selection: ProfileSelection<'ctx, CmdCtxTypesT::WorkspaceParamsKey>, /// Workspace params. // // NOTE: When updating this mutator, also update it for all the other `CmdCtx*Params` types. #[builder( setter(prefix = "with_"), via_mutators(init = WorkspaceParamsOpt::default()), mutators( /// Sets the value at the given workspace params key. /// /// # Parameters /// /// * `key`: The key to store the given value against. /// * `value`: The value to store at the given key. This is an /// `Option` so that you may remove a value if desired. /// /// # Type Parameters /// /// * `V`: The serializable type stored at the given key. pub fn with_workspace_param<V>( &mut self, key: CmdCtxTypesT::WorkspaceParamsKey, value: Option<V>, ) where V: ParamsValue, { let _ = self.workspace_params.insert(key, value); } ) )] #[builder(setter(prefix = "with_"))] pub workspace_params: WorkspaceParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::WorkspaceParamsKey>, /// Profile params for the profile. #[builder( setter(prefix = "with_"), via_mutators(init = ProfileParamsOpt::default()), mutators( /// Sets the value at the given profile params key. /// /// # Parameters /// /// * `key`: The key to store the given value against. /// * `value`: The value to store at the given key. This is an /// `Option` so that you may remove a value if desired. /// /// # Type Parameters /// /// * `V`: The serializable type stored at the given key. pub fn with_profile_param<V>( &mut self, key: CmdCtxTypesT::ProfileParamsKey, value: Option<V>, ) where V: ParamsValue, { let _ = self.profile_params.insert(key, value); } ) )] pub profile_params: ProfileParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::ProfileParamsKey>, } // Use one of the following to obtain the generated type signature: // // ```sh // cargo expand -p peace_cmd_ctx cmd_ctx_spnf_params // ``` // // Sublime text command: // // **LSP-rust-analyzer: Expand Macro Recursively** while the caret is on the // `TypedBuilder` derive. #[allow(non_camel_case_types)] impl<'ctx, CmdCtxTypesT, __interruptibility> CmdCtxSpnfParamsBuilder< 'ctx, CmdCtxTypesT, ( (OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>,), __interruptibility, (OwnedOrRef<'ctx, Workspace>,), (ProfileSelection<'ctx, CmdCtxTypesT::WorkspaceParamsKey>,), (WorkspaceParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::WorkspaceParamsKey>,), (ProfileParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::ProfileParamsKey>,), ), > where CmdCtxTypesT: CmdCtxTypes, CmdCtxSpnfParams<'ctx, CmdCtxTypesT>: for<'__typed_builder_lifetime_for_default> ::typed_builder::NextFieldDefault< ( &'__typed_builder_lifetime_for_default OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, __interruptibility, ), Output = Interruptibility<'static>, >, { pub async fn build(self) -> Result<CmdCtxSpnf<'ctx, CmdCtxTypesT>, CmdCtxTypesT::AppError> { let CmdCtxSpnfParams { output, interruptibility, workspace, profile_selection, workspace_params: workspace_params_provided, profile_params: profile_params_provided, } = self.build_partial(); let workspace_params_type_reg = CmdCtxBuilderSupport::params_type_reg_initialize::<CmdCtxTypesT::WorkspaceParamsKey>(); let profile_params_type_reg = CmdCtxBuilderSupport::params_type_reg_initialize::<CmdCtxTypesT::ProfileParamsKey>(); let workspace_dirs = workspace.dirs(); let storage = workspace.storage(); let workspace_params_file = WorkspaceParamsFile::from(workspace_dirs.peace_app_dir()); let workspace_params = CmdCtxBuilderSupport::workspace_params_merge( storage, &workspace_params_type_reg, workspace_params_provided, &workspace_params_file, ) .await?; let profile = CmdCtxBuilderSupport::profile_from_profile_selection( profile_selection, &workspace_params, storage, &workspace_params_file, ) .await?; let profile_ref = &profile; let profile_dir = ProfileDir::from((workspace_dirs.peace_app_dir(), profile_ref)); let profile_history_dir = ProfileHistoryDir::from(&profile_dir); let dirs_to_create = [ AsRef::<std::path::Path>::as_ref(workspace_dirs.workspace_dir()), AsRef::<std::path::Path>::as_ref(workspace_dirs.peace_dir()), AsRef::<std::path::Path>::as_ref(workspace_dirs.peace_app_dir()), AsRef::<std::path::Path>::as_ref(&profile_dir), AsRef::<std::path::Path>::as_ref(&profile_history_dir), ]; let storage = workspace.storage(); // profile_params_deserialize let profile_params_file = ProfileParamsFile::from(&profile_dir); let profile_params = CmdCtxBuilderSupport::profile_params_merge( storage, &profile_params_type_reg, profile_params_provided, &profile_params_file, ) .await?; // Create directories and write init parameters to storage. #[cfg(target_arch = "wasm32")] { WorkspaceInitializer::dirs_create(storage, dirs_to_create).await?; } #[cfg(not(target_arch = "wasm32"))] { WorkspaceInitializer::dirs_create(dirs_to_create).await?; let workspace_dir = workspace_dirs.workspace_dir(); std::env::set_current_dir(workspace_dir).map_err( #[cfg_attr(coverage_nightly, coverage(off))] |error| { peace_rt_model::Error::Native(peace_rt_model::NativeError::CurrentDirSet { workspace_dir: workspace_dir.clone(), error, }) }, )?; } let interruptibility_state = interruptibility.into(); // Serialize params to `PeaceAppDir`. CmdCtxBuilderSupport::workspace_params_serialize( &workspace_params, storage, &workspace_params_file, ) .await?; CmdCtxBuilderSupport::profile_params_serialize( &profile_params, storage, &profile_params_file, ) .await?; // Track items in memory. let mut resources = peace_resource_rt::Resources::new(); CmdCtxBuilderSupport::workspace_params_insert(workspace_params.clone(), &mut resources); resources.insert(workspace_params_file); CmdCtxBuilderSupport::profile_params_insert(profile_params.clone(), &mut resources); resources.insert(profile_params_file); // Register each mapping function with the `MappingFnReg`. let mapping_fn_reg = CmdCtxBuilderSupport::mapping_fn_reg_setup::<CmdCtxTypesT::MappingFns>(); // Insert resources { let (app_name, workspace_dirs, storage) = (*workspace).clone().into_inner(); let (workspace_dir, peace_dir, peace_app_dir) = workspace_dirs.into_inner(); resources.insert(app_name); resources.insert(storage); resources.insert(workspace_dir); resources.insert(peace_dir); resources.insert(peace_app_dir); resources.insert(profile_dir.clone()); resources.insert(profile_history_dir.clone()); resources.insert(profile.clone()); } let cmd_ctx_spnf = CmdCtxSpnf { output, fields: CmdCtxSpnfFields { interruptibility_state, workspace, profile, profile_dir, profile_history_dir, workspace_params_type_reg, workspace_params, profile_params_type_reg, profile_params, mapping_fn_reg, }, }; Ok(cmd_ctx_spnf) } } #[allow(non_camel_case_types)] impl<'ctx, CmdCtxTypesT, __interruptibility> IntoFuture for CmdCtxSpnfParamsBuilder< 'ctx, CmdCtxTypesT, ( (OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>,), __interruptibility, (OwnedOrRef<'ctx, Workspace>,), (ProfileSelection<'ctx, CmdCtxTypesT::WorkspaceParamsKey>,), (WorkspaceParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::WorkspaceParamsKey>,), (ProfileParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::ProfileParamsKey>,), ), > where CmdCtxTypesT: CmdCtxTypes, CmdCtxSpnfParams<'ctx, CmdCtxTypesT>: for<'__typed_builder_lifetime_for_default> ::typed_builder::NextFieldDefault< ( &'__typed_builder_lifetime_for_default OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, __interruptibility, ), Output = Interruptibility<'static>, >, __interruptibility: 'ctx, { /// Future that returns the `CmdCtxSpnf`. /// /// This is boxed since [TAIT] is not yet available ([rust#63063]). /// /// [TAIT]: https://rust-lang.github.io/impl-trait-initiative/explainer/tait.html /// [rust#63063]: https://github.com/rust-lang/rust/issues/63063 type IntoFuture = LocalBoxFuture<'ctx, Result<CmdCtxSpnf<'ctx, CmdCtxTypesT>, CmdCtxTypesT::AppError>>; type Output = <Self::IntoFuture as std::future::Future>::Output; fn into_future(self) -> Self::IntoFuture { self.build().boxed_local() } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_ctx/src/cmd_ctx_npnf.rs
crate/cmd_ctx/src/cmd_ctx_npnf.rs
use interruptible::InterruptibilityState; use own::{OwnedOrMutRef, OwnedOrRef}; use peace_resource_rt::paths::{PeaceAppDir, PeaceDir, WorkspaceDir}; use peace_rt_model::Workspace; use peace_rt_model_core::params::WorkspaceParams; use type_reg::untagged::{BoxDt, TypeReg}; use crate::{CmdCtxNpnfParams, CmdCtxNpnfParamsBuilder, CmdCtxTypes}; /// Context for a command that only works with workspace parameters -- no /// profile / no flow. /// /// ```bash /// path/to/repo/.peace/envman /// |- πŸ“ workspace_params.yaml # βœ… can read or write `WorkspaceParams` /// | /// |- 🌏 .. # ❌ cannot read or write `Profile` information /// ``` /// /// ## Capabilities /// /// This kind of command can: /// /// * Read or write workspace parameters. /// /// This kind of command cannot: /// /// * Read or write profile parameters -- see [`CmdCtxSpnf`] or [`CmdCtxMpnf`]. /// * Read or write flow parameters or state -- see [`CmdCtxSpsf`] or /// [`CmdCtxMpsf`]. /// /// [`CmdCtxMpnf`]: crate::CmdCtxMpnf /// [`CmdCtxMpsf`]: crate::CmdCtxMpsf /// [`CmdCtxSpnf`]: crate::CmdCtxSpnf /// [`CmdCtxSpsf`]: crate::CmdCtxSpsf #[derive(Debug)] pub struct CmdCtxNpnf<'ctx, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Output endpoint to return values / errors, and write progress /// information to. /// /// See [`OutputWrite`]. /// /// [`OutputWrite`]: peace_rt_model_core::OutputWrite pub output: OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, /// Inner fields without the `output`. /// /// # Design /// /// This is necessary so that the `output` can be separated from the fields /// during execution. pub fields: CmdCtxNpnfFields<'ctx, CmdCtxTypesT>, } #[derive(Debug)] pub struct CmdCtxNpnfFields<'ctx, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Whether the `CmdExecution` is interruptible. /// /// If it is, this holds the interrupt channel receiver. pub interruptibility_state: InterruptibilityState<'static, 'static>, /// Workspace that the `peace` tool runs in. pub workspace: OwnedOrRef<'ctx, Workspace>, /// Type registry for [`WorkspaceParams`] deserialization. /// /// [`WorkspaceParams`]: peace_rt_model::params::WorkspaceParams pub workspace_params_type_reg: TypeReg<CmdCtxTypesT::WorkspaceParamsKey, BoxDt>, /// Workspace params. pub workspace_params: WorkspaceParams<CmdCtxTypesT::WorkspaceParamsKey>, } impl<'ctx, CmdCtxTypesT> CmdCtxNpnf<'ctx, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Returns a [`CmdCtxNpnfParamsBuilder`] to construct this command context. pub fn builder<'ctx_local>() -> CmdCtxNpnfParamsBuilder<'ctx_local, CmdCtxTypesT> { CmdCtxNpnfParams::<'ctx_local, CmdCtxTypesT>::builder() } /// Returns a reference to the output. pub fn output(&self) -> &CmdCtxTypesT::Output { &self.output } /// Returns a mutable reference to the output. pub fn output_mut(&mut self) -> &mut CmdCtxTypesT::Output { &mut self.output } /// Returns a reference to the fields. pub fn fields(&self) -> &CmdCtxNpnfFields<'_, CmdCtxTypesT> { &self.fields } /// Returns a mutable reference to the fields. pub fn fields_mut(&mut self) -> &mut CmdCtxNpnfFields<'ctx, CmdCtxTypesT> { &mut self.fields } } impl<CmdCtxTypesT> CmdCtxNpnfFields<'_, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Returns the interruptibility capability. pub fn interruptibility_state(&mut self) -> InterruptibilityState<'_, '_> { self.interruptibility_state.reborrow() } /// Returns the workspace that the `peace` tool runs in. pub fn workspace(&self) -> &Workspace { &self.workspace } /// Returns a reference to the workspace directory. pub fn workspace_dir(&self) -> &WorkspaceDir { self.workspace.dirs().workspace_dir() } /// Returns a reference to the `.peace` directory. pub fn peace_dir(&self) -> &PeaceDir { self.workspace.dirs().peace_dir() } /// Returns a reference to the `.peace/$app` directory. pub fn peace_app_dir(&self) -> &PeaceAppDir { self.workspace.dirs().peace_app_dir() } /// Returns a reference to the workspace params type registry. pub fn workspace_params_type_reg(&self) -> &TypeReg<CmdCtxTypesT::WorkspaceParamsKey, BoxDt> { &self.workspace_params_type_reg } /// Returns a mutable reference to the workspace params type registry. pub fn workspace_params_type_reg_mut( &mut self, ) -> &mut TypeReg<CmdCtxTypesT::WorkspaceParamsKey, BoxDt> { &mut self.workspace_params_type_reg } /// Returns the workspace params. pub fn workspace_params(&self) -> &WorkspaceParams<CmdCtxTypesT::WorkspaceParamsKey> { &self.workspace_params } /// Returns the workspace params. pub fn workspace_params_mut( &mut self, ) -> &mut WorkspaceParams<CmdCtxTypesT::WorkspaceParamsKey> { &mut self.workspace_params } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_ctx/src/cmd_ctx_mpnf.rs
crate/cmd_ctx/src/cmd_ctx_mpnf.rs
use std::{collections::BTreeMap, fmt::Debug}; use interruptible::InterruptibilityState; use own::{OwnedOrMutRef, OwnedOrRef}; use peace_profile_model::Profile; use peace_resource_rt::paths::{ PeaceAppDir, PeaceDir, ProfileDir, ProfileHistoryDir, WorkspaceDir, }; use peace_rt_model::{ params::{ProfileParams, WorkspaceParams}, Workspace, }; use type_reg::untagged::{BoxDt, TypeReg}; use crate::{CmdCtxMpnfParams, CmdCtxMpnfParamsBuilder, CmdCtxTypes}; /// A command that works with multiple profiles, not scoped to a flow. /// /// ```bash /// path/to/repo/.peace/envman /// |- πŸ“ workspace_params.yaml # βœ… can read or write `WorkspaceParams` /// | /// |- 🌏 internal_dev_a # βœ… can list multiple `Profile`s /// | |- πŸ“ profile_params.yaml # βœ… can read multiple `ProfileParams` /// | | /// | |- .. # ❌ cannot read or write `Flow` information /// | /// |- 🌏 customer_a_dev # βœ… /// | |- πŸ“ profile_params.yaml # βœ… /// | /// |- 🌏 customer_a_prod # βœ… /// | |- πŸ“ profile_params.yaml # βœ… /// | /// |- 🌏 workspace_init # βœ… can list multiple `Profile`s /// |- πŸ“ profile_params.yaml # ❌ cannot read profile params of different underlying type /// ``` /// /// ## Capabilities /// /// This kind of command can: /// /// * Read or write workspace parameters. /// * Read or write multiple profiles' parameters &ndash; as long as they are of /// the same type (same `struct`). /// /// This kind of command cannot: /// /// * Read or write flow parameters -- see [`CmdCtxMpsf`]. /// * Read or write flow state -- see [`CmdCtxMpsf`]. /// /// [`CmdCtxMpsf`]: crate::CmdCtxMpsf #[derive(Debug)] pub struct CmdCtxMpnf<'ctx, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Output endpoint to return values / errors, and write progress /// information to. /// /// See [`OutputWrite`]. /// /// [`OutputWrite`]: peace_rt_model_core::OutputWrite pub output: OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, /// Inner fields without the `output`. /// /// # Design /// /// This is necessary so that the `output` can be separated from the fields /// during execution. pub fields: CmdCtxMpnfFields<'ctx, CmdCtxTypesT>, } /// Fields of [`CmdCtxMpnf`]. /// /// # Design /// /// This is necessary so that the `output` can be separated from the fields /// during execution. #[derive(Debug)] pub struct CmdCtxMpnfFields<'ctx, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Whether the `CmdExecution` is interruptible. /// /// If it is, this holds the interrupt channel receiver. pub interruptibility_state: InterruptibilityState<'static, 'static>, /// Workspace that the `peace` tool runs in. pub workspace: OwnedOrRef<'ctx, Workspace>, /// The profiles that are accessible by this command. pub profiles: Vec<Profile>, /// Profile directories that store params and flows. pub profile_dirs: BTreeMap<Profile, ProfileDir>, /// Directories of each profile's execution history. pub profile_history_dirs: BTreeMap<Profile, ProfileHistoryDir>, /// Type registry for [`WorkspaceParams`] deserialization. /// /// [`WorkspaceParams`]: peace_rt_model::params::WorkspaceParams pub workspace_params_type_reg: TypeReg<CmdCtxTypesT::WorkspaceParamsKey, BoxDt>, /// Workspace params. pub workspace_params: WorkspaceParams<CmdCtxTypesT::WorkspaceParamsKey>, /// Type registry for [`ProfileParams`] deserialization. /// /// [`ProfileParams`]: peace_rt_model::params::ProfileParams pub profile_params_type_reg: TypeReg<CmdCtxTypesT::ProfileParamsKey, BoxDt>, /// Profile params for the profile. pub profile_to_profile_params: BTreeMap<Profile, ProfileParams<CmdCtxTypesT::ProfileParamsKey>>, } impl<'ctx, CmdCtxTypesT> CmdCtxMpnf<'ctx, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Returns a [`CmdCtxMpnfParamsBuilder`] to construct this command context. pub fn builder<'ctx_local>() -> CmdCtxMpnfParamsBuilder<'ctx_local, CmdCtxTypesT> { CmdCtxMpnfParams::<'ctx_local, CmdCtxTypesT>::builder() } /// Returns a reference to the output. pub fn output(&self) -> &CmdCtxTypesT::Output { &self.output } /// Returns a mutable reference to the output. pub fn output_mut(&mut self) -> &mut CmdCtxTypesT::Output { &mut self.output } /// Returns a reference to the fields. pub fn fields(&self) -> &CmdCtxMpnfFields<'_, CmdCtxTypesT> { &self.fields } /// Returns a mutable reference to the fields. pub fn fields_mut(&mut self) -> &mut CmdCtxMpnfFields<'ctx, CmdCtxTypesT> { &mut self.fields } } impl<CmdCtxTypesT> CmdCtxMpnfFields<'_, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Returns the interruptibility capability. pub fn interruptibility_state(&mut self) -> InterruptibilityState<'_, '_> { self.interruptibility_state.reborrow() } /// Returns the workspace that the `peace` tool runs in. pub fn workspace(&self) -> &Workspace { &self.workspace } /// Returns a reference to the workspace directory. pub fn workspace_dir(&self) -> &WorkspaceDir { self.workspace.dirs().workspace_dir() } /// Returns a reference to the `.peace` directory. pub fn peace_dir(&self) -> &PeaceDir { self.workspace.dirs().peace_dir() } /// Returns a reference to the `.peace/$app` directory. pub fn peace_app_dir(&self) -> &PeaceAppDir { self.workspace.dirs().peace_app_dir() } /// Returns the accessible profiles. /// /// These are the profiles that are filtered by the filter function, if /// provided. pub fn profiles(&self) -> &[Profile] { self.profiles.as_ref() } /// Returns the profile directories keyed by each profile. pub fn profile_dirs(&self) -> &BTreeMap<Profile, ProfileDir> { &self.profile_dirs } /// Returns the profile history directories keyed by each profile. pub fn profile_history_dirs(&self) -> &BTreeMap<Profile, ProfileHistoryDir> { &self.profile_history_dirs } /// Returns a reference to the workspace params type registry. pub fn workspace_params_type_reg(&self) -> &TypeReg<CmdCtxTypesT::WorkspaceParamsKey, BoxDt> { &self.workspace_params_type_reg } /// Returns a mutable reference to the workspace params type registry. pub fn workspace_params_type_reg_mut( &mut self, ) -> &mut TypeReg<CmdCtxTypesT::WorkspaceParamsKey, BoxDt> { &mut self.workspace_params_type_reg } /// Returns the workspace params. pub fn workspace_params(&self) -> &WorkspaceParams<CmdCtxTypesT::WorkspaceParamsKey> { &self.workspace_params } /// Returns the workspace params. pub fn workspace_params_mut( &mut self, ) -> &mut WorkspaceParams<CmdCtxTypesT::WorkspaceParamsKey> { &mut self.workspace_params } /// Returns a reference to the profile params type registry. pub fn profile_params_type_reg(&self) -> &TypeReg<CmdCtxTypesT::ProfileParamsKey, BoxDt> { &self.profile_params_type_reg } /// Returns a mutable reference to the profile params type registry. pub fn profile_params_type_reg_mut( &mut self, ) -> &mut TypeReg<CmdCtxTypesT::ProfileParamsKey, BoxDt> { &mut self.profile_params_type_reg } /// Returns the profile params for each profile. pub fn profile_to_profile_params( &self, ) -> &BTreeMap<Profile, ProfileParams<CmdCtxTypesT::ProfileParamsKey>> { &self.profile_to_profile_params } /// Returns the profile params for each profile. pub fn profile_to_profile_params_mut( &mut self, ) -> &mut BTreeMap<Profile, ProfileParams<CmdCtxTypesT::ProfileParamsKey>> { &mut self.profile_to_profile_params } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_ctx/src/profile_filter_fn.rs
crate/cmd_ctx/src/profile_filter_fn.rs
use std::fmt; use peace_profile_model::Profile; /// Filter function for `MultiProfile` scopes. pub struct ProfileFilterFn(pub(crate) Box<dyn Fn(&Profile) -> bool>); impl ProfileFilterFn { /// Returns whether the profile passes this filter. pub fn call(&self, profile: &Profile) -> bool { (self.0)(profile) } } impl fmt::Debug for ProfileFilterFn { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_tuple("ProfileFilterFn") .field(&"Box<dyn Fn(&Profile) -> bool") .finish() } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_ctx/src/cmd_ctx_spsf_params.rs
crate/cmd_ctx/src/cmd_ctx_spsf_params.rs
use std::future::IntoFuture; use futures::{future::LocalBoxFuture, FutureExt}; use interruptible::Interruptibility; use own::{OwnedOrMutRef, OwnedOrRef}; use peace_flow_rt::Flow; use peace_item_model::ItemId; use peace_params::{ParamsSpecs, ParamsValue}; use peace_resource_rt::{ internal::{FlowParamsFile, ProfileParamsFile, WorkspaceParamsFile}, paths::{FlowDir, ParamsSpecsFile, ProfileDir, ProfileHistoryDir, StatesCurrentFile}, resources::ts::Empty, Resources, }; use peace_rt_model::{ params::{FlowParamsOpt, ProfileParamsOpt, WorkspaceParamsOpt}, ParamsSpecsSerializer, Workspace, WorkspaceInitializer, }; use peace_state_rt::StatesSerializer; use typed_builder::TypedBuilder; use crate::{CmdCtxBuilderSupport, CmdCtxSpsf, CmdCtxSpsfFields, CmdCtxTypes, ProfileSelection}; /// Context for a command that works with one profile and one flow. /// /// ```bash /// path/to/repo/.peace/envman /// |- πŸ“ workspace_params.yaml # βœ… can read or write `WorkspaceParams` /// | /// |- 🌏 internal_dev_a /// | |- πŸ“ profile_params.yaml # βœ… can read or write `ProfileParams` /// | | /// | |- 🌊 deploy # βœ… can read `FlowId` /// | | |- πŸ“ flow_params.yaml # βœ… can read or write `FlowParams` /// | | |- πŸ“‹ states_goal.yaml # βœ… can read or write `StatesGoal` /// | | |- πŸ“‹ states_current.yaml # βœ… can read or write `StatesCurrentStored` /// | | /// | |- 🌊 .. # ❌ cannot read or write other `Flow` information /// | /// |- 🌏 .. # ❌ cannot read or write other `Profile` information /// ``` /// /// ## Capabilities /// /// This kind of command can: /// /// * Read or write workspace parameters. /// * Read or write a single profile's parameters. For multiple profiles, see /// [`CmdCtxMpsf`]. /// /// [`CmdCtxMpsf`]: crate::CmdCtxMpsf #[derive(Debug, TypedBuilder)] #[builder(build_method(vis="", name=build_partial))] pub struct CmdCtxSpsfParams<'ctx, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Output endpoint to return values / errors, and write progress /// information to. /// /// See [`OutputWrite`]. /// /// [`OutputWrite`]: peace_rt_model_core::OutputWrite #[builder(setter(prefix = "with_"))] pub output: OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, /// The interrupt channel receiver if this `CmdExecution` is interruptible. #[builder(setter(prefix = "with_"), default = Interruptibility::NonInterruptible)] pub interruptibility: Interruptibility<'static>, /// Workspace that the `peace` tool runs in. #[builder(setter(prefix = "with_"))] pub workspace: OwnedOrRef<'ctx, Workspace>, /// The profile this command operates on. #[builder(setter(prefix = "with_"))] pub profile_selection: ProfileSelection<'ctx, CmdCtxTypesT::WorkspaceParamsKey>, /// The chosen process flow. #[builder(setter(prefix = "with_"))] pub flow: OwnedOrRef<'ctx, Flow<CmdCtxTypesT::AppError>>, /// Workspace params. // // NOTE: When updating this mutator, also update it for all the other `CmdCtx*Params` types. #[builder( setter(prefix = "with_"), via_mutators(init = WorkspaceParamsOpt::default()), mutators( /// Sets the value at the given workspace params key. /// /// # Parameters /// /// * `key`: The key to store the given value against. /// * `value`: The value to store at the given key. This is an /// `Option` so that you may remove a value if desired. /// /// # Type Parameters /// /// * `V`: The serializable type stored at the given key. pub fn with_workspace_param<V>( &mut self, key: CmdCtxTypesT::WorkspaceParamsKey, value: Option<V>, ) where V: ParamsValue, { let _ = self.workspace_params.insert(key, value); } ) )] #[builder(setter(prefix = "with_"))] pub workspace_params: WorkspaceParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::WorkspaceParamsKey>, /// Profile params for the profile. #[builder( setter(prefix = "with_"), via_mutators(init = ProfileParamsOpt::default()), mutators( /// Sets the value at the given profile params key. /// /// # Parameters /// /// * `key`: The key to store the given value against. /// * `value`: The value to store at the given key. This is an /// `Option` so that you may remove a value if desired. /// /// # Type Parameters /// /// * `V`: The serializable type stored at the given key. pub fn with_profile_param<V>( &mut self, key: CmdCtxTypesT::ProfileParamsKey, value: Option<V>, ) where V: ParamsValue, { let _ = self.profile_params.insert(key, value); } ) )] pub profile_params: ProfileParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::ProfileParamsKey>, /// Flow params for the selected flow. #[builder( setter(prefix = "with_"), via_mutators(init = FlowParamsOpt::default()), mutators( /// Sets the value at the given flow params key. /// /// # Parameters /// /// * `key`: The key to store the given value against. /// * `value`: The value to store at the given key. This is an /// `Option` so that you may remove a value if desired. /// /// # Type Parameters /// /// * `V`: The serializable type stored at the given key. pub fn with_flow_param<V>( &mut self, key: CmdCtxTypesT::FlowParamsKey, value: Option<V>, ) where V: ParamsValue, { let _ = self.flow_params.insert(key, value); } ) )] pub flow_params: FlowParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::FlowParamsKey>, /// Item params specs for the selected flow. // // NOTE: When updating this mutator, also check if `CmdCtxMpsf` needs its mutator updated. #[builder( setter(prefix = "with_"), via_mutators(init = ParamsSpecs::new()), mutators( /// Sets an item's parameters. /// /// Note: this **must** be called for each item in the flow. pub fn with_item_params<I>( &mut self, item_id: ItemId, params_spec: <I::Params<'_> as peace_params::Params>::Spec, ) where I: peace_cfg::Item, CmdCtxTypesT::AppError: From<I::Error>, { self.params_specs.insert(item_id, params_spec); } ) )] pub params_specs: ParamsSpecs, /// `Resources` for flow execution. /// /// A "resource" is any object, and `resources` is a map where each object /// is keyed by its type. This means only one instance of each type can be /// held by the map. /// /// Resources are made available to `Item`s through their `Data` associated /// type. // // NOTE: When updating this mutator, also check if `CmdCtxMpsf` needs its mutator updated. #[builder( setter(prefix = "with_"), via_mutators(init = Resources::<Empty>::new()), mutators( /// Adds an object to the in-memory resources. pub fn with_resource<R>( &mut self, resource: R, ) where R: peace_resource_rt::Resource, { self.resources.insert(resource); } ) )] pub resources: Resources<Empty>, } // Use one of the following to obtain the generated type signature: // // ```sh // cargo expand -p peace_cmd_ctx cmd_ctx_spsf_params // ``` // // Sublime text command: // // **LSP-rust-analyzer: Expand Macro Recursively** while the caret is on the // `TypedBuilder` derive. #[allow(non_camel_case_types)] impl<'ctx, CmdCtxTypesT, __interruptibility> CmdCtxSpsfParamsBuilder< 'ctx, CmdCtxTypesT, ( (OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>,), __interruptibility, (OwnedOrRef<'ctx, Workspace>,), (ProfileSelection<'ctx, CmdCtxTypesT::WorkspaceParamsKey>,), (OwnedOrRef<'ctx, Flow<CmdCtxTypesT::AppError>>,), (WorkspaceParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::WorkspaceParamsKey>,), (ProfileParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::ProfileParamsKey>,), (FlowParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::FlowParamsKey>,), (ParamsSpecs,), (Resources<Empty>,), ), > where CmdCtxTypesT: CmdCtxTypes, CmdCtxSpsfParams<'ctx, CmdCtxTypesT>: for<'__typed_builder_lifetime_for_default> ::typed_builder::NextFieldDefault< ( &'__typed_builder_lifetime_for_default OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, __interruptibility, ), Output = Interruptibility<'static>, >, { pub async fn build(self) -> Result<CmdCtxSpsf<'ctx, CmdCtxTypesT>, CmdCtxTypesT::AppError> { let CmdCtxSpsfParams { output, interruptibility, workspace, profile_selection, flow, workspace_params: workspace_params_provided, profile_params: profile_params_provided, flow_params: flow_params_provided, params_specs: params_specs_provided, resources: resources_override, } = self.build_partial(); let workspace_params_type_reg = CmdCtxBuilderSupport::params_type_reg_initialize::<CmdCtxTypesT::WorkspaceParamsKey>(); let profile_params_type_reg = CmdCtxBuilderSupport::params_type_reg_initialize::<CmdCtxTypesT::ProfileParamsKey>(); let flow_params_type_reg = CmdCtxBuilderSupport::params_type_reg_initialize::<CmdCtxTypesT::FlowParamsKey>(); let workspace_dirs = workspace.dirs(); let storage = workspace.storage(); let workspace_params_file = WorkspaceParamsFile::from(workspace_dirs.peace_app_dir()); let workspace_params = CmdCtxBuilderSupport::workspace_params_merge( storage, &workspace_params_type_reg, workspace_params_provided, &workspace_params_file, ) .await?; let profile = CmdCtxBuilderSupport::profile_from_profile_selection( profile_selection, &workspace_params, storage, &workspace_params_file, ) .await?; let profile_ref = &profile; let profile_dir = ProfileDir::from((workspace_dirs.peace_app_dir(), profile_ref)); let profile_history_dir = ProfileHistoryDir::from(&profile_dir); let flow_dir = FlowDir::from((&profile_dir, flow.flow_id())); let dirs_to_create = [ AsRef::<std::path::Path>::as_ref(workspace_dirs.workspace_dir()), AsRef::<std::path::Path>::as_ref(workspace_dirs.peace_dir()), AsRef::<std::path::Path>::as_ref(workspace_dirs.peace_app_dir()), AsRef::<std::path::Path>::as_ref(&profile_dir), AsRef::<std::path::Path>::as_ref(&profile_history_dir), AsRef::<std::path::Path>::as_ref(&flow_dir), ]; let storage = workspace.storage(); // profile_params_deserialize let profile_params_file = ProfileParamsFile::from(&profile_dir); let profile_params = CmdCtxBuilderSupport::profile_params_merge( storage, &profile_params_type_reg, profile_params_provided, &profile_params_file, ) .await?; // flow_params_deserialize let flow_params_file = FlowParamsFile::from(&flow_dir); let flow_params = CmdCtxBuilderSupport::flow_params_merge( storage, &flow_params_type_reg, flow_params_provided, &flow_params_file, ) .await?; // Create directories and write init parameters to storage. #[cfg(target_arch = "wasm32")] { WorkspaceInitializer::dirs_create(storage, dirs_to_create).await?; } #[cfg(not(target_arch = "wasm32"))] { WorkspaceInitializer::dirs_create(dirs_to_create).await?; let workspace_dir = workspace_dirs.workspace_dir(); std::env::set_current_dir(workspace_dir).map_err( #[cfg_attr(coverage_nightly, coverage(off))] |error| { peace_rt_model::Error::Native(peace_rt_model::NativeError::CurrentDirSet { workspace_dir: workspace_dir.clone(), error, }) }, )?; } let interruptibility_state = interruptibility.into(); // Serialize params to `PeaceAppDir`. CmdCtxBuilderSupport::workspace_params_serialize( &workspace_params, storage, &workspace_params_file, ) .await?; CmdCtxBuilderSupport::profile_params_serialize( &profile_params, storage, &profile_params_file, ) .await?; CmdCtxBuilderSupport::flow_params_serialize(&flow_params, storage, &flow_params_file) .await?; // Track items in memory. let mut resources = peace_resource_rt::Resources::new(); CmdCtxBuilderSupport::workspace_params_insert(workspace_params.clone(), &mut resources); resources.insert(workspace_params_file); CmdCtxBuilderSupport::profile_params_insert(profile_params.clone(), &mut resources); resources.insert(profile_params_file); CmdCtxBuilderSupport::flow_params_insert(flow_params.clone(), &mut resources); resources.insert(flow_params_file); // Register each mapping function with the `MappingFnReg`. let mapping_fn_reg = CmdCtxBuilderSupport::mapping_fn_reg_setup::<CmdCtxTypesT::MappingFns>(); // Insert resources { let (app_name, workspace_dirs, storage) = (*workspace).clone().into_inner(); let (workspace_dir, peace_dir, peace_app_dir) = workspace_dirs.into_inner(); resources.insert(app_name); resources.insert(storage); resources.insert(workspace_dir); resources.insert(peace_dir); resources.insert(peace_app_dir); resources.insert(profile_dir.clone()); resources.insert(profile_history_dir.clone()); resources.insert(profile.clone()); resources.insert(flow_dir.clone()); resources.insert(flow.flow_id().clone()); } // Set up resources for the flow's item graph let flow_ref = &flow; let flow_id = flow_ref.flow_id(); let item_graph = flow_ref.graph(); let (params_specs_type_reg, states_type_reg) = CmdCtxBuilderSupport::params_and_states_type_reg(item_graph); // Params specs loading and storage. let params_specs_type_reg_ref = &params_specs_type_reg; let params_specs_file = ParamsSpecsFile::from(&flow_dir); let params_specs_stored = ParamsSpecsSerializer::<peace_rt_model::Error>::deserialize_opt( &profile, flow_id, storage, params_specs_type_reg_ref, &params_specs_file, ) .await?; let params_specs = CmdCtxBuilderSupport::params_specs_merge( flow_ref, params_specs_provided, params_specs_stored, )?; CmdCtxBuilderSupport::params_specs_serialize(&params_specs, storage, &params_specs_file) .await?; // States loading and storage. let states_type_reg_ref = &states_type_reg; let states_current_file = StatesCurrentFile::from(&flow_dir); let states_current_stored = StatesSerializer::<peace_rt_model::Error>::deserialize_stored_opt( flow_id, storage, states_type_reg_ref, &states_current_file, ) .await?; if let Some(states_current_stored) = states_current_stored { resources.insert(states_current_stored); } // Call each `Item`'s initialization function. let mut resources = CmdCtxBuilderSupport::item_graph_setup(item_graph, resources).await?; // output_progress CmdProgressTracker initialization #[cfg(feature = "output_progress")] let cmd_progress_tracker = { let multi_progress = indicatif::MultiProgress::with_draw_target(indicatif::ProgressDrawTarget::hidden()); let progress_trackers = item_graph.iter_insertion().fold( peace_rt_model::IndexMap::with_capacity(item_graph.node_count()), |mut progress_trackers, item| { let progress_bar = multi_progress.add(indicatif::ProgressBar::hidden()); let progress_tracker = peace_progress_model::ProgressTracker::new(progress_bar); progress_trackers.insert(item.id().clone(), progress_tracker); progress_trackers }, ); peace_rt_model::CmdProgressTracker::new(multi_progress, progress_trackers) }; // Needs to come before `state_example`, because params resolution may need // some resources to be inserted for `state_example` to work. resources.merge(resources_override.into_inner()); // Fetching state example inserts it into resources. #[cfg(feature = "item_state_example")] { let () = flow.graph().iter().try_for_each(|item| { let _state_example = item.state_example(&params_specs, &mapping_fn_reg, &resources)?; Ok::<_, CmdCtxTypesT::AppError>(()) })?; } let cmd_ctx_spsf = CmdCtxSpsf { output, #[cfg(feature = "output_progress")] cmd_progress_tracker, fields: CmdCtxSpsfFields { interruptibility_state, workspace, profile, profile_dir, profile_history_dir, flow, flow_dir, workspace_params_type_reg, workspace_params, profile_params_type_reg, profile_params, flow_params_type_reg, flow_params, params_specs_type_reg, params_specs, mapping_fn_reg, states_type_reg, resources, }, }; Ok(cmd_ctx_spsf) } } #[allow(non_camel_case_types)] impl<'ctx, CmdCtxTypesT, __interruptibility> IntoFuture for CmdCtxSpsfParamsBuilder< 'ctx, CmdCtxTypesT, ( (OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>,), __interruptibility, (OwnedOrRef<'ctx, Workspace>,), (ProfileSelection<'ctx, CmdCtxTypesT::WorkspaceParamsKey>,), (OwnedOrRef<'ctx, Flow<CmdCtxTypesT::AppError>>,), (WorkspaceParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::WorkspaceParamsKey>,), (ProfileParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::ProfileParamsKey>,), (FlowParamsOpt<<CmdCtxTypesT as CmdCtxTypes>::FlowParamsKey>,), (ParamsSpecs,), (Resources<Empty>,), ), > where CmdCtxTypesT: CmdCtxTypes, CmdCtxSpsfParams<'ctx, CmdCtxTypesT>: for<'__typed_builder_lifetime_for_default> ::typed_builder::NextFieldDefault< ( &'__typed_builder_lifetime_for_default OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, __interruptibility, ), Output = Interruptibility<'static>, >, __interruptibility: 'ctx, { /// Future that returns the `CmdCtxSpsf`. /// /// This is boxed since [TAIT] is not yet available ([rust#63063]). /// /// [TAIT]: https://rust-lang.github.io/impl-trait-initiative/explainer/tait.html /// [rust#63063]: https://github.com/rust-lang/rust/issues/63063 type IntoFuture = LocalBoxFuture<'ctx, Result<CmdCtxSpsf<'ctx, CmdCtxTypesT>, CmdCtxTypesT::AppError>>; type Output = <Self::IntoFuture as std::future::Future>::Output; fn into_future(self) -> Self::IntoFuture { self.build().boxed_local() } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_ctx/src/cmd_ctx_mpsf.rs
crate/cmd_ctx/src/cmd_ctx_mpsf.rs
use std::{collections::BTreeMap, fmt::Debug}; use interruptible::InterruptibilityState; use own::{OwnedOrMutRef, OwnedOrRef}; use peace_flow_rt::Flow; use peace_params::{MappingFnReg, ParamsSpecs}; use peace_profile_model::Profile; use peace_resource_rt::{ paths::{FlowDir, PeaceAppDir, PeaceDir, ProfileDir, ProfileHistoryDir, WorkspaceDir}, resources::ts::SetUp, states::StatesCurrentStored, Resources, }; use peace_rt_model::{ params::{FlowParams, ProfileParams, WorkspaceParams}, ParamsSpecsTypeReg, StatesTypeReg, Workspace, }; use type_reg::untagged::{BoxDt, TypeReg}; use crate::{CmdCtxMpsfParams, CmdCtxMpsfParamsBuilder, CmdCtxTypes}; /// A command that works with multiple profiles, and a single flow. /// /// ```bash /// path/to/repo/.peace/envman /// |- πŸ“ workspace_params.yaml # βœ… can read or write `WorkspaceParams` /// | /// |- 🌏 internal_dev_a # βœ… can list multiple `Profile`s /// | |- πŸ“ profile_params.yaml # βœ… can read multiple `ProfileParams` /// | | /// | |- 🌊 deploy # βœ… can read `FlowId` /// | | |- πŸ“ flow_params.yaml # βœ… can read or write `FlowParams` /// | | |- πŸ“‹ states_goal.yaml # βœ… can read or write `StatesGoal` /// | | |- πŸ“‹ states_current.yaml # βœ… can read or write `StatesCurrentStored` /// | | /// | |- 🌊 .. # ❌ cannot read or write other `Flow` information /// | /// |- 🌏 customer_a_dev # βœ… /// | |- πŸ“ profile_params.yaml # βœ… /// | | /// | |- 🌊 deploy # βœ… /// | |- πŸ“ flow_params.yaml # βœ… /// | |- πŸ“‹ states_goal.yaml # βœ… /// | |- πŸ“‹ states_current.yaml # βœ… /// | /// |- 🌏 customer_a_prod # βœ… /// | |- πŸ“ profile_params.yaml # βœ… /// | | /// | |- 🌊 deploy # βœ… /// | |- πŸ“ flow_params.yaml # βœ… /// | |- πŸ“‹ states_goal.yaml # βœ… /// | |- πŸ“‹ states_current.yaml # βœ… /// | /// | /// |- 🌏 workspace_init # βœ… can list multiple `Profile`s /// |- πŸ“ profile_params.yaml # ❌ cannot read profile params of different underlying type /// | |- 🌊 workspace_init # ❌ cannot read unrelated flows /// ``` /// /// ## Capabilities /// /// This kind of command can: /// /// * Read or write workspace parameters. /// * Read or write multiple profiles' parameters &ndash; as long as they are of /// the same type (same `struct`). /// * Read or write flow parameters for the same flow. /// * Read or write flow state for the same flow. /// /// This kind of command cannot: /// /// * Read or write flow parameters for different flows. /// * Read or write flow state for different flows. #[derive(Debug)] pub struct CmdCtxMpsf<'ctx, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Output endpoint to return values / errors, and write progress /// information to. /// /// See [`OutputWrite`]. /// /// [`OutputWrite`]: peace_rt_model_core::OutputWrite pub output: OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, /// Inner fields without the `output`. /// /// # Design /// /// This is necessary so that the `output` can be separated from the fields /// during execution. pub fields: CmdCtxMpsfFields<'ctx, CmdCtxTypesT>, } /// Fields of [`CmdCtxMpsf`]. /// /// # Design /// /// This is necessary so that the `output` can be separated from the fields /// during execution. #[derive(Debug)] pub struct CmdCtxMpsfFields<'ctx, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Whether the `CmdExecution` is interruptible. /// /// If it is, this holds the interrupt channel receiver. pub interruptibility_state: InterruptibilityState<'static, 'static>, /// Workspace that the `peace` tool runs in. pub workspace: OwnedOrRef<'ctx, Workspace>, /// The profiles that are accessible by this command. pub profiles: Vec<Profile>, /// Profile directories that store params and flows. pub profile_dirs: BTreeMap<Profile, ProfileDir>, /// Directories of each profile's execution history. pub profile_history_dirs: BTreeMap<Profile, ProfileHistoryDir>, /// The chosen process flow. pub flow: OwnedOrRef<'ctx, Flow<CmdCtxTypesT::AppError>>, /// Flow directory that stores params and states. pub flow_dirs: BTreeMap<Profile, FlowDir>, /// Type registry for [`WorkspaceParams`] deserialization. /// /// [`WorkspaceParams`]: peace_rt_model::params::WorkspaceParams pub workspace_params_type_reg: TypeReg<CmdCtxTypesT::WorkspaceParamsKey, BoxDt>, /// Workspace params. pub workspace_params: WorkspaceParams<CmdCtxTypesT::WorkspaceParamsKey>, /// Type registry for [`ProfileParams`] deserialization. /// /// [`ProfileParams`]: peace_rt_model::params::ProfileParams pub profile_params_type_reg: TypeReg<CmdCtxTypesT::ProfileParamsKey, BoxDt>, /// Profile params for the profile. pub profile_to_profile_params: BTreeMap<Profile, ProfileParams<CmdCtxTypesT::ProfileParamsKey>>, /// Type registry for [`FlowParams`] deserialization. /// /// [`FlowParams`]: peace_rt_model::params::FlowParams pub flow_params_type_reg: TypeReg<CmdCtxTypesT::FlowParamsKey, BoxDt>, /// Flow params for the selected flow. pub profile_to_flow_params: BTreeMap<Profile, FlowParams<CmdCtxTypesT::FlowParamsKey>>, /// Stored current states for each profile for the selected flow. pub profile_to_states_current_stored: BTreeMap<Profile, Option<StatesCurrentStored>>, /// Type registry for each item's [`Params`]`::Spec`. /// /// This is used to deserialize [`ParamsSpecsFile`]. /// /// [`Params`]: peace_cfg::Item::Params /// [`ParamsSpecsFile`]: peace_resource_rt::paths::ParamsSpecsFile pub params_specs_type_reg: ParamsSpecsTypeReg, /// Item params specs for each profile for the selected flow. pub profile_to_params_specs: BTreeMap<Profile, ParamsSpecs>, /// Mapping function registry for each item's [`Params`]`::Spec`. /// /// This maps the [`MappingFnId`] stored in [`ParamsSpecsFile`] to the /// [`MappingFn`] logic. /// /// [`MappingFn`]: peace_params::MappingFn /// [`MappingFnId`]: peace_params::MappingFnId /// [`Params`]: peace_cfg::Item::Params /// [`ParamsSpecsFile`]: peace_resource_rt::paths::ParamsSpecsFile pub mapping_fn_reg: MappingFnReg, /// Type registry for each item's `State`. /// /// This is used to deserialize [`StatesCurrentFile`] and /// [`StatesGoalFile`]. /// /// [`StatesCurrentFile`]: peace_resource_rt::paths::StatesCurrentFile /// [`StatesGoalFile`]: peace_resource_rt::paths::StatesGoalFile pub states_type_reg: StatesTypeReg, /// `Resources` for flow execution. pub resources: Resources<SetUp>, } impl<'ctx, CmdCtxTypesT> CmdCtxMpsf<'ctx, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Returns a [`CmdCtxMpsfParamsBuilder`] to construct this command context. pub fn builder<'ctx_local>() -> CmdCtxMpsfParamsBuilder<'ctx_local, CmdCtxTypesT> { CmdCtxMpsfParams::<'ctx_local, CmdCtxTypesT>::builder() } /// Returns a reference to the output. pub fn output(&self) -> &CmdCtxTypesT::Output { &self.output } /// Returns a mutable reference to the output. pub fn output_mut(&mut self) -> &mut CmdCtxTypesT::Output { &mut self.output } /// Returns a reference to the fields. pub fn fields(&self) -> &CmdCtxMpsfFields<'_, CmdCtxTypesT> { &self.fields } /// Returns a mutable reference to the fields. pub fn fields_mut(&mut self) -> &mut CmdCtxMpsfFields<'ctx, CmdCtxTypesT> { &mut self.fields } } impl<CmdCtxTypesT> CmdCtxMpsfFields<'_, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Returns the interruptibility capability. pub fn interruptibility_state(&mut self) -> InterruptibilityState<'_, '_> { self.interruptibility_state.reborrow() } /// Returns the workspace that the `peace` tool runs in. pub fn workspace(&self) -> &Workspace { &self.workspace } /// Returns a reference to the workspace directory. pub fn workspace_dir(&self) -> &WorkspaceDir { self.workspace.dirs().workspace_dir() } /// Returns a reference to the `.peace` directory. pub fn peace_dir(&self) -> &PeaceDir { self.workspace.dirs().peace_dir() } /// Returns a reference to the `.peace/$app` directory. pub fn peace_app_dir(&self) -> &PeaceAppDir { self.workspace.dirs().peace_app_dir() } /// Returns the accessible profiles. /// /// These are the profiles that are filtered by the filter function, if /// provided. pub fn profiles(&self) -> &[Profile] { self.profiles.as_ref() } /// Returns the profile directories keyed by each profile. pub fn profile_dirs(&self) -> &BTreeMap<Profile, ProfileDir> { &self.profile_dirs } /// Returns the profile history directories keyed by each profile. pub fn profile_history_dirs(&self) -> &BTreeMap<Profile, ProfileHistoryDir> { &self.profile_history_dirs } /// Returns the flow. pub fn flow(&self) -> &Flow<CmdCtxTypesT::AppError> { &self.flow } /// Returns the flow directories keyed by each profile. pub fn flow_dirs(&self) -> &BTreeMap<Profile, FlowDir> { &self.flow_dirs } /// Returns a reference to the workspace params type registry. pub fn workspace_params_type_reg(&self) -> &TypeReg<CmdCtxTypesT::WorkspaceParamsKey, BoxDt> { &self.workspace_params_type_reg } /// Returns a mutable reference to the workspace params type registry. pub fn workspace_params_type_reg_mut( &mut self, ) -> &mut TypeReg<CmdCtxTypesT::WorkspaceParamsKey, BoxDt> { &mut self.workspace_params_type_reg } /// Returns the workspace params. pub fn workspace_params(&self) -> &WorkspaceParams<CmdCtxTypesT::WorkspaceParamsKey> { &self.workspace_params } /// Returns the workspace params. pub fn workspace_params_mut( &mut self, ) -> &mut WorkspaceParams<CmdCtxTypesT::WorkspaceParamsKey> { &mut self.workspace_params } /// Returns a reference to the profile params type registry. pub fn profile_params_type_reg(&self) -> &TypeReg<CmdCtxTypesT::ProfileParamsKey, BoxDt> { &self.profile_params_type_reg } /// Returns a mutable reference to the profile params type registry. pub fn profile_params_type_reg_mut( &mut self, ) -> &mut TypeReg<CmdCtxTypesT::ProfileParamsKey, BoxDt> { &mut self.profile_params_type_reg } /// Returns the profile params for each profile. pub fn profile_to_profile_params( &self, ) -> &BTreeMap<Profile, ProfileParams<CmdCtxTypesT::ProfileParamsKey>> { &self.profile_to_profile_params } /// Returns the profile params for each profile. pub fn profile_to_profile_params_mut( &mut self, ) -> &mut BTreeMap<Profile, ProfileParams<CmdCtxTypesT::ProfileParamsKey>> { &mut self.profile_to_profile_params } /// Returns a reference to the flow params type registry. pub fn flow_params_type_reg(&self) -> &TypeReg<CmdCtxTypesT::FlowParamsKey, BoxDt> { &self.flow_params_type_reg } /// Returns a mutable reference to the flow params type registry. pub fn flow_params_type_reg_mut(&mut self) -> &mut TypeReg<CmdCtxTypesT::FlowParamsKey, BoxDt> { &mut self.flow_params_type_reg } /// Returns the flow params for each profile. pub fn profile_to_flow_params( &self, ) -> &BTreeMap<Profile, FlowParams<CmdCtxTypesT::FlowParamsKey>> { &self.profile_to_flow_params } /// Returns the flow params for each profile. pub fn profile_to_flow_params_mut( &mut self, ) -> &mut BTreeMap<Profile, FlowParams<CmdCtxTypesT::FlowParamsKey>> { &mut self.profile_to_flow_params } /// Returns the stored current states for each profile for the selected /// flow. pub fn profile_to_states_current_stored( &self, ) -> &BTreeMap<Profile, Option<StatesCurrentStored>> { &self.profile_to_states_current_stored } /// Returns the type registry for each item's [`Params`]`::Spec`. /// /// This is used to deserialize [`ParamsSpecsFile`]. /// /// [`Params`]: peace_cfg::Item::Params /// [`ParamsSpecsFile`]: peace_resource_rt::paths::ParamsSpecsFile pub fn params_specs_type_reg(&self) -> &ParamsSpecsTypeReg { &self.params_specs_type_reg } /// Returns the item params specs for each profile for the selected /// flow. pub fn profile_to_params_specs(&self) -> &BTreeMap<Profile, ParamsSpecs> { &self.profile_to_params_specs } /// Returns the mapping function registry for each item's /// [`Params`]`::Spec`. /// /// This maps the [`MappingFnId`] stored in [`ParamsSpecsFile`] to the /// [`MappingFn`] logic. /// /// [`MappingFn`]: peace_params::MappingFn /// [`MappingFnId`]: peace_params::MappingFnId /// [`Params`]: peace_cfg::Item::Params /// [`ParamsSpecsFile`]: peace_resource_rt::paths::ParamsSpecsFile pub fn mapping_fn_reg(&self) -> &MappingFnReg { &self.mapping_fn_reg } /// Returns the type registry for each item's `State`. /// /// This is used to deserialize [`StatesCurrentFile`] and /// [`StatesGoalFile`]. /// /// [`StatesCurrentFile`]: peace_resource_rt::paths::StatesCurrentFile /// [`StatesGoalFile`]: peace_resource_rt::paths::StatesGoalFile pub fn states_type_reg(&self) -> &StatesTypeReg { &self.states_type_reg } /// Returns a reference to the `Resources` for flow execution. pub fn resources(&self) -> &Resources<SetUp> { &self.resources } /// Returns a reference to the `Resources` for flow execution. pub fn resources_mut(&mut self) -> &mut Resources<SetUp> { &mut self.resources } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_ctx/src/cmd_ctx_builder_support.rs
crate/cmd_ctx/src/cmd_ctx_builder_support.rs
use futures::{StreamExt, TryStreamExt}; use peace_flow_rt::{Flow, ItemGraph}; use peace_item_model::ItemId; use peace_params::{MappingFnReg, MappingFns, ParamsKey, ParamsSpecs}; use peace_profile_model::Profile; use peace_resource_rt::{ internal::{FlowParamsFile, ProfileParamsFile, WorkspaceParamsFile}, paths::ParamsSpecsFile, resources::ts::{Empty, SetUp}, Resource, Resources, }; use peace_rt_model::{ params::{ FlowParams, FlowParamsOpt, ProfileParams, ProfileParamsOpt, WorkspaceParams, WorkspaceParamsOpt, }, ParamsSpecsSerializer, ParamsSpecsTypeReg, StatesTypeReg, Storage, WorkspaceInitializer, }; use type_reg::untagged::{BoxDt, TypeReg}; use crate::ProfileSelection; /// Common code used to build different `CmdCtx*` types. pub(crate) struct CmdCtxBuilderSupport; impl CmdCtxBuilderSupport { /// Selects a profile from the given profile selection. pub async fn profile_from_profile_selection<WorkspaceParamsK>( profile_selection: ProfileSelection<'_, WorkspaceParamsK>, workspace_params: &WorkspaceParams<WorkspaceParamsK>, storage: &peace_rt_model::Storage, workspace_params_file: &WorkspaceParamsFile, ) -> Result<Profile, peace_rt_model::Error> where WorkspaceParamsK: ParamsKey, { match profile_selection { ProfileSelection::Specified(profile) => Ok(profile), ProfileSelection::FromWorkspaceParam(workspace_params_k_profile) => { let profile_from_workspace_params = workspace_params.get(&workspace_params_k_profile).cloned(); match profile_from_workspace_params { Some(profile) => Ok(profile), None => { let profile_key = storage .serialized_write_string( &*workspace_params_k_profile, peace_rt_model::Error::WorkspaceParamsProfileKeySerialize, ) .expect("Failed to serialize workspace params profile key.") .trim_end() .to_string(); let workspace_params_file = workspace_params_file.clone(); let workspace_params_file_contents = storage .read_to_string(&workspace_params_file) .await .unwrap_or_default(); Err(peace_rt_model::Error::WorkspaceParamsProfileNone { profile_key, workspace_params_file, workspace_params_file_contents, }) } } } } } /// Returns a [`TypeReg`] to deserialize workspace, profile, or flow params. pub(crate) fn params_type_reg_initialize<PKeys>() -> TypeReg<PKeys, BoxDt> where PKeys: ParamsKey, { let mut params_type_reg = TypeReg::new(); enum_iterator::all::<PKeys>().for_each(|params_key| { params_key.register_value_type(&mut params_type_reg); }); params_type_reg } /// Merges workspace params provided by the caller with the workspace params /// on disk. /// /// Type registry for [`WorkspaceParams`] deserialization. /// /// [`WorkspaceParams`]: peace_rt_model::params::WorkspaceParams pub(crate) async fn workspace_params_merge<WorkspaceParamsK>( storage: &peace_rt_model::Storage, workspace_params_type_reg: &TypeReg<WorkspaceParamsK, BoxDt>, workspace_params_provided: WorkspaceParamsOpt<WorkspaceParamsK>, workspace_params_file: &peace_resource_rt::internal::WorkspaceParamsFile, ) -> Result<WorkspaceParams<WorkspaceParamsK>, peace_rt_model::Error> where WorkspaceParamsK: ParamsKey, { let params_deserialized = WorkspaceInitializer::workspace_params_deserialize::< WorkspaceParamsK, >( storage, workspace_params_type_reg, workspace_params_file ) .await?; let mut workspace_params = params_deserialized.unwrap_or_default(); workspace_params_provided .into_inner() .into_inner() .into_iter() .for_each(|(key, param)| { let _ = match param { Some(value) => workspace_params.insert_raw(key, value), None => workspace_params.shift_remove(&key), }; }); Ok(workspace_params) } /// Merges profile params provided by the caller with the profile params /// on disk. /// /// Type registry for [`ProfileParams`] deserialization. /// /// [`ProfileParams`]: peace_rt_model::params::ProfileParams pub(crate) async fn profile_params_merge<ProfileParamsK>( storage: &peace_rt_model::Storage, profile_params_type_reg: &TypeReg<ProfileParamsK, BoxDt>, profile_params_provided: ProfileParamsOpt<ProfileParamsK>, profile_params_file: &peace_resource_rt::internal::ProfileParamsFile, ) -> Result<ProfileParams<ProfileParamsK>, peace_rt_model::Error> where ProfileParamsK: ParamsKey, { let params_deserialized = WorkspaceInitializer::profile_params_deserialize::<ProfileParamsK>( storage, profile_params_type_reg, profile_params_file, ) .await?; let mut profile_params = params_deserialized.unwrap_or_default(); profile_params_provided .into_inner() .into_inner() .into_iter() .for_each(|(key, param)| { let _ = match param { Some(value) => profile_params.insert_raw(key, value), None => profile_params.shift_remove(&key), }; }); Ok(profile_params) } /// Merges flow params provided by the caller with the flow params /// on disk. /// /// Type registry for [`FlowParams`] deserialization. /// /// [`FlowParams`]: peace_rt_model::params::FlowParams pub(crate) async fn flow_params_merge<FlowParamsK>( storage: &peace_rt_model::Storage, flow_params_type_reg: &TypeReg<FlowParamsK, BoxDt>, flow_params_provided: FlowParamsOpt<FlowParamsK>, flow_params_file: &peace_resource_rt::internal::FlowParamsFile, ) -> Result<FlowParams<FlowParamsK>, peace_rt_model::Error> where FlowParamsK: ParamsKey, { let params_deserialized = WorkspaceInitializer::flow_params_deserialize::<FlowParamsK>( storage, flow_params_type_reg, flow_params_file, ) .await?; let mut flow_params = params_deserialized.unwrap_or_default(); flow_params_provided .into_inner() .into_inner() .into_iter() .for_each(|(key, param)| { let _ = match param { Some(value) => flow_params.insert_raw(key, value), None => flow_params.shift_remove(&key), }; }); Ok(flow_params) } /// Serializes workspace params to storage. pub(crate) async fn workspace_params_serialize<WorkspaceParamsK>( workspace_params: &WorkspaceParams<WorkspaceParamsK>, storage: &Storage, workspace_params_file: &WorkspaceParamsFile, ) -> Result<(), peace_rt_model::Error> where WorkspaceParamsK: ParamsKey, { WorkspaceInitializer::workspace_params_serialize( storage, workspace_params, workspace_params_file, ) .await?; Ok(()) } /// Inserts workspace params into the `Resources` map. pub(crate) fn workspace_params_insert<WorkspaceParamsK>( mut workspace_params: WorkspaceParams<WorkspaceParamsK>, resources: &mut Resources<Empty>, ) where WorkspaceParamsK: ParamsKey, { workspace_params .drain(..) .for_each(|(_key, workspace_param)| { let workspace_param = workspace_param.into_inner().upcast(); let type_id = Resource::type_id(&*workspace_param); resources.insert_raw(type_id, workspace_param); }); } /// Serializes profile params to storage. pub(crate) async fn profile_params_serialize<ProfileParamsK>( profile_params: &ProfileParams<ProfileParamsK>, storage: &Storage, profile_params_file: &ProfileParamsFile, ) -> Result<(), peace_rt_model::Error> where ProfileParamsK: ParamsKey, { WorkspaceInitializer::profile_params_serialize( storage, profile_params, profile_params_file, ) .await?; Ok(()) } /// Inserts profile params into the `Resources` map. pub(crate) fn profile_params_insert<ProfileParamsK>( mut profile_params: ProfileParams<ProfileParamsK>, resources: &mut Resources<Empty>, ) where ProfileParamsK: ParamsKey, { profile_params.drain(..).for_each(|(_key, profile_param)| { let profile_param = profile_param.into_inner().upcast(); let type_id = Resource::type_id(&*profile_param); resources.insert_raw(type_id, profile_param); }); } /// Serializes flow params to storage. pub(crate) async fn flow_params_serialize<FlowParamsK>( flow_params: &FlowParams<FlowParamsK>, storage: &Storage, flow_params_file: &FlowParamsFile, ) -> Result<(), peace_rt_model::Error> where FlowParamsK: ParamsKey, { WorkspaceInitializer::flow_params_serialize(storage, flow_params, flow_params_file).await?; Ok(()) } /// Serializes item params to storage. pub(crate) async fn params_specs_serialize( params_specs: &ParamsSpecs, storage: &Storage, params_specs_file: &ParamsSpecsFile, ) -> Result<(), peace_rt_model::Error> { ParamsSpecsSerializer::serialize(storage, params_specs, params_specs_file).await } /// Inserts flow params into the `Resources` map. pub(crate) fn flow_params_insert<FlowParamsK>( mut flow_params: FlowParams<FlowParamsK>, resources: &mut Resources<Empty>, ) where FlowParamsK: ParamsKey, { flow_params.drain(..).for_each(|(_key, flow_param)| { let flow_param = flow_param.into_inner().upcast(); let type_id = Resource::type_id(&*flow_param); resources.insert_raw(type_id, flow_param); }); } /// Registers each item's `Params` and `State` for stateful /// deserialization. pub(crate) fn params_and_states_type_reg<E>( item_graph: &ItemGraph<E>, ) -> (ParamsSpecsTypeReg, StatesTypeReg) where E: 'static, { item_graph.iter().fold( (ParamsSpecsTypeReg::new(), StatesTypeReg::new()), |(mut params_specs_type_reg, mut states_type_reg), item| { item.params_and_state_register(&mut params_specs_type_reg, &mut states_type_reg); (params_specs_type_reg, states_type_reg) }, ) } /// Merges provided item parameters with previously stored item /// parameters. /// /// If an item's parameters are not provided, and nothing was previously /// stored, then an error is returned. pub(crate) fn params_specs_merge<E>( flow: &Flow<E>, mut params_specs_provided: ParamsSpecs, params_specs_stored: Option<ParamsSpecs>, ) -> Result<ParamsSpecs, peace_rt_model::Error> where E: From<peace_rt_model::Error> + 'static, { // Combine provided and stored params specs. Provided params specs take // precedence. // // We construct a new TypeMap because we want to make sure params specs are // serialized in order of the items in the graph. let item_graph = flow.graph(); let mut params_specs = ParamsSpecs::with_capacity(item_graph.node_count()); // Collected erroneous data -- parameters may have been valid in the past, but: // // * item IDs may have changed. // * items may have been removed, but params specs remain. // * items may have been added, but params specs forgotten to be added. let mut item_ids_with_no_params_specs = Vec::<ItemId>::new(); let mut params_specs_stored_mismatches = None; let mut params_specs_not_usable = Vec::<ItemId>::new(); if let Some(mut params_specs_stored) = params_specs_stored { item_graph.iter_insertion().for_each(|item_rt| { let item_id = item_rt.id(); // Removing the entry from stored params specs is deliberate, so filtering for // stored params specs that no longer have a corresponding item are // detected. let params_spec_provided = params_specs_provided.shift_remove_entry(item_id); let params_spec_stored = params_specs_stored.shift_remove_entry(item_id); // Deep merge params specs. let params_spec_to_use = match (params_spec_provided, params_spec_stored) { (None, None) => None, (None, Some(params_spec_stored)) => Some(params_spec_stored), // Newly added item, or potentially renamed. (Some(params_spec_provided), None) => Some(params_spec_provided), ( Some((item_id, mut params_spec_provided)), Some((_item_id, params_spec_stored)), ) => { params_spec_provided.merge(&*params_spec_stored); Some((item_id, params_spec_provided)) } }; if let Some((item_id, params_spec_boxed)) = params_spec_to_use { // Field wise `ParamsSpec`s may contain `ValueSpec::Stored` for fields // which never had specifications, which are unusable. if params_spec_boxed.is_usable() { params_specs.insert_raw(item_id, params_spec_boxed); } else { params_specs_not_usable.push(item_id); } } else { // Collect items that do not have parameters. item_ids_with_no_params_specs.push(item_id.clone()); } }); // Stored parameters whose IDs do not correspond to any item IDs in the // graph. May be empty. params_specs_stored_mismatches = Some(params_specs_stored); } else { item_graph.iter_insertion().for_each(|item_rt| { let item_id = item_rt.id(); if let Some((item_id, params_spec_boxed)) = params_specs_provided.shift_remove_entry(item_id) { params_specs.insert_raw(item_id, params_spec_boxed); } else { // Collect items that do not have parameters. item_ids_with_no_params_specs.push(item_id.clone()); } }); } // Provided parameters whose IDs do not correspond to any item IDs in the // graph. let params_specs_provided_mismatches = params_specs_provided; let params_no_issues = item_ids_with_no_params_specs.is_empty() && params_specs_provided_mismatches.is_empty() && params_specs_stored_mismatches .as_ref() .map(|params_specs_stored_mismatches| params_specs_stored_mismatches.is_empty()) .unwrap_or(true) && params_specs_not_usable.is_empty(); if params_no_issues { Ok(params_specs) } else { let params_specs_stored_mismatches = Box::new(params_specs_stored_mismatches); let params_specs_provided_mismatches = Box::new(params_specs_provided_mismatches); Err(peace_rt_model::Error::ParamsSpecsMismatch { item_ids_with_no_params_specs, params_specs_provided_mismatches, params_specs_stored_mismatches, params_specs_not_usable, }) } } /// Registers each mapping function with the `MappingFnReg` and inserts it /// into `resources`. /// /// This is also needed whenever flow params need to be deserialized. #[must_use] pub(crate) fn mapping_fn_reg_setup<MFns>() -> MappingFnReg where MFns: MappingFns, { let mut mapping_fn_reg = MappingFnReg::new(); mapping_fn_reg.register_all::<MFns>(); mapping_fn_reg } pub(crate) async fn item_graph_setup<E>( item_graph: &ItemGraph<E>, resources: Resources<Empty>, ) -> Result<Resources<SetUp>, E> where E: std::error::Error + 'static, { let resources = item_graph .stream() .map(Ok::<_, E>) .try_fold(resources, |mut resources, item| async move { item.setup(&mut resources).await?; Ok(resources) }) .await?; Ok(Resources::<SetUp>::from(resources)) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_ctx/src/cmd_ctx_spsf.rs
crate/cmd_ctx/src/cmd_ctx_spsf.rs
use interruptible::InterruptibilityState; use own::{OwnedOrMutRef, OwnedOrRef}; use peace_flow_rt::Flow; use peace_params::{MappingFnReg, ParamsSpecs}; use peace_profile_model::Profile; use peace_resource_rt::{ paths::{FlowDir, PeaceAppDir, PeaceDir, ProfileDir, ProfileHistoryDir, WorkspaceDir}, resources::ts::SetUp, Resources, }; use peace_rt_model::{ParamsSpecsTypeReg, StatesTypeReg, Workspace}; use peace_rt_model_core::params::{FlowParams, ProfileParams, WorkspaceParams}; use type_reg::untagged::{BoxDt, TypeReg}; use crate::{CmdCtxSpsfParams, CmdCtxSpsfParamsBuilder, CmdCtxTypes}; /// Context for a command that works with one profile and one flow. /// /// ```bash /// path/to/repo/.peace/envman /// |- πŸ“ workspace_params.yaml # βœ… can read or write `WorkspaceParams` /// | /// |- 🌏 internal_dev_a /// | |- πŸ“ profile_params.yaml # βœ… can read or write `ProfileParams` /// | | /// | |- 🌊 deploy # βœ… can read `FlowId` /// | | |- πŸ“ flow_params.yaml # βœ… can read or write `FlowParams` /// | | |- πŸ“‹ states_goal.yaml # βœ… can read or write `StatesGoal` /// | | |- πŸ“‹ states_current.yaml # βœ… can read or write `StatesCurrentStored` /// | | /// | |- 🌊 .. # ❌ cannot read or write other `Flow` information /// | /// |- 🌏 .. # ❌ cannot read or write other `Profile` information /// ``` /// /// ## Capabilities /// /// This kind of command can: /// /// * Read or write workspace parameters. /// * Read or write a single profile's parameters. For multiple profiles, see /// [`CmdCtxMpsf`]. /// /// [`CmdCtxMpsf`]: crate::CmdCtxMpsf #[derive(Debug)] pub struct CmdCtxSpsf<'ctx, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Output endpoint to return values / errors, and write progress /// information to. /// /// See [`OutputWrite`]. /// /// [`OutputWrite`]: peace_rt_model_core::OutputWrite pub output: OwnedOrMutRef<'ctx, CmdCtxTypesT::Output>, /// Tracks progress of each function execution. #[cfg(feature = "output_progress")] pub cmd_progress_tracker: peace_rt_model::CmdProgressTracker, /// Inner fields without the `output` and `cmd_progress_tracker`. /// /// # Design /// /// This is necessary so that the `output` and `cmd_progress_tracker` can be /// used in `CmdExecution` while passing the fields to the `CmdBlock`. pub fields: CmdCtxSpsfFields<'ctx, CmdCtxTypesT>, } /// Fields of [`CmdCtxSpsf`]. /// /// # Design /// /// This is necessary so that the `output` and `cmd_progress_tracker` can be /// used in `CmdExecution` while passing the fields to the `CmdBlock`. #[derive(Debug)] pub struct CmdCtxSpsfFields<'ctx, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Whether the `CmdExecution` is interruptible. /// /// If it is, this holds the interrupt channel receiver. pub interruptibility_state: InterruptibilityState<'static, 'static>, /// Workspace that the `peace` tool runs in. pub workspace: OwnedOrRef<'ctx, Workspace>, /// The profile this command operates on. pub profile: Profile, /// Profile directory that stores params and flows. pub profile_dir: ProfileDir, /// Directory to store profile execution history. pub profile_history_dir: ProfileHistoryDir, /// The chosen process flow. pub flow: OwnedOrRef<'ctx, Flow<CmdCtxTypesT::AppError>>, /// Flow directory that stores params and states. pub flow_dir: FlowDir, /// Type registry for [`WorkspaceParams`] deserialization. /// /// [`WorkspaceParams`]: peace_rt_model::params::WorkspaceParams pub workspace_params_type_reg: TypeReg<CmdCtxTypesT::WorkspaceParamsKey, BoxDt>, /// Workspace params. pub workspace_params: WorkspaceParams<CmdCtxTypesT::WorkspaceParamsKey>, /// Type registry for [`ProfileParams`] deserialization. /// /// [`ProfileParams`]: peace_rt_model::params::ProfileParams pub profile_params_type_reg: TypeReg<CmdCtxTypesT::ProfileParamsKey, BoxDt>, /// Profile params for the profile. pub profile_params: ProfileParams<CmdCtxTypesT::ProfileParamsKey>, /// Type registry for [`FlowParams`] deserialization. /// /// [`FlowParams`]: peace_rt_model::params::FlowParams pub flow_params_type_reg: TypeReg<CmdCtxTypesT::FlowParamsKey, BoxDt>, /// Flow params for the selected flow. pub flow_params: FlowParams<CmdCtxTypesT::FlowParamsKey>, /// Type registry for each item's [`Params`]`::Spec`. /// /// This is used to deserialize [`ParamsSpecsFile`]. /// /// [`Params`]: peace_cfg::Item::Params /// [`ParamsSpecsFile`]: peace_resource_rt::paths::ParamsSpecsFile pub params_specs_type_reg: ParamsSpecsTypeReg, /// Item params specs for the selected flow. pub params_specs: ParamsSpecs, /// Mapping function registry for each item's [`Params`]`::Spec`. /// /// This maps the [`MappingFnId`] stored in [`ParamsSpecsFile`] to the /// [`MappingFn`] logic. /// /// [`MappingFn`]: peace_params::MappingFn /// [`MappingFnId`]: peace_params::MappingFnId /// [`Params`]: peace_cfg::Item::Params /// [`ParamsSpecsFile`]: peace_resource_rt::paths::ParamsSpecsFile pub mapping_fn_reg: MappingFnReg, /// Type registry for each item's `State`. /// /// This is used to deserialize [`StatesCurrentFile`] and /// [`StatesGoalFile`]. /// /// [`StatesCurrentFile`]: peace_resource_rt::paths::StatesCurrentFile /// [`StatesGoalFile`]: peace_resource_rt::paths::StatesGoalFile pub states_type_reg: StatesTypeReg, /// `Resources` for flow execution. pub resources: Resources<SetUp>, } impl<'ctx, CmdCtxTypesT> CmdCtxSpsf<'ctx, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Returns a [`CmdCtxSpsfParamsBuilder`] to construct this command context. pub fn builder<'ctx_local>() -> CmdCtxSpsfParamsBuilder<'ctx_local, CmdCtxTypesT> { CmdCtxSpsfParams::<'ctx_local, CmdCtxTypesT>::builder() } /// Returns a reference to the output. pub fn output(&self) -> &CmdCtxTypesT::Output { &self.output } /// Returns a mutable reference to the output. pub fn output_mut(&mut self) -> &mut CmdCtxTypesT::Output { &mut self.output } /// Returns the progress tracker for all functions' executions. #[cfg(feature = "output_progress")] pub fn cmd_progress_tracker(&self) -> &peace_rt_model::CmdProgressTracker { &self.cmd_progress_tracker } /// Returns a mutable reference to the progress tracker for all functions' /// executions. #[cfg(feature = "output_progress")] pub fn cmd_progress_tracker_mut(&mut self) -> &mut peace_rt_model::CmdProgressTracker { &mut self.cmd_progress_tracker } /// Returns a reference to the fields. pub fn fields(&self) -> &CmdCtxSpsfFields<'_, CmdCtxTypesT> { &self.fields } /// Returns a mutable reference to the fields. pub fn fields_mut(&mut self) -> &mut CmdCtxSpsfFields<'ctx, CmdCtxTypesT> { &mut self.fields } } impl<CmdCtxTypesT> CmdCtxSpsfFields<'_, CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Returns the interruptibility capability. pub fn interruptibility_state(&mut self) -> InterruptibilityState<'_, '_> { self.interruptibility_state.reborrow() } /// Returns the workspace that the `peace` tool runs in. pub fn workspace(&self) -> &Workspace { &self.workspace } /// Returns a reference to the workspace directory. /// /// Convenience method for `cmd_ctx_Spsf.workspace.dirs().workspace_dir()`. pub fn workspace_dir(&self) -> &WorkspaceDir { self.workspace.dirs().workspace_dir() } /// Returns a reference to the `.peace` directory. /// /// Convenience method for `cmd_ctx_Spsf.workspace.dirs().peace_dir()`. pub fn peace_dir(&self) -> &PeaceDir { self.workspace.dirs().peace_dir() } /// Returns a reference to the `.peace/$app` directory. /// /// Convenience method for `cmd_ctx_Spsf.workspace.dirs().peace_app_dir()`. pub fn peace_app_dir(&self) -> &PeaceAppDir { self.workspace.dirs().peace_app_dir() } /// Returns a reference to the profile. pub fn profile(&self) -> &Profile { &self.profile } /// Returns a reference to the profile directory. pub fn profile_dir(&self) -> &ProfileDir { &self.profile_dir } /// Returns a reference to the profile history directory. pub fn profile_history_dir(&self) -> &ProfileHistoryDir { &self.profile_history_dir } /// Returns a reference to the flow. pub fn flow(&self) -> &Flow<CmdCtxTypesT::AppError> { &self.flow } /// Returns a reference to the flow directory. pub fn flow_dir(&self) -> &FlowDir { &self.flow_dir } /// Returns a reference to the workspace params type registry. pub fn workspace_params_type_reg(&self) -> &TypeReg<CmdCtxTypesT::WorkspaceParamsKey, BoxDt> { &self.workspace_params_type_reg } /// Returns a mutable reference to the workspace params type registry. pub fn workspace_params_type_reg_mut( &mut self, ) -> &mut TypeReg<CmdCtxTypesT::WorkspaceParamsKey, BoxDt> { &mut self.workspace_params_type_reg } /// Returns the workspace params. pub fn workspace_params(&self) -> &WorkspaceParams<CmdCtxTypesT::WorkspaceParamsKey> { &self.workspace_params } /// Returns the workspace params. pub fn workspace_params_mut( &mut self, ) -> &mut WorkspaceParams<CmdCtxTypesT::WorkspaceParamsKey> { &mut self.workspace_params } /// Returns a reference to the profile params type registry. pub fn profile_params_type_reg(&self) -> &TypeReg<CmdCtxTypesT::ProfileParamsKey, BoxDt> { &self.profile_params_type_reg } /// Returns a mutable reference to the profile params type registry. pub fn profile_params_type_reg_mut( &mut self, ) -> &mut TypeReg<CmdCtxTypesT::ProfileParamsKey, BoxDt> { &mut self.profile_params_type_reg } /// Returns the profile params. pub fn profile_params(&self) -> &ProfileParams<CmdCtxTypesT::ProfileParamsKey> { &self.profile_params } /// Returns the profile params. pub fn profile_params_mut(&mut self) -> &mut ProfileParams<CmdCtxTypesT::ProfileParamsKey> { &mut self.profile_params } /// Returns a reference to the flow params type registry. pub fn flow_params_type_reg(&self) -> &TypeReg<CmdCtxTypesT::FlowParamsKey, BoxDt> { &self.flow_params_type_reg } /// Returns a mutable reference to the flow params type registry. pub fn flow_params_type_reg_mut(&mut self) -> &mut TypeReg<CmdCtxTypesT::FlowParamsKey, BoxDt> { &mut self.flow_params_type_reg } /// Returns the flow params. pub fn flow_params(&self) -> &FlowParams<CmdCtxTypesT::FlowParamsKey> { &self.flow_params } /// Returns the flow params. pub fn flow_params_mut(&mut self) -> &mut FlowParams<CmdCtxTypesT::FlowParamsKey> { &mut self.flow_params } /// Returns the type registry for each item's [`Params`]`::Spec`. /// /// This is used to deserialize [`ParamsSpecsFile`]. /// /// [`Params`]: peace_cfg::Item::Params /// [`ParamsSpecsFile`]: peace_resource_rt::paths::ParamsSpecsFile pub fn params_specs_type_reg(&self) -> &ParamsSpecsTypeReg { &self.params_specs_type_reg } /// Returns the item params specs for the selected flow. pub fn params_specs(&self) -> &ParamsSpecs { &self.params_specs } /// Returns the mapping function registry for each item's /// [`Params`]`::Spec`. /// /// This maps the [`MappingFnId`] stored in [`ParamsSpecsFile`] to the /// [`MappingFn`] logic. /// /// [`MappingFn`]: peace_params::MappingFn /// [`MappingFnId`]: peace_params::MappingFnId /// [`Params`]: peace_cfg::Item::Params /// [`ParamsSpecsFile`]: peace_resource_rt::paths::ParamsSpecsFile pub fn mapping_fn_reg(&self) -> &MappingFnReg { &self.mapping_fn_reg } /// Returns the type registry for each item's `State`. /// /// This is used to deserialize [`StatesCurrentFile`] and /// [`StatesGoalFile`]. /// /// [`StatesCurrentFile`]: peace_resource_rt::paths::StatesCurrentFile /// [`StatesGoalFile`]: peace_resource_rt::paths::StatesGoalFile pub fn states_type_reg(&self) -> &StatesTypeReg { &self.states_type_reg } /// Returns a reference to the `Resources` for flow execution. pub fn resources(&self) -> &Resources<SetUp> { &self.resources } /// Returns a reference to the `Resources` for flow execution. pub fn resources_mut(&mut self) -> &mut Resources<SetUp> { &mut self.resources } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cmd_ctx/src/cmd_ctx_builder_support_multi.rs
crate/cmd_ctx/src/cmd_ctx_builder_support_multi.rs
use futures::stream::TryStreamExt; use own::OwnedOrRef; use peace_flow_model::FlowId; use peace_flow_rt::Flow; use peace_params::ParamsSpecs; use peace_profile_model::Profile; use peace_resource_rt::{ internal::{FlowParamsFile, ProfileParamsFile, WorkspaceDirs}, paths::{ FlowDir, ParamsSpecsFile, PeaceAppDir, ProfileDir, ProfileHistoryDir, StatesCurrentFile, }, states::{ts::CurrentStored, States, StatesCurrentStored}, }; use peace_rt_model::{ params::{FlowParamsOpt, ProfileParams, ProfileParamsOpt}, ParamsSpecsSerializer, StatesTypeReg, }; use peace_rt_model_core::params::FlowParams; use peace_state_rt::StatesSerializer; use std::{collections::BTreeMap, marker::PhantomData}; use type_reg::untagged::TypeReg; use crate::{CmdCtxBuilderSupport, CmdCtxTypes, ProfileFilterFn}; /// Common code used to build different `CmdCtxM*` types. pub(crate) struct CmdCtxBuilderSupportMulti<CmdCtxTypesT>(PhantomData<CmdCtxTypesT>); impl<CmdCtxTypesT> CmdCtxBuilderSupportMulti<CmdCtxTypesT> where CmdCtxTypesT: CmdCtxTypes, { /// Reads the the `Profile` and `ProfileHistory` directory paths into /// memory. pub(crate) fn profile_and_history_dirs_read( profiles_ref: &[Profile], workspace_dirs: &WorkspaceDirs, ) -> ( BTreeMap<Profile, ProfileDir>, BTreeMap<Profile, ProfileHistoryDir>, ) where CmdCtxTypesT: CmdCtxTypes, { let (profile_dirs, profile_history_dirs) = profiles_ref.iter().fold( ( BTreeMap::<Profile, ProfileDir>::new(), BTreeMap::<Profile, ProfileHistoryDir>::new(), ), |(mut profile_dirs, mut profile_history_dirs), profile| { let profile_dir = ProfileDir::from((workspace_dirs.peace_app_dir(), profile)); let profile_history_dir = ProfileHistoryDir::from(&profile_dir); profile_dirs.insert(profile.clone(), profile_dir); profile_history_dirs.insert(profile.clone(), profile_history_dir); (profile_dirs, profile_history_dirs) }, ); (profile_dirs, profile_history_dirs) } /// Reads the the `Flow`directory paths into memory. pub(crate) fn flow_dirs_read( profile_dirs: &BTreeMap<Profile, ProfileDir>, flow: &OwnedOrRef<'_, Flow<CmdCtxTypesT::AppError>>, ) -> BTreeMap<Profile, FlowDir> { let flow_dirs = profile_dirs.iter().fold( BTreeMap::<Profile, FlowDir>::new(), |mut flow_dirs, (profile, profile_dir)| { let flow_dir = FlowDir::from((profile_dir, flow.flow_id())); flow_dirs.insert(profile.clone(), flow_dir); flow_dirs }, ); flow_dirs } pub(crate) async fn profile_params_deserialize( profile_dirs: &BTreeMap<Profile, ProfileDir>, mut profile_to_profile_params_provided: BTreeMap< Profile, ProfileParamsOpt<CmdCtxTypesT::ProfileParamsKey>, >, storage: &peace_rt_model::Storage, profile_params_type_reg_ref: &TypeReg<CmdCtxTypesT::ProfileParamsKey>, ) -> Result< BTreeMap<Profile, ProfileParams<CmdCtxTypesT::ProfileParamsKey>>, CmdCtxTypesT::AppError, > { let profile_to_profile_params = futures::stream::iter( profile_dirs .iter() .map(Result::<_, peace_rt_model_core::Error>::Ok), ) .and_then(|(profile, profile_dir)| { let profile_params_provided = profile_to_profile_params_provided .remove(profile) .unwrap_or_default(); async move { let profile_params_file = ProfileParamsFile::from(profile_dir); let profile_params = CmdCtxBuilderSupport::profile_params_merge( storage, profile_params_type_reg_ref, profile_params_provided, &profile_params_file, ) .await?; Ok((profile.clone(), profile_params)) } }) .try_collect::<BTreeMap<Profile, ProfileParams<CmdCtxTypesT::ProfileParamsKey>>>() .await?; Ok(profile_to_profile_params) } pub(crate) async fn flow_params_deserialize( flow_dirs: &BTreeMap<Profile, FlowDir>, mut profile_to_flow_params_provided: BTreeMap< Profile, FlowParamsOpt<CmdCtxTypesT::FlowParamsKey>, >, storage: &peace_rt_model::Storage, flow_params_type_reg_ref: &TypeReg<CmdCtxTypesT::FlowParamsKey>, ) -> Result<BTreeMap<Profile, FlowParams<CmdCtxTypesT::FlowParamsKey>>, CmdCtxTypesT::AppError> { let profile_to_flow_params = futures::stream::iter( flow_dirs .iter() .map(Result::<_, peace_rt_model_core::Error>::Ok), ) .and_then(|(profile, flow_dir)| { let flow_params_provided = profile_to_flow_params_provided .remove(profile) .unwrap_or_default(); async move { let flow_params_file = FlowParamsFile::from(flow_dir); let flow_params = CmdCtxBuilderSupport::flow_params_merge( storage, flow_params_type_reg_ref, flow_params_provided, &flow_params_file, ) .await?; Ok((profile.clone(), flow_params)) } }) .try_collect::<BTreeMap<Profile, FlowParams<CmdCtxTypesT::FlowParamsKey>>>() .await?; Ok(profile_to_flow_params) } #[cfg(not(target_arch = "wasm32"))] pub(crate) async fn profiles_from_peace_app_dir( peace_app_dir: &PeaceAppDir, profile_filter_fn: Option<&ProfileFilterFn>, ) -> Result<Vec<Profile>, peace_rt_model_core::Error> { use std::{ffi::OsStr, str::FromStr}; let mut profiles = Vec::new(); let mut peace_app_read_dir = tokio::fs::read_dir(peace_app_dir).await.map_err( #[cfg_attr(coverage_nightly, coverage(off))] |error| { peace_rt_model_core::Error::Native(peace_rt_model::NativeError::PeaceAppDirRead { peace_app_dir: peace_app_dir.to_path_buf(), error, }) }, )?; while let Some(entry) = peace_app_read_dir.next_entry().await.map_err( #[cfg_attr(coverage_nightly, coverage(off))] |error| { peace_rt_model_core::Error::Native( peace_rt_model::NativeError::PeaceAppDirEntryRead { peace_app_dir: peace_app_dir.to_path_buf(), error, }, ) }, )? { let file_type = entry.file_type().await.map_err( #[cfg_attr(coverage_nightly, coverage(off))] |error| { peace_rt_model_core::Error::Native( peace_rt_model::NativeError::PeaceAppDirEntryFileTypeRead { path: entry.path(), error, }, ) }, )?; if file_type.is_dir() { let entry_path = entry.path(); if let Some(dir_name) = entry_path.file_name().and_then(OsStr::to_str) { // Assume this is a profile directory let profile = peace_profile_model::Profile::from_str(dir_name).map_err(|error| { peace_rt_model_core::Error::Native( peace_rt_model::NativeError::ProfileDirInvalidName { dir_name: dir_name.to_string(), path: entry_path.to_path_buf(), error, }, ) })?; if let Some(profile_filter_fn) = profile_filter_fn { if !profile_filter_fn.call(&profile) { // Exclude any profiles that do not pass the filter continue; } } profiles.push(profile) } // Assume non-UTF8 file names are not profile directories } } // Ensure profiles are in a consistent, sensible order. profiles.sort(); Ok(profiles) } #[cfg(target_arch = "wasm32")] pub(crate) async fn profiles_from_peace_app_dir( _peace_app_dir: &PeaceAppDir, _profile_filter_fn: Option<&ProfileFilterFn>, ) -> Result<Vec<Profile>, peace_rt_model_core::Error> { let profiles = Vec::new(); // TODO: Not supported yet -- needs a `Storage` abstraction over both native an // web assembly. Ok(profiles) } /// Serializes profile params to storage. pub(crate) async fn profile_params_serialize( profile_to_profile_params: &BTreeMap< Profile, ProfileParams<CmdCtxTypesT::ProfileParamsKey>, >, profile_dirs: &BTreeMap<Profile, ProfileDir>, storage: &peace_rt_model::Storage, ) -> Result<(), CmdCtxTypesT::AppError> { futures::stream::iter( profile_to_profile_params .iter() .map(Result::<_, peace_rt_model_core::Error>::Ok), ) .try_for_each(|(profile, profile_params)| { let profile_dir = profile_dirs.get(profile).unwrap_or_else( #[cfg_attr(coverage_nightly, coverage(off))] || { panic!( "`profile_dir` for `{profile}` should exist as it is inserted by \ `CmdCtxBuilderSupportMulti::profile_and_history_dirs_read`." ) }, ); let profile_params_file = ProfileParamsFile::from(profile_dir); async move { CmdCtxBuilderSupport::profile_params_serialize( profile_params, storage, &profile_params_file, ) .await?; Ok(()) } }) .await?; Ok(()) } /// Serializes flow params to storage. pub(crate) async fn flow_params_serialize( profile_to_flow_params: &BTreeMap<Profile, FlowParams<CmdCtxTypesT::FlowParamsKey>>, flow_dirs: &BTreeMap<Profile, peace_resource_rt::paths::FlowDir>, storage: &peace_rt_model::Storage, ) -> Result<(), CmdCtxTypesT::AppError> { futures::stream::iter( profile_to_flow_params .iter() .map(Result::<_, peace_rt_model_core::Error>::Ok), ) .try_for_each(|(profile, flow_params)| { let flow_dir = flow_dirs.get(profile).unwrap_or_else( #[cfg_attr(coverage_nightly, coverage(off))] || { panic!( "`flow_dir` for `{profile}` should exist as it is inserted by \ `CmdCtxBuilderSupportMulti::flow_dirs_read`." ) }, ); let flow_params_file = FlowParamsFile::from(flow_dir); async move { CmdCtxBuilderSupport::flow_params_serialize( flow_params, storage, &flow_params_file, ) .await?; Ok(()) } }) .await?; Ok(()) } /// Reads `StateCurrent` for each profile. pub(crate) async fn states_current_read( flow_dirs: &BTreeMap<Profile, FlowDir>, flow_id: &FlowId, storage: &peace_rt_model::Storage, states_type_reg_ref: &StatesTypeReg, ) -> Result<BTreeMap<Profile, Option<States<CurrentStored>>>, CmdCtxTypesT::AppError> { let profile_to_states_current_stored = futures::stream::iter(flow_dirs.iter().map(Result::<_, peace_rt_model::Error>::Ok)) .and_then(|(profile, flow_dir)| async move { let states_current_file = StatesCurrentFile::from(flow_dir); let states_current_stored = StatesSerializer::<peace_rt_model::Error>::deserialize_stored_opt( flow_id, storage, states_type_reg_ref, &states_current_file, ) .await?; Ok((profile.clone(), states_current_stored)) }) .try_collect::<BTreeMap<Profile, Option<StatesCurrentStored>>>() .await?; Ok(profile_to_states_current_stored) } /// Deserializes previously stored params specs, merges them with the /// provided params specs, and stores the merged values. pub(crate) async fn params_specs_load_merge_and_store( flow_dirs: &BTreeMap<Profile, FlowDir>, profile_to_params_specs_provided: BTreeMap<Profile, ParamsSpecs>, flow: &Flow<CmdCtxTypesT::AppError>, storage: &peace_rt_model::Storage, params_specs_type_reg_ref: &peace_rt_model::ParamsSpecsTypeReg, app_name: &peace_cfg::AppName, ) -> Result<BTreeMap<Profile, ParamsSpecs>, CmdCtxTypesT::AppError> { let flow_id = flow.flow_id(); let profile_to_params_specs = futures::stream::iter( flow_dirs .iter() .map(Result::<_, peace_rt_model_core::Error>::Ok), ) .and_then(|(profile, flow_dir)| { let params_specs_provided = profile_to_params_specs_provided.get(profile).cloned(); async move { let params_specs_file = ParamsSpecsFile::from(flow_dir); let params_specs_stored = ParamsSpecsSerializer::<peace_rt_model_core::Error>::deserialize_opt( profile, flow_id, storage, params_specs_type_reg_ref, &params_specs_file, ) .await?; // For mapping fns, we still need the developer to provide the params spec // so that multi-profile diffs can be done. let profile = profile.clone(); let params_specs = match (params_specs_stored, params_specs_provided) { (None, None) => { return Err(peace_rt_model_core::Error::ItemParamsSpecsFileNotFound { app_name: app_name.clone(), profile, flow_id: flow_id.clone(), }); } (None, Some(params_specs_provided)) => params_specs_provided, (Some(params_specs_stored), None) => params_specs_stored, (Some(params_specs_stored), Some(params_specs_provided)) => { CmdCtxBuilderSupport::params_specs_merge( flow, params_specs_provided, Some(params_specs_stored), )? } }; // Serialize params specs back to disk. CmdCtxBuilderSupport::params_specs_serialize( &params_specs, storage, &params_specs_file, ) .await?; Ok((profile, params_specs)) } }) .try_collect::<BTreeMap<Profile, ParamsSpecs>>() .await?; Ok(profile_to_params_specs) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/lib.rs
crate/resource_rt/src/lib.rs
//! Runtime resources for the peace automation framework. //! //! This crate contains resources necessary for the peace framework to work, and //! are likely to be common use for all applications. // Re-exports pub use resman::*; pub use type_reg; pub use crate::{item_rt_id::ItemRtId, resources::Resources}; pub mod internal; pub mod paths; pub mod resources; pub mod states; mod item_rt_id;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/internal.rs
crate/resource_rt/src/internal.rs
//! Data types used by the framework, not part of API. //! //! Since this is not API, it is not intended to be used (or useful outside the //! framework). There may be breakage between releases. pub use self::{ flow_params_file::FlowParamsFile, profile_params_file::ProfileParamsFile, state_diffs_mut::StateDiffsMut, states_mut::StatesMut, workspace_dirs::WorkspaceDirs, workspace_params_file::WorkspaceParamsFile, }; mod flow_params_file; mod profile_params_file; mod state_diffs_mut; mod states_mut; mod workspace_dirs; mod workspace_params_file;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/resources.rs
crate/resource_rt/src/resources.rs
use std::{ marker::PhantomData, ops::{Deref, DerefMut}, }; use crate::resources::ts::{Empty, SetUp}; pub mod ts; /// Runtime borrow-checked typemap of data available to the command context. /// [`resman::Resources`] newtype. /// /// This augments the any-map functionality of [`resman::Resources`] with type /// state, so that it is impossible for developers to pass `Resources` to /// functions that require particular data to have been inserted beforehand. /// /// For example, `Resources` must be `setup` before any `TryFnSpec`, /// `ApplyFns`, or `CleanOpSpec` may execute with it. /// /// # Type Parameters /// /// * `TS`: The type state of the `Resources` map. /// /// [`ItemId`]: peace_item_model::ItemId #[derive(Debug)] pub struct Resources<TS> { inner: resman::Resources, marker: PhantomData<TS>, } impl Resources<Empty> { /// Returns a new `Resources`. pub fn new() -> Self { Self { inner: resman::Resources::new(), marker: PhantomData, } } } impl<TS> Resources<TS> { /// Returns the inner [`resman::Resources`]. pub fn into_inner(self) -> resman::Resources { self.inner } } impl Default for Resources<Empty> { fn default() -> Self { Self::new() } } impl<TS> Deref for Resources<TS> { type Target = resman::Resources; fn deref(&self) -> &Self::Target { &self.inner } } impl<TS> DerefMut for Resources<TS> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } } // For `ItemGraph` after resources have been set up. impl From<Resources<Empty>> for Resources<SetUp> { fn from(resources: Resources<Empty>) -> Self { Self { inner: resources.into_inner(), marker: PhantomData, } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/paths.rs
crate/resource_rt/src/paths.rs
//! Types for well-known directories. //! //! # Design //! //! The designed structure of directories and their contents is as follows: //! //! ```bash //! WorkspaceDir //! |- PeaceDir //! |- ProfileDir # "profile_name", multiple //! |- HistoryDir //! | |- CmdExecution0 //! | |- .. //! | |- CmdExecutionN //! | //! |- ProfileParams //! | //! |- FlowDir # "flow_name", multiple //! |- StatesMeta //! |- StatesCurrent //! |- StatesGoal //! ``` //! //! Concrete folder structure example: //! //! ```bash //! workspace //! |- .peace //! |- profile1 / main / default //! | |- .history //! | | |- 00000000_2022-08-21T20_48_02_init.yaml //! | | |- 00000001_2022-08-21T20_48_07_dev_env_discover.yaml //! | | |- 00000002_2022-08-21T20_50_32_dev_env_deploy.yaml # dry //! | | |- 00000003_2022-08-21T20_50_43_dev_env_deploy.yaml //! | | |- 00000004_2022-08-22T08_16_09_dev_env_clean.yaml # dry //! | | |- 00000005_2022-08-22T08_16_29_dev_env_clean.yaml //! | | |- 00000006_2022-08-23T13_02_14_artifact_discover.yaml //! | | |- 00000007_2022-08-23T13_07_31_artifact_publish.yaml //! | | //! | |- .meta.yaml # Store the last discovered time so we can inform the user. //! | | # Should time be stored per item, or per invocation? //! | | //! | |- dev_env # flow name //! | | |- states_goal.yaml //! | | |- states_current.yaml //! | | //! | |- artifact //! | | |- states_goal.yaml //! | | |- states_current.yaml //! | | //! | |- profile_params.yaml # Parameters used to initialize this profile //! | # We write to this so that each time the user re-`init`s, //! | # if they version control it, they can rediscover the //! | # states from previous inits, and clean them up. //! | //! |- production //! | |- .history //! | | |- 00000000_2022-08-21T20_48_02_init.yaml //! | | |- 00000001_2022-08-21T20_48_07_discover.yaml //! | | //! | |- customer_one //! | | |- flow_params.yaml //! | | |- states_goal.yaml //! | | |- states_current.yaml //! | | //! | |- .meta.yaml //! | |- profile_params.yaml //! | //! |- workspace_params.yaml //! ``` pub use self::{ flow_dir::FlowDir, params_specs_file::ParamsSpecsFile, peace_app_dir::PeaceAppDir, peace_dir::PeaceDir, profile_dir::ProfileDir, profile_history_dir::ProfileHistoryDir, states_current_file::StatesCurrentFile, states_goal_file::StatesGoalFile, workspace_dir::WorkspaceDir, }; mod flow_dir; mod params_specs_file; mod peace_app_dir; mod peace_dir; mod profile_dir; mod profile_history_dir; mod states_current_file; mod states_goal_file; mod workspace_dir; /// Common impl logic for `PathBuf` newtypes. /// /// This does not include declaring the type, as it may prevent IDEs from /// discovering the type declaration, making those types harder to discover. macro_rules! pathbuf_newtype { ($ty_name:ident) => { impl $ty_name { #[doc = concat!("Returns a new [`", stringify!($ty_name), "`].")] pub fn new(path: std::path::PathBuf) -> Self { Self(path) } /// Returns the inner [`PathBuf`]. /// /// [`PathBuf`]: std::path::PathBuf pub fn into_inner(self) -> std::path::PathBuf { self.0 } } impl From<std::path::PathBuf> for $ty_name { fn from(path_buf: std::path::PathBuf) -> Self { Self(path_buf) } } impl AsRef<std::ffi::OsStr> for $ty_name { fn as_ref(&self) -> &std::ffi::OsStr { self.0.as_ref() } } impl AsRef<std::path::Path> for $ty_name { fn as_ref(&self) -> &std::path::Path { &self.0 } } impl std::ops::Deref for $ty_name { type Target = std::path::Path; fn deref(&self) -> &Self::Target { &self.0 } } }; } pub(crate) use pathbuf_newtype;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/item_rt_id.rs
crate/resource_rt/src/item_rt_id.rs
use std::ops::{Deref, DerefMut}; use peace_data::fn_graph::FnId; /// Runtime identifier for an [`Item`]. [`FnId`] newtype. /// /// This is a cheap identifier to copy around, instead of cloning /// [`ItemId`]. /// /// [`ItemId`]: peace_item_model::ItemId #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ItemRtId(FnId); impl ItemRtId { /// Returns a new `ItemRtId`. pub fn new(fn_id: FnId) -> Self { Self(fn_id) } /// Returns the inner [`FnId`]. pub fn into_inner(self) -> FnId { self.0 } } impl Deref for ItemRtId { type Target = FnId; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for ItemRtId { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<usize> for ItemRtId { fn from(index: usize) -> Self { Self(FnId::new(index)) } } impl From<FnId> for ItemRtId { fn from(fn_id: FnId) -> Self { Self(fn_id) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/states.rs
crate/resource_rt/src/states.rs
//! Resources that track current and goal states, and state diffs. pub use self::{ state_diffs::StateDiffs, states_clean::StatesClean, states_cleaned::StatesCleaned, states_cleaned_dry::StatesCleanedDry, states_current::StatesCurrent, states_current_stored::StatesCurrentStored, states_ensured::StatesEnsured, states_ensured_dry::StatesEnsuredDry, states_goal::StatesGoal, states_goal_stored::StatesGoalStored, states_previous::StatesPrevious, states_serde::StatesSerde, }; pub mod ts; use std::{marker::PhantomData, ops::Deref}; use peace_fmt::{Presentable, Presenter}; use peace_item_model::ItemId; use serde::Serialize; use type_reg::untagged::{BoxDtDisplay, TypeMap}; use crate::internal::StatesMut; mod state_diffs; mod states_clean; mod states_cleaned; mod states_cleaned_dry; mod states_current; mod states_current_stored; mod states_ensured; mod states_ensured_dry; mod states_goal; mod states_goal_stored; mod states_previous; mod states_serde; /// Map of `State`s for all `Item`s. `TypeMap<ItemId, Item::State>` newtype. /// /// # Type Parameters /// /// * `TS`: Type state to distinguish the purpose of the `States` map. /// /// # Serialization /// /// [`StatesSerde`] is used for serialization and deserialization. /// /// # Design /// /// When states are serialized, we want there to be an entry for each item. /// /// 1. This means the `States` map should contain an entry for each item, /// regardless of whether a `State` is recorded for that item. /// /// 2. Inserting an `Option<_>` layer around the `Item::State` turns the map /// into a `Map<ItemId, Option<Item::State>>`. /// /// 3. Calling `states.get(item_id)` returns `Option<Option<Item::State>>`, the /// outer layer for whether the item had an entry, and the inner layer for /// whether there was any `State` recorded. /// /// 4. If we can guarantee the item ID is valid -- an ID of an item in the flow /// -- we could remove that outer `Option` layer. Currently we cannot make /// this guarantee, as: /// /// - item IDs are constructed by developer code, without any constraints /// for which items are inserted into the Flow, and which are inserted /// into `States` -- although insertion into `States` is largely managed /// by `peace`. /// /// - `States` may contain different items across different versions of an /// automation tool, so it is possible (and valid) to: /// /// + Deserialize `States` that contain states for `Item`s that are no /// longer in the flow. /// + Deserialize `States` that do not contain states for `Item`s that /// are newly added to the flow. /// + Have a combination of the above for renamed items. /// /// 5. For clarity of each of these `Option` layers, we can wrap them in a /// newtype. /// /// 6. For code cleanliness, this additional layer requires calling /// [`flatten()`] on `states.get(item_id)`. /// /// 7. We *could* introduce a different type during serialization that handles /// this additional layer, to remove the additional `flatten()`. How do we /// handle flow upgrades smoothly? /// /// - **Development:** Compile time API support with runtime errors may be /// sufficient. /// - **User:** Developers *may* require users to decide how to migrate /// data. This use case hopefully is less common. /// /// ## `StatesSerde` Separate Type /// /// Newtype for `Map<ItemId, Option<Item::State>>`. /// /// ### Item Additions /// /// * Flow contains the `Item`. /// * Stored state doesn't contain an entry for the item. /// * Deserialized `StatesSerde` should contain `(item_id!("new"), None)` -- may /// need custom deserialization code. /// /// ### Item Removals /// /// * Flow does not contain the `Item`. /// * Stored state contains an entry for the item, but cannot be deserialized. /// * Deserialized `StatesSerde` would not contain any entry. /// * Deserialization will return the unable to be deserialized item state in /// the return value. Meaning, `StatesSerde` will contain it in a separate /// "removed" field. /// /// After deserialization, `StatesSerde` is explicitly mapped into `States`, and /// we can inform the developer and/or user of the removed items if it is /// useful. /// /// ## `States` With Optional Item State /// /// Developers will frequently use `states.get(item_id).flatten()` to access /// state. /// /// Deserialization has all the same properties as the `StatesSerde` separate /// type. However, the entries that fail to be deserialized are retained in the /// `States` type (or are lost, if we deliberately ignore entries that fail to /// be deserialized). /// /// Should `Flow`s be versionable, and we migrate them to the latest version as /// encountered? If so, then: /// /// * `peace` should store the version of the flow in the stored states files /// * items that have ever been used in flows must be shipped in the automation /// software, in order to support safe upgrades. /// /// How would this work? /// /// * Newly added items just work. /// * Removed items need to be removed: /// - Successors may need their parameters specified from new predecessors. /// - If removing multiple items, we need to clean them in reverse. /// * Renamed items may need to be re-applied, or potentially cleaned and /// re-ensured. This doesn't support data retention if a predecessor needs to /// be cleaned, forcing successors to be cleaned, and reensured after. Unless, /// `peace` supports backup and restore. /// /// [`flatten()`]: std::option::Option::flatten #[derive(Debug, Serialize)] #[serde(transparent)] // Needed to serialize as a map instead of a list. pub struct States<TS>( pub(crate) TypeMap<ItemId, BoxDtDisplay>, pub(crate) PhantomData<TS>, ); impl<TS> States<TS> { /// Returns a new `States` map. pub fn new() -> Self { Self::default() } /// Creates an empty `States` map with the specified capacity. /// /// The `States` will be able to hold at least capacity elements /// without reallocating. If capacity is 0, the map will not allocate. pub fn with_capacity(capacity: usize) -> Self { Self(TypeMap::with_capacity_typed(capacity), PhantomData) } /// Returns the inner map. pub fn into_inner(self) -> TypeMap<ItemId, BoxDtDisplay> { self.0 } } impl<TS> Clone for States<TS> { fn clone(&self) -> Self { let mut clone = Self(TypeMap::with_capacity_typed(self.0.len()), PhantomData); clone.0.extend( self.0 .iter() .map(|(item_id, state)| (item_id.clone(), state.clone())), ); clone } } impl<TS> Default for States<TS> { fn default() -> Self { Self(TypeMap::default(), PhantomData) } } impl<TS> Deref for States<TS> { type Target = TypeMap<ItemId, BoxDtDisplay>; fn deref(&self) -> &Self::Target { &self.0 } } impl<TS> From<TypeMap<ItemId, BoxDtDisplay>> for States<TS> { fn from(type_map: TypeMap<ItemId, BoxDtDisplay>) -> Self { Self(type_map, PhantomData) } } impl<TS> From<StatesMut<TS>> for States<TS> { fn from(states_mut: StatesMut<TS>) -> Self { Self(states_mut.into_inner(), PhantomData) } } #[peace_fmt::async_trait(?Send)] impl<TS> Presentable for States<TS> { async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> where PR: Presenter<'output>, { presenter .list_numbered_with(self.iter(), |(item_id, state)| { (item_id, format!(": {state}")) }) .await } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/internal/profile_params_file.rs
crate/resource_rt/src/internal/profile_params_file.rs
use std::{fmt, path::PathBuf}; use crate::paths::ProfileDir; /// Path to the file that stores the profile initialization parameters. /// /// Typically `$workspace_dir/.peace/$app/$profile/profile_params.yaml`. /// /// See `ProfileParamsFile::from<&ProfileDir>` if you want to construct a /// `ProfileParamsFile` with the conventional `$profile_dir/profile_params.yaml` /// path. #[derive(Clone, Debug, PartialEq, Eq)] pub struct ProfileParamsFile(PathBuf); crate::paths::pathbuf_newtype!(ProfileParamsFile); impl ProfileParamsFile { /// File name of the initialization parameters file. pub const NAME: &'static str = "profile_params.yaml"; } impl From<&ProfileDir> for ProfileParamsFile { fn from(profile_dir: &ProfileDir) -> Self { let path = profile_dir.join(Self::NAME); Self(path) } } impl fmt::Display for ProfileParamsFile { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0.display()) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/internal/workspace_params_file.rs
crate/resource_rt/src/internal/workspace_params_file.rs
use std::{fmt, path::PathBuf}; use crate::paths::PeaceAppDir; /// Path to the file that stores the workspace initialization parameters. /// /// Typically `$workspace_dir/.peace/$app/workspace_params.yaml`. /// /// See `WorkspaceParamsFile::from<&PeaceAppDir>` if you want to construct a /// `WorkspaceParamsFile` with the conventional /// `$peace_dir/$app/workspace_params.yaml` path. #[derive(Clone, Debug, PartialEq, Eq)] pub struct WorkspaceParamsFile(PathBuf); crate::paths::pathbuf_newtype!(WorkspaceParamsFile); impl WorkspaceParamsFile { /// File name of the workspace parameters file. pub const NAME: &'static str = "workspace_params.yaml"; } impl From<&PeaceAppDir> for WorkspaceParamsFile { fn from(flow_dir: &PeaceAppDir) -> Self { let path = flow_dir.join(Self::NAME); Self(path) } } impl fmt::Display for WorkspaceParamsFile { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0.display()) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/internal/states_mut.rs
crate/resource_rt/src/internal/states_mut.rs
use std::{ marker::PhantomData, ops::{Deref, DerefMut}, }; use peace_item_model::ItemId; use serde::Serialize; use type_reg::untagged::{BoxDtDisplay, TypeMap}; /// `State`s for all `Item`s. `TypeMap<ItemId, BoxDtDisplay>` newtype. /// /// # Implementors /// /// To reference State from another `Item`, in `Item::Data`, you should /// reference [`Current<T>`] or [`Goal<T>`], where `T` is the predecessor /// item's state. /// /// # Type Parameters /// /// * `TS`: Type state to distinguish the purpose of the `States` map. /// /// [`Current<T>`]: peace_data::marker::Current /// [`Data`]: peace_data::Data /// [`Goal<T>`]: peace_data::marker::Goal /// [`Resources`]: crate::Resources /// [`StatesCurrent`]: crate::StatesCurrent /// [`StatesRw`]: crate::StatesRw #[derive(Debug, Serialize)] pub struct StatesMut<TS>(TypeMap<ItemId, BoxDtDisplay>, PhantomData<TS>); impl<TS> StatesMut<TS> { /// Returns a new `StatesMut` map. pub fn new() -> Self { Self::default() } /// Creates an empty `StatesMut` map with the specified capacity. /// /// The `StatesMut` will be able to hold at least capacity elements /// without reallocating. If capacity is 0, the map will not allocate. pub fn with_capacity(capacity: usize) -> Self { Self(TypeMap::with_capacity_typed(capacity), PhantomData) } /// Returns the inner map. pub fn into_inner(self) -> TypeMap<ItemId, BoxDtDisplay> { self.0 } } impl<TS> Default for StatesMut<TS> { fn default() -> Self { Self(TypeMap::default(), PhantomData) } } impl<TS> Deref for StatesMut<TS> { type Target = TypeMap<ItemId, BoxDtDisplay>; fn deref(&self) -> &Self::Target { &self.0 } } impl<TS> DerefMut for StatesMut<TS> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<TS> From<TypeMap<ItemId, BoxDtDisplay>> for StatesMut<TS> { fn from(type_map: TypeMap<ItemId, BoxDtDisplay>) -> Self { Self(type_map, PhantomData) } } impl<TS> Extend<(ItemId, BoxDtDisplay)> for StatesMut<TS> { fn extend<T: IntoIterator<Item = (ItemId, BoxDtDisplay)>>(&mut self, iter: T) { iter.into_iter().for_each(|(item_id, state)| { self.insert_raw(item_id, state); }); } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/internal/flow_params_file.rs
crate/resource_rt/src/internal/flow_params_file.rs
use std::{fmt, path::PathBuf}; use crate::paths::FlowDir; /// Path to the file that stores the flow initialization parameters. /// /// Typically `$workspace_dir/.peace/$app/$profile/$flow_id/flow_params.yaml`. /// /// See `FlowParamsFile::from<&FlowDir>` if you want to construct a /// `FlowParamsFile` with the conventional `$flow_dir/flow_params.yaml` /// path. #[derive(Clone, Debug, PartialEq, Eq)] pub struct FlowParamsFile(PathBuf); crate::paths::pathbuf_newtype!(FlowParamsFile); impl FlowParamsFile { /// File name of the initialization parameters file. pub const NAME: &'static str = "flow_params.yaml"; } impl From<&FlowDir> for FlowParamsFile { fn from(flow_dir: &FlowDir) -> Self { let path = flow_dir.join(Self::NAME); Self(path) } } impl fmt::Display for FlowParamsFile { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0.display()) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/internal/workspace_dirs.rs
crate/resource_rt/src/internal/workspace_dirs.rs
use crate::paths::{PeaceAppDir, PeaceDir, WorkspaceDir}; /// Directories used during `peace` execution. /// /// This type itself is not inserted into `Resources`, but each of the member /// directories are individually inserted. This is created by /// `WorkspaceDirsBuilder` from either the `peace_rt_model` or /// `peace_rt_model_web` crates. #[derive(Clone, Debug, PartialEq, Eq)] pub struct WorkspaceDirs { /// Base directory of the workspace. workspace_dir: WorkspaceDir, /// Peace directory, peace_dir: PeaceDir, /// Peace app directory, peace_app_dir: PeaceAppDir, } impl WorkspaceDirs { /// Returns new `WorkspaceDirs`. pub fn new( workspace_dir: WorkspaceDir, peace_dir: PeaceDir, peace_app_dir: PeaceAppDir, ) -> Self { Self { workspace_dir, peace_dir, peace_app_dir, } } /// Returns the individual workspace directories. pub fn into_inner(self) -> (WorkspaceDir, PeaceDir, PeaceAppDir) { let Self { workspace_dir, peace_dir, peace_app_dir, } = self; (workspace_dir, peace_dir, peace_app_dir) } /// Returns a reference to the workspace directory. pub fn workspace_dir(&self) -> &WorkspaceDir { &self.workspace_dir } /// Returns a reference to the `.peace` directory. pub fn peace_dir(&self) -> &PeaceDir { &self.peace_dir } /// Returns a reference to the `.peace/$app` directory. pub fn peace_app_dir(&self) -> &PeaceAppDir { &self.peace_app_dir } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/internal/state_diffs_mut.rs
crate/resource_rt/src/internal/state_diffs_mut.rs
use std::ops::{Deref, DerefMut}; use peace_item_model::ItemId; use serde::Serialize; use type_reg::untagged::{BoxDtDisplay, TypeMap}; /// Diffs of `State`s for each `Item`s. `TypeMap<ItemId, BoxDtDisplay>` /// newtype. /// /// # Implementors /// /// [`StateDiffsMut`] is a framework-only type and is never inserted into /// [`Resources`]. If you need to inspect diffs, you may borrow [`StateDiffs`]. /// /// [`StateDiffs`]: crate::StateDiffs /// [`Resources`]: crate::Resources #[derive(Debug, Default, Serialize)] pub struct StateDiffsMut(TypeMap<ItemId, BoxDtDisplay>); impl StateDiffsMut { /// Returns a new `StateDiffsMut` map. pub fn new() -> Self { Self::default() } /// Creates an empty `StateDiffsMut` map with the specified capacity. /// /// The `StateDiffsMut` will be able to hold at least capacity elements /// without reallocating. If capacity is 0, the map will not allocate. pub fn with_capacity(capacity: usize) -> Self { Self(TypeMap::with_capacity_typed(capacity)) } /// Returns the inner map. pub fn into_inner(self) -> TypeMap<ItemId, BoxDtDisplay> { self.0 } } impl Deref for StateDiffsMut { type Target = TypeMap<ItemId, BoxDtDisplay>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for StateDiffsMut { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<TypeMap<ItemId, BoxDtDisplay>> for StateDiffsMut { fn from(type_map: TypeMap<ItemId, BoxDtDisplay>) -> Self { Self(type_map) } } impl Extend<(ItemId, BoxDtDisplay)> for StateDiffsMut { fn extend<T: IntoIterator<Item = (ItemId, BoxDtDisplay)>>(&mut self, iter: T) { iter.into_iter().for_each(|(item_id, state_diff)| { self.insert_raw(item_id, state_diff); }); } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/paths/profile_history_dir.rs
crate/resource_rt/src/paths/profile_history_dir.rs
use std::path::PathBuf; use crate::paths::ProfileDir; /// Directory to store all data produced by the current profile's execution. /// /// Typically `$workspace_dir/.peace/$app/$profile/.history`. /// /// This directory is intended to contain significant command execution /// summaries. Currently it is not written to yet. /// /// See `ProfileHistoryDir::from<&ProfileDir>` if you want to construct a /// `ProfileHistoryDir` with the conventional `$profile_dir/.history` path. #[derive(Clone, Debug, PartialEq, Eq)] pub struct ProfileHistoryDir(PathBuf); crate::paths::pathbuf_newtype!(ProfileHistoryDir); impl From<&ProfileDir> for ProfileHistoryDir { fn from(profile_dir: &ProfileDir) -> Self { let path = profile_dir.join(".history"); Self(path) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/paths/states_current_file.rs
crate/resource_rt/src/paths/states_current_file.rs
use std::path::PathBuf; use crate::paths::FlowDir; /// Path to the file that stores items' states. /// /// Typically `$workspace_dir/.peace/$profile/$flow_id/states_current.yaml`. /// /// See `StatesCurrentFile::from<&FlowDir>` if you want to construct a /// `StatesCurrentFile` with the conventional `$flow_dir/states_current.yaml` /// path. #[derive(Clone, Debug, PartialEq, Eq)] pub struct StatesCurrentFile(PathBuf); crate::paths::pathbuf_newtype!(StatesCurrentFile); impl StatesCurrentFile { /// File name of the states file. pub const NAME: &'static str = "states_current.yaml"; } impl From<&FlowDir> for StatesCurrentFile { fn from(flow_dir: &FlowDir) -> Self { let path = flow_dir.join(Self::NAME); Self(path) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/paths/workspace_dir.rs
crate/resource_rt/src/paths/workspace_dir.rs
use std::path::PathBuf; /// Base directory of the workspace. /// /// Given a workspace lives in `workspace_dir`, it is natural for users to /// execute a `peace` tool in any sub directory of `workspace_dir`, in which /// case execution should be consistent with invocations in `workspace_dir`. #[derive(Clone, Debug, PartialEq, Eq)] pub struct WorkspaceDir(PathBuf); crate::paths::pathbuf_newtype!(WorkspaceDir);
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/paths/peace_dir.rs
crate/resource_rt/src/paths/peace_dir.rs
use std::path::PathBuf; use crate::paths::WorkspaceDir; /// Directory to store all data produced by `peace` tools' executions. /// /// Typically `$workspace_dir/.peace`. /// /// See `PeaceDir::from<&WorkspaceDir>` if you want to construct a `PeaceDir` /// with the conventional `$workspace_dir/.peace` path. #[derive(Clone, Debug, PartialEq, Eq)] pub struct PeaceDir(PathBuf); crate::paths::pathbuf_newtype!(PeaceDir); impl PeaceDir { /// Default name of the `.peace` directory. pub const NAME: &'static str = ".peace"; } impl From<&WorkspaceDir> for PeaceDir { fn from(workspace_dir: &WorkspaceDir) -> Self { let path = workspace_dir.join(PeaceDir::NAME); Self(path) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/paths/params_specs_file.rs
crate/resource_rt/src/paths/params_specs_file.rs
use std::path::PathBuf; use crate::paths::FlowDir; /// Path to the file that stores items' states. /// /// Typically `$workspace_dir/.peace/$profile/$flow_id/params_specs.yaml`. /// /// See `ParamsSpecsFile::from<&FlowDir>` if you want to construct a /// `ParamsSpecsFile` with the conventional `$flow_dir/params_specs.yaml` /// path. #[derive(Clone, Debug, PartialEq, Eq)] pub struct ParamsSpecsFile(PathBuf); crate::paths::pathbuf_newtype!(ParamsSpecsFile); impl ParamsSpecsFile { /// File name of the states file. pub const NAME: &'static str = "params_specs.yaml"; } impl From<&FlowDir> for ParamsSpecsFile { fn from(flow_dir: &FlowDir) -> Self { let path = flow_dir.join(Self::NAME); Self(path) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/paths/peace_app_dir.rs
crate/resource_rt/src/paths/peace_app_dir.rs
use std::path::PathBuf; use peace_core::AppName; use crate::paths::PeaceDir; /// Directory to store all data produced by the current application's execution. /// /// Typically `$workspace_dir/.peace/$app`. /// /// This is the directory that contains all information produced and used during /// a `peace` tool invocation. This directory layer is created to accommodate /// different `peace` tools being run in the same workspace. /// /// # Implementors /// /// This type is constructed by the Peace framework when a Workspace's /// directories are created. #[derive(Clone, Debug, PartialEq, Eq)] pub struct PeaceAppDir(PathBuf); crate::paths::pathbuf_newtype!(PeaceAppDir); impl From<(&PeaceDir, &AppName)> for PeaceAppDir { fn from((peace_dir, app_name): (&PeaceDir, &AppName)) -> Self { let path = peace_dir.join(app_name.as_ref()); Self(path) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/paths/flow_dir.rs
crate/resource_rt/src/paths/flow_dir.rs
use std::path::PathBuf; use peace_flow_model::FlowId; use crate::paths::ProfileDir; /// Directory to store all data produced by the current flow's execution. /// /// Typically `$workspace_dir/.peace/$app/$profile/$flow_id`. /// /// This is the directory that contains the information produced and used during /// a `peace` tool invocation for a particular flow. /// /// See `FlowDir::from<(&ProfileDir, &FlowId)>` if you want to construct a /// `FlowDir` with the conventional `$profile_dir/$flow_id` path. #[derive(Clone, Debug, PartialEq, Eq)] pub struct FlowDir(PathBuf); crate::paths::pathbuf_newtype!(FlowDir); impl From<(&ProfileDir, &FlowId)> for FlowDir { fn from((peace_dir, flow_id): (&ProfileDir, &FlowId)) -> Self { let path = peace_dir.join(flow_id.as_ref()); Self(path) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/paths/profile_dir.rs
crate/resource_rt/src/paths/profile_dir.rs
use std::path::PathBuf; use peace_profile_model::Profile; use crate::paths::PeaceAppDir; /// Directory to store all data produced by the current profile's execution. /// /// Typically `$workspace_dir/.peace/$app/$profile`. /// /// This is the directory that contains all information produced and used during /// a `peace` tool invocation. Exceptions include authentication information /// stored in their respective directories on the file system, such as /// application credentials stored in `~/${app}/credentials`. /// /// See `ProfileDir::from<(&PeaceAppDir, &Profile)>` if you want to construct a /// `ProfileDir` with the conventional `$peace_dir/.peace/$app/$profile` path. #[derive(Clone, Debug, PartialEq, Eq)] pub struct ProfileDir(PathBuf); crate::paths::pathbuf_newtype!(ProfileDir); impl From<(&PeaceAppDir, &Profile)> for ProfileDir { fn from((peace_app_dir, profile): (&PeaceAppDir, &Profile)) -> Self { let path = peace_app_dir.join(profile.as_ref()); Self(path) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/paths/states_goal_file.rs
crate/resource_rt/src/paths/states_goal_file.rs
use std::path::PathBuf; use crate::paths::FlowDir; /// Path to the file that stores items' states. /// /// Typically `$workspace_dir/.peace/$profile/$flow_id/states_goal.yaml`. /// /// See `StatesGoalFile::from<&FlowDir>` if you want to construct a /// `StatesGoalFile` with the conventional `$flow_dir/states_goal.yaml` /// path. #[derive(Clone, Debug, PartialEq, Eq)] pub struct StatesGoalFile(PathBuf); crate::paths::pathbuf_newtype!(StatesGoalFile); impl StatesGoalFile { /// File name of the goal states file. pub const NAME: &'static str = "states_goal.yaml"; } impl From<&FlowDir> for StatesGoalFile { fn from(flow_dir: &FlowDir) -> Self { let path = flow_dir.join(Self::NAME); Self(path) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/resources/ts.rs
crate/resource_rt/src/resources/ts.rs
//! Type states for [`Resources`]. //! //! This allows compile time checking that [`Resources`] is in the correct state //! before a particular `TryFnSpec`, `ApplyFns`, or `CleanOpSpec` //! is executed with it. //! //! [`Resources`]: crate::Resources /// [`Resources`] is created but not setup. /// /// [`Resources`]: crate::Resources #[derive(Debug)] pub struct Empty; /// `Item::setup` has been run over [`Resources`]. #[derive(Debug)] pub struct SetUp;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/states/states_previous.rs
crate/resource_rt/src/states/states_previous.rs
use std::marker::PhantomData; use crate::states::{ts::Previous, States, StatesCurrent}; /// Previous `State`s for all `Item`s. /// /// This is present when an `ApplyCmd` (`EnsureCmd` or `CleanCmd`) is run, /// whereby the current states have changed to the newly ensured states. pub type StatesPrevious = States<Previous>; impl From<StatesCurrent> for StatesPrevious { fn from(states_current: StatesCurrent) -> Self { Self(states_current.into_inner(), PhantomData) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/states/states_ensured.rs
crate/resource_rt/src/states/states_ensured.rs
use std::marker::PhantomData; use crate::states::{ts::Ensured, States, StatesCurrent}; /// Ensured `State`s for all `Item`s. `TypeMap<ItemId>` newtype. /// /// These are the `State`s collected after `ApplyFns::exec` has been run. /// /// # Implementors /// /// You may reference [`StatesEnsured`] after `EnsureCmd::exec` has been run. /// /// [`Data`]: peace_data::Data pub type StatesEnsured = States<Ensured>; impl From<StatesCurrent> for StatesEnsured { fn from(states_current: StatesCurrent) -> Self { Self(states_current.into_inner(), PhantomData) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/states/states_goal.rs
crate/resource_rt/src/states/states_goal.rs
use std::marker::PhantomData; use crate::states::{ ts::{Goal, GoalStored}, States, }; /// Goal `State`s for all `Item`s. /// /// These are the states that each item would be in, if `Item::apply` were to be /// run with `state_goal` as the target state. /// /// # Implementors /// /// If an `Item`'s goal state discovery depends on the goal `State` of /// a previous `Item`, then you should insert the predecessor's goal /// state into [`Resources`], and reference that in the subsequent /// `TryFnSpec`'s [`Data`]: /// /// ```rust /// # use std::path::PathBuf; /// # /// # use peace_data::{Data, R}; /// # /// /// Predecessor `TryFnSpec::Data`. /// #[derive(Data, Debug)] /// pub struct AppUploadParams<'exec> { /// /// Path to the application directory. /// app_dir: W<'exec, PathBuf>, /// } /// /// /// Successor `TryFnSpec::Data`. /// #[derive(Data, Debug)] /// pub struct AppInstallParams<'exec> { /// /// Path to the application directory. /// app_dir: R<'exec, PathBuf>, /// /// Configuration to use. /// config: W<'exec, String>, /// } /// ``` /// /// You may reference [`StatesGoal`] in `ApplyFns::Data` for reading. It /// is not mutable as `StatesGoal` must remain unchanged so that all /// `Item`s operate over consistent data. /// /// [`Data`]: peace_data::Data /// [`Resources`]: crate::Resources pub type StatesGoal = States<Goal>; impl From<States<GoalStored>> for States<Goal> { fn from(states_goal_stored: States<GoalStored>) -> Self { let States(type_map, PhantomData) = states_goal_stored; Self(type_map, PhantomData) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/states/states_current_stored.rs
crate/resource_rt/src/states/states_current_stored.rs
use std::marker::PhantomData; use crate::states::{ ts::{Current, CurrentStored}, States, }; /// Stored current `State`s for all `Item`s. /// /// This is loaded into [`Resources`] at the beginning of any command execution, /// from the [`StatesCurrentFile`]. /// /// This is distinct from [`StatesCurrent`] to address the following use cases: /// /// * Discovering current state from what is recorded in the /// [`StatesCurrentFile`]. /// * Discovering current state and comparing it with previous state within the /// same execution. /// /// # Implementors /// /// If an `Item`'s state discovery depends on the `State` of a previous /// `Item`, then you should insert the predecessor's state into /// [`Resources`], and reference that in the subsequent `TryFnSpec`'s [`Data`]: /// /// ```rust /// # use std::path::PathBuf; /// # /// # use peace_data::{Data, R}; /// # /// /// Predecessor `TryFnSpec::Data`. /// #[derive(Data, Debug)] /// pub struct AppUploadParams<'exec> { /// /// Path to the application directory. /// app_dir: W<'exec, PathBuf>, /// } /// /// /// Successor `TryFnSpec::Data`. /// #[derive(Data, Debug)] /// pub struct AppInstallParams<'exec> { /// /// Path to the application directory. /// app_dir: R<'exec, PathBuf>, /// /// Configuration to use. /// config: W<'exec, String>, /// } /// ``` /// /// You may reference [`StatesCurrentStored`] in `ApplyFns::Data` for reading. /// It is not mutable as `StatesCurrentStored` must remain unchanged so that all /// `Item`s operate over consistent data. /// /// [`StatesCurrentFile`]: crate::paths::StatesCurrentFile /// [`Data`]: peace_data::Data /// [`Resources`]: crate::Resources pub type StatesCurrentStored = States<CurrentStored>; impl From<States<Current>> for States<CurrentStored> { fn from(states_current: States<Current>) -> Self { let States(type_map, PhantomData) = states_current; Self(type_map, PhantomData) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/states/ts.rs
crate/resource_rt/src/states/ts.rs
//! Type states for [`States`]. //! //! These distinguish between the purposes of each `States` map. //! //! [`States`]: crate::states::States use serde::{Deserialize, Serialize}; /// Clean / blank states of items. /// /// Not to be confused with [`Cleaned`]. #[derive(Debug, Deserialize, Serialize)] pub struct Clean; /// Stored current states of items. #[derive(Debug, Deserialize, Serialize)] pub struct CurrentStored; /// Current states of items. #[derive(Debug, Deserialize, Serialize)] pub struct Current; /// Stored goal states of items. #[derive(Debug, Deserialize, Serialize)] pub struct GoalStored; /// Goal states of items. #[derive(Debug, Deserialize, Serialize)] pub struct Goal; /// States of items after running the `EnsureCmd`. #[derive(Debug, Deserialize, Serialize)] pub struct Ensured; /// States of items after dry-running `EnsureCmd`. #[derive(Debug, Deserialize, Serialize)] pub struct EnsuredDry; /// States of items after running the `CleanCmd`. /// /// Not to be confused with [`Clean`]. #[derive(Debug, Deserialize, Serialize)] pub struct Cleaned; /// States of items after dry-running `CleanCmd`. #[derive(Debug, Deserialize, Serialize)] pub struct CleanedDry; /// Previous states of items. /// /// This is intended as a record of `States` before an `ApplyCmd` (`EnsureCmd` /// or `CleanCmd`) are run. #[derive(Debug, Deserialize, Serialize)] pub struct Previous;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/states/states_clean.rs
crate/resource_rt/src/states/states_clean.rs
use crate::states::{ts::Clean, States}; /// Clean `State`s for all `Item`s. /// /// These are the states that each item would be in, if `Item::apply` were to be /// run with `state_clean` as the target state. /// /// **Note:** Not to be confused with [`StatesCleaned`]. /// /// [`StatesCleaned`]: crate::states::StatesCleaned /// /// # Implementors /// /// You may reference [`StatesClean`] after `CleanCmd::exec` has been run, /// unless it is the `ExecutionOutcome`. pub type StatesClean = States<Clean>;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/states/states_serde.rs
crate/resource_rt/src/states/states_serde.rs
//! Resources that track current and goal states, and state diffs. use std::{fmt::Debug, ops::Deref}; use peace_item_model::ItemId; use serde::Serialize; use type_reg::{ common::UnknownEntriesSome, untagged::{BoxDtDisplay, TypeMapOpt}, }; /// Map of `State`s for all `Item`s. `TypeMapOpt<ItemId, Item::State>` /// newtype. /// /// Conceptually you can think of this as a `Map<ItemId, Option<Item::State>>`. /// /// This map should: /// /// * Always contain an entry for every item in the flow. /// * Contain an unknown entry for deserialized unknown items. /// /// This map can be initialized either through one of: /// /// * Deserialization. /// * `From<&ItemGraph<E>>`: All states are initialized to `None`. /// * [`FromIterator::<(ItemId, Option<BoxDtDisplay>)>::from_iter`]. /// /// [`FromIterator::<(ItemId, Option<BoxDtDisplay>)>::from_iter`]: std::iter::FromIterator #[derive(Debug, Serialize)] #[serde(transparent)] // Needed to serialize as a map instead of a list. pub struct StatesSerde<ValueT>(TypeMapOpt<ItemId, BoxDtDisplay, UnknownEntriesSome<ValueT>>) where ValueT: Clone + Debug + PartialEq + Eq; impl<ValueT> StatesSerde<ValueT> where ValueT: Clone + Debug + PartialEq + Eq, { /// Creates an empty `StatesSerde` map with the specified capacity. /// /// The `StatesSerde` will be able to hold at least capacity elements /// without reallocating. If capacity is 0, the map will not allocate. pub fn with_capacity(capacity: usize) -> Self { Self(TypeMapOpt::with_capacity_typed(capacity)) } /// Returns the inner map. pub fn into_inner(self) -> TypeMapOpt<ItemId, BoxDtDisplay, UnknownEntriesSome<ValueT>> { self.0 } } impl<ValueT> Clone for StatesSerde<ValueT> where ValueT: Clone + Debug + PartialEq + Eq, { fn clone(&self) -> Self { let mut clone = Self(TypeMapOpt::with_capacity_typed(self.0.len())); clone.0.extend( self.0 .iter() .map(|(item_id, state)| (item_id.clone(), state.clone())), ); clone } } impl<ValueT> Deref for StatesSerde<ValueT> where ValueT: Clone + Debug + PartialEq + Eq, { type Target = TypeMapOpt<ItemId, BoxDtDisplay, UnknownEntriesSome<ValueT>>; fn deref(&self) -> &Self::Target { &self.0 } } impl<ValueT> FromIterator<(ItemId, Option<BoxDtDisplay>)> for StatesSerde<ValueT> where ValueT: Clone + Debug + PartialEq + Eq, { fn from_iter<T: IntoIterator<Item = (ItemId, Option<BoxDtDisplay>)>>(iter: T) -> Self { iter.into_iter().fold( Self(TypeMapOpt::new_typed()), |mut states_serde, (item_id, state_boxed)| { states_serde.0.insert_raw(item_id, state_boxed); states_serde }, ) } } impl<ValueT> From<TypeMapOpt<ItemId, BoxDtDisplay, UnknownEntriesSome<ValueT>>> for StatesSerde<ValueT> where ValueT: Clone + Debug + PartialEq + Eq, { fn from(type_map_opt: TypeMapOpt<ItemId, BoxDtDisplay, UnknownEntriesSome<ValueT>>) -> Self { Self(type_map_opt) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/states/state_diffs.rs
crate/resource_rt/src/states/state_diffs.rs
use std::ops::Deref; use peace_fmt::{Presentable, Presenter}; use peace_item_model::ItemId; use serde::Serialize; use type_reg::untagged::{BoxDtDisplay, TypeMap}; use crate::internal::StateDiffsMut; /// Diffs of `State`s for each `Item`s. `TypeMap<ItemId, BoxDtDisplay>` /// newtype. /// /// [`External`] fields are not necessarily used in `StateDiff` computations. /// /// # Implementors /// /// [`StateDiffs`] is a read-only resource, stored in [`Resources`] after /// `DiffCmd` has been executed. /// /// [`External`]: peace_cfg::state::External /// [`Resources`]: crate::Resources #[derive(Debug, Default, Serialize)] pub struct StateDiffs(TypeMap<ItemId, BoxDtDisplay>); impl StateDiffs { /// Returns a new `StateDiffs` map. pub fn new() -> Self { Self::default() } /// Creates an empty `StateDiffs` map with the specified capacity. /// /// The `StateDiffs` will be able to hold at least capacity elements /// without reallocating. If capacity is 0, the map will not allocate. pub fn with_capacity(capacity: usize) -> Self { Self(TypeMap::with_capacity_typed(capacity)) } /// Returns the inner map. pub fn into_inner(self) -> TypeMap<ItemId, BoxDtDisplay> { self.0 } } impl Deref for StateDiffs { type Target = TypeMap<ItemId, BoxDtDisplay>; fn deref(&self) -> &Self::Target { &self.0 } } impl From<TypeMap<ItemId, BoxDtDisplay>> for StateDiffs { fn from(type_map: TypeMap<ItemId, BoxDtDisplay>) -> Self { Self(type_map) } } impl From<StateDiffsMut> for StateDiffs { fn from(state_diffs_mut: StateDiffsMut) -> Self { Self(state_diffs_mut.into_inner()) } } #[peace_fmt::async_trait(?Send)] impl Presentable for StateDiffs { async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> where PR: Presenter<'output>, { presenter .list_numbered_with(self.iter(), |(item_id, state_diff)| { (item_id, format!(": {state_diff}")) }) .await } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/states/states_goal_stored.rs
crate/resource_rt/src/states/states_goal_stored.rs
use std::marker::PhantomData; use crate::states::{ ts::{Goal, GoalStored}, States, }; /// Stored goal `State`s for all `Item`s. /// /// These are the states that each item would be in, if `Item::apply` were to be /// run with `state_goal` as the target state. /// /// This is loaded into [`Resources`] at the beginning of any command execution, /// from the [`StatesGoalFile`]. /// /// This is distinct from [`StatesGoal`] to address the following use cases: /// /// * Fast and offline retrieval of the goal state. /// * Knowing what information the user used when applying a change. /// /// [`StatesGoalFile`]: crate::paths::StatesGoalFile /// [`Data`]: peace_data::Data /// [`Resources`]: crate::Resources pub type StatesGoalStored = States<GoalStored>; impl From<States<Goal>> for States<GoalStored> { fn from(states_goal: States<Goal>) -> Self { let States(type_map, PhantomData) = states_goal; Self(type_map, PhantomData) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/states/states_ensured_dry.rs
crate/resource_rt/src/states/states_ensured_dry.rs
use std::marker::PhantomData; use crate::states::{ts::EnsuredDry, States, StatesCurrent}; /// Dry-run ensured `State`s for all `Item`s. /// /// These are the `State`s collected after `ApplyFns::exec_dry` has been /// run. /// /// # Implementors /// /// You may reference [`StatesEnsuredDry`] after `EnsureCmd::exec_dry` has been /// run. /// /// [`Data`]: peace_data::Data pub type StatesEnsuredDry = States<EnsuredDry>; impl From<StatesCurrent> for StatesEnsuredDry { fn from(states_current: StatesCurrent) -> Self { Self(states_current.into_inner(), PhantomData) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/states/states_current.rs
crate/resource_rt/src/states/states_current.rs
use std::marker::PhantomData; use crate::states::{ ts::{Current, CurrentStored}, States, }; /// Current `State`s for all `Item`s. /// /// This is strictly only present when the [`States`] are discovered in the /// current execution. `States` read from the [`StatesCurrentFile`] are /// inserted into [`Resources`] as [`StatesCurrentStored`], as those discovered /// states may be out of date with the actual. /// /// # Implementors /// /// If an `Item`'s state discovery depends on the `State` of a previous /// `Item`, then you should insert the predecessor's state into /// [`Resources`], and reference that in the subsequent `TryFnSpec`'s [`Data`]: /// /// ```rust /// # use std::path::PathBuf; /// # /// # use peace_data::{Data, R}; /// # /// /// Predecessor `TryFnSpec::Data`. /// #[derive(Data, Debug)] /// pub struct AppUploadParams<'exec> { /// /// Path to the application directory. /// app_dir: W<'exec, PathBuf>, /// } /// /// /// Successor `TryFnSpec::Data`. /// #[derive(Data, Debug)] /// pub struct AppInstallParams<'exec> { /// /// Path to the application directory. /// app_dir: R<'exec, PathBuf>, /// /// Configuration to use. /// config: W<'exec, String>, /// } /// ``` /// /// You may reference [`StatesCurrent`] in `ApplyFns::Data` for reading. It /// is not mutable as `StatesCurrent` must remain unchanged so that all /// `Item`s operate over consistent data. /// /// [`Data`]: peace_data::Data /// [`Resources`]: crate::Resources /// [`StatesCurrentFile`] crate::paths::StatesCurrentFile /// [`StatesCurrentStored`]: crate::states::StatesCurrentStored pub type StatesCurrent = States<Current>; impl From<States<CurrentStored>> for States<Current> { fn from(states_current_stored: States<CurrentStored>) -> Self { let States(type_map, PhantomData) = states_current_stored; Self(type_map, PhantomData) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/states/states_cleaned.rs
crate/resource_rt/src/states/states_cleaned.rs
use std::marker::PhantomData; use crate::states::{ts::Cleaned, States, StatesCurrent}; /// Cleaned `State`s for all `Item`s. `TypeMap<ItemId>` newtype. /// /// These are the `State`s collected after `CleanOpSpec::exec` has been run. /// /// **Note:** Not to be confused with [`StatesClean`]. /// /// [`StatesClean`]: crate::states::StatesClean /// /// # Implementors /// /// You may reference [`StatesCleaned`] after `CleanCmd::exec` has been run, /// unless it is the `ExecutionOutcome`. pub type StatesCleaned = States<Cleaned>; impl From<StatesCurrent> for StatesCleaned { fn from(states: StatesCurrent) -> Self { Self(states.into_inner(), PhantomData) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/resource_rt/src/states/states_cleaned_dry.rs
crate/resource_rt/src/states/states_cleaned_dry.rs
use std::marker::PhantomData; use crate::states::{ts::CleanedDry, States, StatesCurrent}; /// Dry-run ensured `State`s for all `Item`s. /// /// These are the `State`s collected after `CleanOpSpec::exec_dry` has been /// run. /// /// # Implementors /// /// You may reference [`StatesCleanedDry`] after `CleanCmd::exec_dry` has been /// run. /// /// [`Data`]: peace_data::Data pub type StatesCleanedDry = States<CleanedDry>; impl From<StatesCurrent> for StatesCleanedDry { fn from(states: StatesCurrent) -> Self { Self(states.into_inner(), PhantomData) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/flow_model/src/item_info.rs
crate/flow_model/src/item_info.rs
use peace_item_model::ItemId; use serde::{Deserialize, Serialize}; /// Serializable representation of values used for / produced by an [`Item`]. /// /// [`Item`]: https://docs.rs/peace_cfg/latest/peace_cfg/trait.Item.html #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct ItemInfo { /// ID of the `Item`. pub item_id: ItemId, } impl ItemInfo { /// Returns a new `ItemInfo`. pub fn new(item_id: ItemId) -> Self { Self { item_id } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/flow_model/src/flow_spec_info.rs
crate/flow_model/src/flow_spec_info.rs
use dot_ix::model::{ common::{EdgeId, Edges, NodeHierarchy, NodeId, NodeNames}, info_graph::{GraphDir, GraphStyle, InfoGraph}, }; use fn_graph::{daggy::Walker, Edge, GraphInfo}; use serde::{Deserialize, Serialize}; use crate::{FlowId, ItemSpecInfo}; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { use std::collections::HashMap; use dot_ix::model::{ common::AnyId, theme::{AnyIdOrDefaults, CssClassPartials, Theme, ThemeAttr}, }; use peace_item_model::ItemId; use peace_progress_model::{ProgressComplete, ProgressStatus}; } } /// Serializable representation of how a [`Flow`] is configured. /// /// [`Flow`]: https://docs.rs/peace_rt_model/latest/peace_rt_model/struct.Flow.html #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] pub struct FlowSpecInfo { /// ID of the flow. pub flow_id: FlowId, /// Serialized representation of the flow graph. pub graph_info: GraphInfo<ItemSpecInfo>, } impl FlowSpecInfo { /// Returns a new `FlowSpecInfo`. pub fn new(flow_id: FlowId, graph_info: GraphInfo<ItemSpecInfo>) -> Self { Self { flow_id, graph_info, } } /// Returns an [`InfoGraph`] that represents the progress of the flow's /// execution. pub fn to_progress_info_graph(&self) -> InfoGraph { self.to_progress_info_graph_internal( #[cfg(feature = "output_progress")] &HashMap::new(), ) } /// Returns an [`InfoGraph`] that represents the progress of the flow's /// execution. #[cfg(feature = "output_progress")] pub fn to_progress_info_graph_with_statuses( &self, item_progress_statuses: &HashMap<ItemId, ProgressStatus>, ) -> InfoGraph { self.to_progress_info_graph_internal(item_progress_statuses) } fn to_progress_info_graph_internal( &self, #[cfg(feature = "output_progress")] item_progress_statuses: &HashMap< ItemId, ProgressStatus, >, ) -> InfoGraph { let graph_info = &self.graph_info; let item_count = graph_info.node_count(); let hierarchy = graph_info.iter_insertion_with_indices().fold( NodeHierarchy::with_capacity(item_count), |mut hierarchy, (_node_index, item_spec_info)| { let node_id = item_spec_info_to_node_id(item_spec_info); // Progress nodes have no nested nodes. hierarchy.insert(node_id, NodeHierarchy::new()); hierarchy }, ); let edges = progress_node_edges(graph_info); let node_names = node_names(graph_info); let info_graph = InfoGraph::default() .with_graph_style(GraphStyle::Circle) .with_direction(GraphDir::Vertical) .with_hierarchy(hierarchy) .with_edges(edges) .with_node_names(node_names); #[cfg(feature = "output_progress")] { if !item_progress_statuses.is_empty() { let theme = graph_info.iter_insertion_with_indices().fold( Theme::new(), |mut theme, (_node_index, item_spec_info)| { let item_id = &item_spec_info.item_id; if let Some(progress_status) = item_progress_statuses.get(item_id) { let css_class_partials = item_progress_css_class_partials(progress_status); let any_id = AnyId::try_from(item_id.as_str().to_string()).expect( "Expected `peace` `ItemId`s to be valid `dot_ix` `AnyId`s.`", ); if !css_class_partials.is_empty() { theme .styles .insert(AnyIdOrDefaults::AnyId(any_id), css_class_partials); } } theme }, ); return info_graph.with_theme(theme).with_css(String::from( r#" @keyframes ellipse-stroke-dashoffset-move { 0% { stroke-dashoffset: 30; } 100% { stroke-dashoffset: 0; } } "#, )); } } info_graph } } #[cfg(feature = "output_progress")] fn item_progress_css_class_partials(progress_status: &ProgressStatus) -> CssClassPartials { let mut css_class_partials = CssClassPartials::with_capacity(4); match progress_status { ProgressStatus::Initialized => {} ProgressStatus::Interrupted => { css_class_partials.insert(ThemeAttr::ShapeColor, "yellow".to_string()); } ProgressStatus::ExecPending | ProgressStatus::Queued => { css_class_partials.insert(ThemeAttr::ShapeColor, "indigo".to_string()); } ProgressStatus::Running => { css_class_partials.insert(ThemeAttr::StrokeStyle, "dashed".to_string()); css_class_partials.insert(ThemeAttr::StrokeWidth, "[2px]".to_string()); css_class_partials.insert(ThemeAttr::ShapeColor, "blue".to_string()); css_class_partials.insert( ThemeAttr::Animate, "[ellipse-stroke-dashoffset-move_1s_linear_infinite]".to_string(), ); } ProgressStatus::RunningStalled => { css_class_partials.insert(ThemeAttr::ShapeColor, "amber".to_string()); } ProgressStatus::UserPending => { css_class_partials.insert(ThemeAttr::ShapeColor, "purple".to_string()); } ProgressStatus::Complete(ProgressComplete::Success) => { css_class_partials.insert(ThemeAttr::ShapeColor, "green".to_string()); } ProgressStatus::Complete(ProgressComplete::Fail) => { css_class_partials.insert(ThemeAttr::ShapeColor, "red".to_string()); } } css_class_partials } /// Returns the list of edges between items in the graph for progress. /// /// For progress graphs, an edge is rendered between pairs of predecessor and /// successor items, regardless of whether their dependency is `Edge::Logic` /// (adjacent) or `Edge::Contains` (nested). fn progress_node_edges(graph_info: &GraphInfo<ItemSpecInfo>) -> Edges { graph_info.iter_insertion_with_indices().fold( Edges::with_capacity(graph_info.node_count()), |mut edges, (node_index, item_spec_info)| { // let children = graph_info.children(node_index); children .iter(graph_info) .filter_map(|(edge_index, child_node_index)| { // For progress graphs, child nodes that: // // * are contained by parents nodes // * reference data from parent nodes // // are both represented by forward edges, since this is their sequential // ordering. if matches!( graph_info.edge_weight(edge_index).copied(), Some(Edge::Logic | Edge::Contains) ) { Some(child_node_index) } else { None } }) .for_each(|child_node_index| { let item_id = item_spec_info_to_node_id(item_spec_info); let child_item_id = item_spec_info_to_node_id(&graph_info[child_node_index]); let edge_id = EdgeId::try_from(format!("{item_id}__{child_item_id}")).expect( "Expected concatenated `peace` `ItemId`s to be valid `dot_ix` `EdgeId`s.", ); edges.insert(edge_id, [item_id, child_item_id]); }); edges }, ) } /// Returns the list of edges between items in the graph. fn node_names(graph_info: &GraphInfo<ItemSpecInfo>) -> NodeNames { graph_info.iter_insertion_with_indices().fold( NodeNames::with_capacity(graph_info.node_count()), |mut node_names, (_node_index, item_spec_info)| { let item_id = item_spec_info_to_node_id(item_spec_info); // Note: This does not have to be the ID, it can be a human readable name. let node_name = item_id.to_string(); node_names.insert(item_id, node_name); node_names }, ) } fn item_spec_info_to_node_id(item_spec_info: &ItemSpecInfo) -> NodeId { NodeId::try_from(item_spec_info.item_id.to_string()) .expect("Expected `peace` `ItemId`s to be valid `dot_ix` `NodeId`s.`") }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/flow_model/src/lib.rs
crate/flow_model/src/lib.rs
//! Flow data model for the peace automation framework. //! //! This includes the serializable representation of a `Flow`. Since an actual //! `Flow` contains logic, it currently resides in `peace_rt_model`. // Re-exports; pub use dot_ix; pub use fn_graph::GraphInfo; pub use peace_static_check_macros::flow_id; pub use crate::{ flow_id::{FlowId, FlowIdInvalidFmt}, flow_info::FlowInfo, flow_spec_info::FlowSpecInfo, item_info::ItemInfo, item_spec_info::ItemSpecInfo, }; mod flow_id; mod flow_info; mod flow_spec_info; mod item_info; mod item_spec_info;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/flow_model/src/flow_id.rs
crate/flow_model/src/flow_id.rs
use std::borrow::Cow; use serde::{Deserialize, Serialize}; /// Identifier or name of a process flow. /// /// Examples are `"dev_env"` and `"artifact"` in the following snippet: /// /// ```bash /// peace dev_env discover # StatesDiscoverCmd /// peace dev_env status # StatesCurrentStoredDisplayCmd /// peace dev_env deploy # EnsureCmd /// peace dev_env clean # CleanCmd /// /// peace artifact discover # StatesDiscoverCmd /// peace artifact status # StatesCurrentStoredDisplayCmd /// peace artifact publish # EnsureCmd /// ``` /// /// Must begin with a letter or underscore, and contain only letters, numbers, /// and underscores. /// /// # Examples /// /// The following are all examples of valid `FlowId`s: /// /// ```rust /// # use peace_flow_model::{flow_id, FlowId}; /// # /// let _snake = flow_id!("snake_case"); /// let _camel = flow_id!("camelCase"); /// let _pascal = flow_id!("PascalCase"); /// ``` #[derive(Clone, Debug, Hash, PartialEq, Eq, Deserialize, Serialize)] pub struct FlowId(Cow<'static, str>); peace_core::id_newtype!(FlowId, FlowIdInvalidFmt, flow_id, code_inline);
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/flow_model/src/flow_info.rs
crate/flow_model/src/flow_info.rs
use fn_graph::GraphInfo; use serde::{Deserialize, Serialize}; use crate::{FlowId, ItemInfo}; /// Serializable representation of values in a [`Flow`]. /// /// This includes values passed into, or produced by `Item`s in the `Flow`. /// /// [`Flow`]: https://docs.rs/peace_rt_model/latest/peace_rt_model/struct.Flow.html #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct FlowInfo { /// ID of the flow. pub flow_id: FlowId, /// Serialized representation of the flow graph. pub graph_info: GraphInfo<ItemInfo>, } impl FlowInfo { /// Returns a new `FlowInfo`. pub fn new(flow_id: FlowId, graph_info: GraphInfo<ItemInfo>) -> Self { Self { flow_id, graph_info, } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/flow_model/src/item_spec_info.rs
crate/flow_model/src/item_spec_info.rs
use peace_item_model::ItemId; use serde::{Deserialize, Serialize}; /// Serializable representation of how an [`Item`] is configured. /// /// [`Item`]: https://docs.rs/peace_cfg/latest/peace_cfg/trait.Item.html #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct ItemSpecInfo { /// ID of the `Item`. pub item_id: ItemId, } impl ItemSpecInfo { /// Returns a new `ItemSpecInfo`. pub fn new(item_id: ItemId) -> Self { Self { item_id } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/webi_model/src/outcome_info_graph_variant.rs
crate/webi_model/src/outcome_info_graph_variant.rs
use serde::{Deserialize, Serialize}; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { use std::collections::HashMap; use peace_item_model::ItemId; use peace_item_interaction_model::ItemLocationState; use peace_progress_model::{CmdBlockItemInteractionType, ProgressStatus}; } } /// How to style the outcome `InfoGraph`. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum OutcomeInfoGraphVariant { /// Example `InfoGraph` diagram with no special styling. Example, /// Current `InfoGraph` diagram that shows execution progress. Current { /// Type of interactions that a `CmdBlock`s has with `ItemLocation`s. #[cfg(feature = "output_progress")] cmd_block_item_interaction_type: CmdBlockItemInteractionType, /// `ItemLocationState`s of each item. /// /// This is used in the calculation for styling each node. #[cfg(feature = "output_progress")] item_location_states: HashMap<ItemId, ItemLocationState>, /// Execution progress status of each item. /// /// This is used in the calculation for styling each edge. #[cfg(feature = "output_progress")] item_progress_statuses: HashMap<ItemId, ProgressStatus>, }, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/webi_model/src/flow_progress_info_graphs.rs
crate/webi_model/src/flow_progress_info_graphs.rs
use std::ops::{Deref, DerefMut}; use crate::FlowInfoGraphs; /// Shared memory for `Map<CmdExecId, InfoGraph>`. /// /// This is intended to be used for progress diagrams. #[derive(Clone, Debug)] pub struct FlowProgressInfoGraphs<K>(FlowInfoGraphs<K>); impl<K> FlowProgressInfoGraphs<K> { /// Returns a new `FlowProgressInfoGraphs` map. pub fn new() -> Self { Self::default() } /// Returns the underlying `FlowInfoGraphs<K>`. pub fn into_inner(self) -> FlowInfoGraphs<K> { self.0 } } impl<K> Deref for FlowProgressInfoGraphs<K> { type Target = FlowInfoGraphs<K>; fn deref(&self) -> &FlowInfoGraphs<K> { &self.0 } } impl<K> DerefMut for FlowProgressInfoGraphs<K> { fn deref_mut(&mut self) -> &mut FlowInfoGraphs<K> { &mut self.0 } } impl<K> Default for FlowProgressInfoGraphs<K> { fn default() -> Self { Self(Default::default()) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/webi_model/src/lib.rs
crate/webi_model/src/lib.rs
//! Web interface data types for the peace automation framework. pub use crate::{ flow_info_graphs::FlowInfoGraphs, flow_outcome_info_graphs::FlowOutcomeInfoGraphs, flow_progress_info_graphs::FlowProgressInfoGraphs, outcome_info_graph_variant::OutcomeInfoGraphVariant, progress_info_graph_variant::ProgressInfoGraphVariant, web_ui_update::WebUiUpdate, webi_error::WebiError, }; mod flow_info_graphs; mod flow_outcome_info_graphs; mod flow_progress_info_graphs; mod outcome_info_graph_variant; mod progress_info_graph_variant; mod web_ui_update; mod webi_error;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/webi_model/src/web_ui_update.rs
crate/webi_model/src/web_ui_update.rs
use serde::{Deserialize, Serialize}; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { use peace_item_model::ItemId; use peace_item_interaction_model::ItemLocationState; use peace_progress_model::{CmdBlockItemInteractionType, ProgressLimit, ProgressStatus}; } } /// A message that carries what needs to be updated in the web UI. /// /// This is received by the `CmdExecution` task, processed into `InfoGraph`, and /// rendered by `leptos`. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub enum WebUiUpdate { /// A `CmdBlock` has started. #[cfg(feature = "output_progress")] CmdBlockStart { /// The type of interactions the `CmdBlock` has with the /// `ItemLocation`s. cmd_block_item_interaction_type: CmdBlockItemInteractionType, }, /// `ItemLocationState` for a single item. /// /// # Design Note /// /// `ItemLocationState` should live in `peace_item_interaction_model`, but /// this creates a circular dependency. #[cfg(feature = "output_progress")] ItemLocationState { /// ID of the `Item`. item_id: ItemId, /// The representation of the state of an `ItemLocation`. item_location_state: ItemLocationState, }, /// Item's execution progress status. #[cfg(feature = "output_progress")] ItemProgressStatus { /// ID of the item that is updated. item_id: ItemId, /// Status of the item's execution progress. progress_status: ProgressStatus, /// Progress limit for the execution, if known. progress_limit: Option<ProgressLimit>, /// Message to display. message: Option<String>, }, /// Markdown to render. Markdown { /// The markdown source to render. // TODO: receiver should render this using `pulldown-cmark`. markdown_src: String, }, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/webi_model/src/flow_outcome_info_graphs.rs
crate/webi_model/src/flow_outcome_info_graphs.rs
use std::ops::{Deref, DerefMut}; use crate::FlowInfoGraphs; /// Shared memory for `Map<CmdExecId, InfoGraph>`. /// /// This is intended to be used for example / actual outcome diagrams. #[derive(Clone, Debug)] pub struct FlowOutcomeInfoGraphs<K>(FlowInfoGraphs<K>); impl<K> FlowOutcomeInfoGraphs<K> { /// Returns a new `FlowOutcomeInfoGraphs` map. pub fn new() -> Self { Self::default() } /// Returns the underlying `FlowInfoGraphs<K>`. pub fn into_inner(self) -> FlowInfoGraphs<K> { self.0 } } impl<K> Deref for FlowOutcomeInfoGraphs<K> { type Target = FlowInfoGraphs<K>; fn deref(&self) -> &FlowInfoGraphs<K> { &self.0 } } impl<K> DerefMut for FlowOutcomeInfoGraphs<K> { fn deref_mut(&mut self) -> &mut FlowInfoGraphs<K> { &mut self.0 } } impl<K> Default for FlowOutcomeInfoGraphs<K> { fn default() -> Self { Self(Default::default()) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/webi_model/src/flow_info_graphs.rs
crate/webi_model/src/flow_info_graphs.rs
use std::{ collections::HashMap, ops::{Deref, DerefMut}, sync::{Arc, Mutex}, }; use dot_ix_model::info_graph::InfoGraph; /// Shared memory for `Map<CmdExecId, InfoGraph>`. /// /// This may be used for example/actual outcome state. #[derive(Clone, Debug)] pub struct FlowInfoGraphs<K>(Arc<Mutex<HashMap<K, InfoGraph>>>); impl<K> FlowInfoGraphs<K> { /// Returns a new `FlowInfoGraphs` map. pub fn new() -> Self { Self::default() } /// Returns the underlying `Arc<Mutex<HashMap<K, InfoGraph>>>`. pub fn into_inner(self) -> Arc<Mutex<HashMap<K, InfoGraph>>> { self.0 } } impl<K> Deref for FlowInfoGraphs<K> { type Target = Arc<Mutex<HashMap<K, InfoGraph>>>; fn deref(&self) -> &Arc<Mutex<HashMap<K, InfoGraph>>> { &self.0 } } impl<K> DerefMut for FlowInfoGraphs<K> { fn deref_mut(&mut self) -> &mut Arc<Mutex<HashMap<K, InfoGraph>>> { &mut self.0 } } impl<K> Default for FlowInfoGraphs<K> { fn default() -> Self { Self(Arc::new(Mutex::new(HashMap::new()))) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/webi_model/src/progress_info_graph_variant.rs
crate/webi_model/src/progress_info_graph_variant.rs
use indexmap::IndexSet; use peace_item_model::ItemId; use serde::{Deserialize, Serialize}; /// How to style the progress `InfoGraph`. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum ProgressInfoGraphVariant { /// Example `InfoGraph` diagram with no special styling. Example, /// Current `InfoGraph` diagram that shows execution progress. Current { /// IDs of items that are currently in progress. /// /// These items should be styled with animated blue strokes. item_ids_in_progress: IndexSet<ItemId>, /// IDs of the items that are already done. /// /// These items should be styled with green strokes. item_ids_completed: IndexSet<ItemId>, /// Whether the process is interrupted. /// /// Edges after items in progress should be styled yellow. interrupted: bool, }, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/webi_model/src/webi_error.rs
crate/webi_model/src/webi_error.rs
use std::{net::SocketAddr, path::PathBuf}; /// Errors concerning the web interface. #[cfg_attr(feature = "error_reporting", derive(miette::Diagnostic))] #[derive(Debug, thiserror::Error)] pub enum WebiError { /// Failed to create asset directory. #[error("Failed to create asset directory: `{asset_dir}`")] #[cfg_attr( feature = "error_reporting", diagnostic( code(peace_webi_model::webi_asset_dir_create), help("Check if you have sufficient permission to write to the directory.") ) )] AssetDirCreate { /// The directory attempted to be created. asset_dir: PathBuf, /// The underlying error. error: std::io::Error, }, /// Failed to create asset directory. #[error("Failed to write asset: `{asset_path}`")] #[cfg_attr( feature = "error_reporting", diagnostic( code(peace_webi_model::webi_asset_write), help("Check if you have sufficient permission to write to the file.") ) )] AssetWrite { /// Path to the file attempted to be written to. asset_path: PathBuf, /// The underlying error. error: std::io::Error, }, /// Failed to read leptos configuration. /// /// This may be a bug in the Peace framework or `leptos`. #[error("Failed to read leptos configuration. This may be a bug in the Peace framework or `leptos`.")] #[cfg_attr( feature = "error_reporting", diagnostic( code(peace_webi_model::leptos_config_read), help("Ask for help on Discord.") ) )] LeptosConfigRead { /// The underlying error. error: leptos_config::errors::LeptosConfigError, }, /// Failed to start web server for Web interface. #[error("Failed to start web server for Web interface on socket: {socket_addr}")] #[cfg_attr( feature = "error_reporting", diagnostic( code(peace_webi_model::webi_axum_serve), help("Another process may be using the same socket address.") ) )] ServerServe { /// The socket address that the web server attempted to listen on. socket_addr: SocketAddr, /// Underlying error. #[source] error: std::io::Error, }, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cfg/src/accessors.rs
crate/cfg/src/accessors.rs
pub use self::stored::Stored; mod stored;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cfg/src/lib.rs
crate/cfg/src/lib.rs
//! Configuration model for the peace automation library. //! //! This crate defines the API for logic and data to be used in the `peace` //! framework. // Re-exports pub use async_trait::async_trait; pub use peace_core::*; pub use crate::{apply_check::ApplyCheck, fn_ctx::FnCtx, item::Item, state::State}; #[cfg(feature = "output_progress")] pub use crate::ref_into::RefInto; pub mod accessors; pub mod state; mod apply_check; mod fn_ctx; mod item; #[cfg(feature = "output_progress")] mod ref_into;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cfg/src/ref_into.rs
crate/cfg/src/ref_into.rs
use peace_item_interaction_model::ItemLocationState; /// Returns `T` from a reference to `self`. /// /// Allows setting a constraint on `Item::State`, such that `&State` can be /// turned into an `peace_item_interaction_model::ItemLocationState`. /// /// # Implementors /// /// You should `impl<'state> From<&'state YourItemState> for ItemLocationState /// {}`. There is a blanket implementation that implements /// `RefInto<ItemLocationState> for S where ItemLocationState: From<&'state S>` pub trait RefInto<T> { /// Returns `T` from a reference to `self`. fn into(&self) -> T; } impl<S> RefInto<ItemLocationState> for S where for<'state> ItemLocationState: From<&'state S>, S: 'static, { fn into(&self) -> ItemLocationState { ItemLocationState::from(self) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cfg/src/fn_ctx.rs
crate/cfg/src/fn_ctx.rs
use std::marker::PhantomData; use peace_item_model::ItemId; #[cfg(feature = "output_progress")] use peace_progress_model::ProgressSender; /// References to pass information between the Peace framework and an item. #[derive(Clone, Copy, Debug)] pub struct FnCtx<'exec> { /// ID of the item this belongs to. pub item_id: &'exec ItemId, /// For items to submit progress updates. #[cfg(feature = "output_progress")] pub progress_sender: ProgressSender<'exec>, /// Marker. pub marker: PhantomData<&'exec ()>, } impl<'exec> FnCtx<'exec> { /// Returns a new `OpCtx`. pub fn new( item_id: &'exec ItemId, #[cfg(feature = "output_progress")] progress_sender: ProgressSender<'exec>, ) -> Self { Self { item_id, #[cfg(feature = "output_progress")] progress_sender, marker: PhantomData, } } /// Returns the `ProgressTracker` for items to send progress to. #[cfg(feature = "output_progress")] pub fn progress_sender(&self) -> &ProgressSender<'exec> { &self.progress_sender } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cfg/src/state.rs
crate/cfg/src/state.rs
pub use self::{ external::{External, Fetched, Generated, Timestamped}, external_opt::{ExternalOpt, FetchedOpt, GeneratedOpt, TimestampedOpt}, nothing::Nothing, }; mod external; mod external_opt; mod nothing; use std::{any::TypeId, fmt}; use serde::{Deserialize, Serialize}; /// Logical and physical states of a managed item. /// /// This type can be used when the managed item has both logical and physical /// states. Otherwise, a type that represents the fully logical / fully physical /// state is sufficient. /// /// In `peace`, [`State`] represents the values of an item, and has the /// following usages: /// /// * Showing users the state of an item. /// * Allowing users to describe the state that an item should be. /// * Determining what needs to change between the current state and the goal /// state. /// /// Therefore, `State` should be: /// /// * Serializable /// * Displayable in a human readable format /// * Relatively lightweight &ndash; e.g. does not necessarily contain file /// contents, but a hash of it. /// /// /// ## Logical and Physical State /// /// State can be separated into two parts: /// /// * **Logical state:** Information that is functionally important, and can be /// specified by the user ahead of time. /// /// Examples of logical state are: /// /// - File contents /// - An application version /// - Server operating system version /// - Server CPU capacity /// - Server RAM capacity /// /// * **Physical state:** Information that is discovered / produced when the /// automation is executed. /// /// Examples of physical state are: /// /// - ETag of a downloaded file. /// - Execution time of a command. /// - Server ID that is generated on launch. /// - Server IP address. /// /// /// ## Defining State /// /// ### Fully Logical /// /// If an item's state can be fully described before the item exists, and can be /// made to happen without interacting with an external service, then the state /// is fully logical. /// /// For example, copying a file from one directory to another. The state of the /// file in the source directory and destination directories are fully /// discoverable, and there is no information generated during automation that /// is needed to determine if the states are equivalent. /// /// /// ### Logical and Physical /// /// If an item's goal state can be described before the item exists, but /// interacts with an external service which produces additional information to /// bring that goal state into existence, then the state has both logical and /// physical parts. /// /// For example, launching a server or virtual machine. The operating system, /// CPU capacity, and RAM are logical information, and can be determined ahead /// of time. However, the server ID and IP address are produced by the virtual /// machine service provider, which is physical state. /// /// /// ### Fully Physical /// /// If an item's goal state is simply, "automation has been executed after these /// files have been modified", then the state has no logical component. /// /// For example, running a compilation command only if the compilation artifact /// doesn't exist, or the source files have changed since the last time the /// compilation has been executed. #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] pub struct State<Logical, Physical> { /// Logical state pub logical: Logical, /// Physical state pub physical: Physical, } impl<Logical, Physical> State<Logical, Physical> { /// Returns a new `State`. pub fn new(logical: Logical, physical: Physical) -> Self { Self { logical, physical } } } impl<Logical, Physical> fmt::Display for State<Logical, Physical> where Logical: fmt::Display, Physical: fmt::Display + 'static, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let State { logical, physical } = self; // Perhaps we should provide a separate trait instead of using `Display`, which // returns an optional function for each logical / physical state. if TypeId::of::<Physical>() == TypeId::of::<Nothing>() { write!(f, "{logical}") } else { write!(f, "{logical}, {physical}") } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cfg/src/apply_check.rs
crate/cfg/src/apply_check.rs
use serde::{Deserialize, Serialize}; #[cfg(feature = "output_progress")] use peace_progress_model::ProgressLimit; /// Whether the `apply` function needs to be executed. #[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub enum ApplyCheck { /// Item is not in goal state. #[cfg(not(feature = "output_progress"))] ExecRequired, /// Item is not in goal state. #[cfg(feature = "output_progress")] ExecRequired { /// Unit of measurement and limit to indicate progress. progress_limit: ProgressLimit, }, /// Item is already in goal state. ExecNotRequired, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cfg/src/item.rs
crate/cfg/src/item.rs
use std::fmt::{Debug, Display}; use async_trait::async_trait; use dyn_clone::DynClone; use peace_data::Data; use peace_item_model::ItemId; use peace_params::{Params, ParamsSpec}; use peace_resource_rt::{resources::ts::Empty, Resources}; use serde::{de::DeserializeOwned, Serialize}; use crate::{ApplyCheck, FnCtx}; /// Defines all of the data and logic to manage an item. /// /// The item may be simple or complex, ranging from: /// /// * File download. /// * Application installation. /// * Server launching / initialization. /// * Multiple cloud resource management. /// /// The lifecycle functions include: /// /// 1. Status discovery. /// 2. Execution. /// 3. Backup. /// 4. Restoration. /// 5. Clean up / deletion. /// /// Since the latter four functions are write-operations, their specification /// includes a dry run function. /// /// # Logical IDs vs Physical IDs /// /// A logical ID is defined by code, and does not change. A physical ID is one /// generated during execution, which may be random or computed. /// /// ## Examples /// /// The following are examples of logical IDs and corresponding physical /// IDs: /// /// * If the function creates a file, the ID *may* be the full file path, or it /// may be the file name, assuming the file path may be deduced by the clean /// up logic from [`Data`]. /// /// * If the function instantiates a virtual machine on a cloud platform, this /// may be the ID of the instance so that it may be terminated. /// /// | Logical ID | Physical ID | /// | ------------------------ | -------------------------------------- | /// | `app.file_path` | `/mnt/data/app.zip` | /// | `app_server_instance_id` | `ef34a9a4-0c02-45a6-96ec-a4db06d4980c` | /// | `app_server.address` | `10.0.0.1` | /// /// [`Data`]: crate::CleanOpSpec::Data #[async_trait(?Send)] pub trait Item: DynClone { /// Consumer provided error type. type Error: std::error::Error + Send + Sync; /// Summary of the managed item's state. /// /// **For an extensive explanation of state, and how to define it, please /// see the [state concept] as well as the [`State`] type.** /// /// This type is used to represent the current state of the item (if it /// exists), the goal state of the item (what is intended to exist), and /// is used in the *diff* calculation -- what is the difference between the /// current and goal states. /// /// # Examples /// /// * A file's state may be its path, and a hash of its contents. /// * A server's state may be its operating system, CPU and memory capacity, /// IP address, and ID. /// /// [state concept]: https://peace.mk/book/technical_concepts/state.html /// [`State`]: crate::state::State #[cfg(not(feature = "output_progress"))] type State: Clone + Debug + Display + PartialEq + Serialize + DeserializeOwned + Send + Sync + 'static; /// Summary of the managed item's state. /// /// **For an extensive explanation of state, and how to define it, please /// see the [state concept] as well as the [`State`] type.** /// /// This type is used to represent the current state of the item (if it /// exists), the goal state of the item (what is intended to exist), and /// is used in the *diff* calculation -- what is the difference between the /// current and goal states. /// /// # Examples /// /// * A file's state may be its path, and a hash of its contents. /// * A server's state may be its operating system, CPU and memory capacity, /// IP address, and ID. /// /// [state concept]: https://peace.mk/book/technical_concepts/state.html /// [`State`]: crate::state::State #[cfg(feature = "output_progress")] type State: Clone + Debug + Display + PartialEq + Serialize + DeserializeOwned + Send + Sync + 'static + crate::RefInto<peace_item_interaction_model::ItemLocationState>; /// Diff between the current and target [`State`]s. /// /// # Design Note /// /// Initially I thought the field-wise diff between two [`State`]s is /// suitable, but: /// /// * Externally controlled state may not be known ahead of time. /// * It isn't easy or necessarily goal to compare every single field. /// * `state.apply(diff) = state_goal` may not be meaningful for a field /// level diff, and the `apply` may be a complex process. /// /// [`State`]: Self::State type StateDiff: Clone + Debug + Display + Serialize + DeserializeOwned + Send + Sync + 'static; /// Parameters to use this item. /// /// Item consumers must provide for this item to work. /// /// # Examples /// /// * For a file download item: /// /// - URL of the file. /// - Credentials. /// /// * For a server launch item: /// /// - Image ID. /// - Server size. /// /// # Implementors /// /// Peace will automatically save and load these into `Resources` when a /// command context is built. type Params<'exec>: Params<Spec = ParamsSpec<Self::Params<'exec>>> + Clone + Debug + Serialize + DeserializeOwned + Send + Sync + 'static; /// Data that the item accesses at runtime. /// /// These may be objects instantiated in `setup` for use during execution, /// or information calculated from previous items. type Data<'exec>: Data<'exec>; /// Returns the ID of this full spec. /// /// # Implementors /// /// The ID should be a unique value that does not change over the lifetime /// of the managed item. /// /// [`ItemId`]s must begin with a letter or underscore, and contain only /// letters, numbers, and underscores. The [`item_id!`] macro provides /// a compile time check to ensure that these conditions are upheld. /// /// ```rust /// # use peace_item_model::{item_id, ItemId}; /// const fn id() -> ItemId { /// item_id!("my_item") /// } /// # fn main() { let _id = id(); } /// ``` /// /// # Design Note /// /// This is an instance method as logic for an `Item` may be used for /// multiple tasks. For example, an `Item` implemented to download a /// file may be instantiated with different files to download, and each /// instance of the `Item` should have its own ID. /// /// [`item_id!`]: peace_static_check_macros::item_id fn id(&self) -> &ItemId; /// Inserts an instance of each data type in [`Resources`]. /// /// # Implementors /// /// [`Resources`] is the map of any type, and an instance of each data type /// must be inserted into the map so that item functions can borrow the /// instance of that type. /// /// ## External Parameters /// /// If the item works with an external source for parameters, such as: /// /// * a version controlled package file that specifies dependency versions /// * (discouraged) a web service with project configuration /// /// then this is the function to include the logic to read those files. /// /// ## Fallibility /// /// The function signature allows for fallibility, to allow issues to be /// reported early, such as: /// /// * Credentials to SDK clients not present on the user's system. /// * Incompatible / invalid values specified in project configuration /// files, or expected project configuration files don't exist. /// /// [`check`]: crate::ApplyFns::check /// [`apply`]: crate::ApplyFns::apply async fn setup(&self, resources: &mut Resources<Empty>) -> Result<(), Self::Error>; /// Returns an example fully deployed state of the managed item. /// /// # Implementors /// /// This is *expected* to always return a value, as it is used to: /// /// * Display a diagram that shows the user what the item looks like when it /// is fully deployed, without actually interacting with any external /// state. /// /// As much as possible, use the values in the provided params and data. /// /// This function should **NOT** interact with any external services, or /// read from files that are part of the automation process, e.g. /// querying data from a web endpoint, or reading files that may be /// downloaded by a predecessor. /// /// ## Infallibility /// /// The signature is deliberately infallible to signal to implementors that /// calling an external service / read from a file is incorrect /// implementation for this method -- values in params / data may be example /// values from other items that may not resolve. /// /// ## Non-async /// /// Similar to infallibility, this signals to implementors that this /// function should be a cheap example state computation that is relatively /// realistic rather than determining an accurate value. #[cfg(feature = "item_state_example")] fn state_example(params: &Self::Params<'_>, data: Self::Data<'_>) -> Self::State; /// Returns the current state of the managed item, if possible. /// /// This should return `Ok(None)` if the state is not able to be queried, /// such as when failing to connect to a remote host, instead of returning /// an error. async fn try_state_current( fn_ctx: FnCtx<'_>, params_partial: &<Self::Params<'_> as Params>::Partial, data: Self::Data<'_>, ) -> Result<Option<Self::State>, Self::Error>; /// Returns the current state of the managed item. /// /// This is *expected* to successfully discover the current state, so errors /// will be presented to the user. async fn state_current( fn_ctx: FnCtx<'_>, params: &Self::Params<'_>, data: Self::Data<'_>, ) -> Result<Self::State, Self::Error>; /// Returns the goal state of the managed item, if possible. /// /// This should return `Ok(None)` if the state is not able to be queried, /// such as when failing to read a potentially non-existent file to /// determine its content hash, instead of returning an error. async fn try_state_goal( fn_ctx: FnCtx<'_>, params_partial: &<Self::Params<'_> as Params>::Partial, data: Self::Data<'_>, ) -> Result<Option<Self::State>, Self::Error>; /// Returns the goal state of the managed item. /// /// This is *expected* to successfully discover the goal state, so errors /// will be presented to the user. /// /// # Examples /// /// * For a file download item, the goal state could be the destination path /// and a content hash. /// /// * For a web application service item, the goal state could be the web /// service is running on the latest version. async fn state_goal( fn_ctx: FnCtx<'_>, params: &Self::Params<'_>, data: Self::Data<'_>, ) -> Result<Self::State, Self::Error>; /// Returns the difference between two states. /// /// # Implementors /// /// When this type is serialized, it should provide "just enough" / /// meaningful information to the user on what has changed. So instead of /// including the complete goal [`State`], it should only include the /// parts that changed. /// /// This function call is intended to be cheap and fast. /// /// # Examples /// /// * For a file download item, the difference could be the content hash /// changes from `abcd` to `efgh`. /// /// * For a web application service item, the goal state could be the /// application version changing from 1 to 2. async fn state_diff( params_partial: &<Self::Params<'_> as Params>::Partial, data: Self::Data<'_>, state_a: &Self::State, state_b: &Self::State, ) -> Result<Self::StateDiff, Self::Error>; /// Returns the representation of a clean `State`. /// /// # Implementors /// /// This should return essentially the `None` concept of the item /// state. The diff between this and the current state will be shown to the /// user when they want to see what would be cleaned up by the clean /// command. async fn state_clean( params_partial: &<Self::Params<'_> as Params>::Partial, data: Self::Data<'_>, ) -> Result<Self::State, Self::Error>; /// Returns whether `apply` needs to be executed. /// /// If the current state is already in sync with the target state, then /// `apply` does not have to be executed. /// /// # Examples /// /// * For a file download item, if the destination file differs from the /// file on the server, then the file needs to be downloaded. /// /// * For a web application service item, if the web service is running, but /// reports a previous version, then the service may need to be restarted. /// /// # Implementors /// /// This function call is intended to be cheap and fast. /// /// # Parameters /// /// * `fn_ctx`: Context to send progress updates. /// * `params`: Parameters to the item. /// * `data`: Runtime data that the function reads from or writes to. /// * `state_current`: Current [`State`] of the managed item, returned from /// [`state_current`]. /// * `state_target`: Target [`State`] of the managed item, either /// [`state_clean`] or [`state_goal`]. /// * `state_diff`: Goal [`State`] of the managed item, returned from /// [`state_diff`]. /// /// [`state_clean`]: crate::Item::state_clean /// [`state_current`]: crate::Item::state_current /// [`state_goal`]: crate::Item::state_goal /// [`State`]: Self::State /// [`state_diff`]: crate::Item::state_diff async fn apply_check( params: &Self::Params<'_>, data: Self::Data<'_>, state_current: &Self::State, state_target: &Self::State, diff: &Self::StateDiff, ) -> Result<ApplyCheck, Self::Error>; /// Dry-run transform of the current state to the target state. /// /// This will only be called if [`check`] returns [`ExecRequired`]. /// /// This should mirror the logic in [`apply`], with the following /// differences: /// /// 1. When state will actually be altered, this would skip the logic. /// /// 2. Where there would be IDs received from an external system, a /// placeholder ID should still be inserted into the runtime data. This /// should allow subsequent `Item`s that rely on this one to use those /// placeholders in their logic. /// /// # Implementors /// /// This function call is intended to be read-only and relatively cheap. /// Values in `params` and `data` cannot be guaranteed to truly exist. /// [#196] tracks the work to resolve what this function's contract should /// be. /// /// # Parameters /// /// * `fn_ctx`: Context to send progress updates. /// * `params`: Parameters to the item. /// * `data`: Runtime data that the function reads from or writes to. /// * `state_current`: Current [`State`] of the managed item, returned from /// [`state_current`]. /// * `state_target`: Target [`State`] of the managed item, either /// [`state_clean`] or [`state_goal`]. /// * `state_diff`: Goal [`State`] of the managed item, returned from /// [`state_diff`]. /// /// [`check`]: Self::check /// [`ExecRequired`]: crate::ApplyCheck::ExecRequired /// [`state_clean`]: crate::Item::state_clean /// [`state_current`]: crate::Item::state_current /// [`state_goal`]: crate::Item::state_goal /// [`State`]: Self::State /// [`state_diff`]: crate::Item::state_diff /// [#196]: https://github.com/azriel91/peace/issues/196 async fn apply_dry( fn_ctx: FnCtx<'_>, params: &Self::Params<'_>, data: Self::Data<'_>, state_current: &Self::State, state_target: &Self::State, diff: &Self::StateDiff, ) -> Result<Self::State, Self::Error>; /// Transforms the current state to the target state. /// /// This will only be called if [`check`] returns [`ExecRequired`]. /// /// # Parameters /// /// * `fn_ctx`: Context to send progress updates. /// * `params`: Parameters to the item. /// * `data`: Runtime data that the function reads from or writes to. /// * `state_current`: Current [`State`] of the managed item, returned from /// [`state_current`]. /// * `state_target`: Target [`State`] of the managed item, either /// [`state_clean`] or [`state_goal`]. /// * `state_diff`: Goal [`State`] of the managed item, returned from /// [`state_diff`]. /// /// [`check`]: Self::check /// [`ExecRequired`]: crate::ApplyCheck::ExecRequired /// [`state_clean`]: crate::Item::state_clean /// [`state_current`]: crate::Item::state_current /// [`state_goal`]: crate::Item::state_goal /// [`State`]: Self::State /// [`state_diff`]: crate::Item::state_diff async fn apply( fn_ctx: FnCtx<'_>, params: &Self::Params<'_>, data: Self::Data<'_>, state_current: &Self::State, state_target: &Self::State, diff: &Self::StateDiff, ) -> Result<Self::State, Self::Error>; /// Returns the physical resources that this item interacts with. /// /// # Examples /// /// ## File Download Item /// /// This may be from: /// /// * host server /// * URL /// /// to: /// /// * localhost /// * file system path /// /// /// ### Server Launch Item /// /// This may be from: /// /// * localhost /// /// to: /// /// * cloud provider /// * region /// * subnet /// * host /// /// /// # Implementors /// /// The returned list should be in order of least specific to most specific /// location. #[cfg(feature = "item_interactions")] fn interactions( params: &Self::Params<'_>, data: Self::Data<'_>, ) -> Vec<peace_item_interaction_model::ItemInteraction>; }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cfg/src/state/external.rs
crate/cfg/src/state/external.rs
use std::fmt::{self, Display}; use serde::{Deserialize, Serialize}; /// Physical state that is externally defined -- computed, generated, or /// fetched. /// /// Compared to [`ExternalOpt`], this does not have the `None` variant, to /// indicate that the external source must return a value, and the lack of a /// value is a bug and must be surfaced as an issue to the user. /// /// The following type aliases are available to semantically name the type in /// item implementations: /// /// * [`Generated`] /// * [`Fetched`] /// * [`Timestamped`] /// /// [`ExternalOpt`]: crate::state::ExternalOpt #[enser::enser] #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum External<V> { /// Placeholder indicating this value is not yet defined. Tbd, /// Value has been recorded after execution. Value(V), } impl<V> Display for External<V> where V: Clone + Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let type_name = tynm::type_name::<V>(); match self { Self::Tbd => write!(f, "{type_name} not yet determined"), Self::Value(v) => write!(f, "{type_name}: {v}"), } } } /// Physical state that is computed or generated externally, e.g. a server ID. pub type Generated<V> = External<V>; /// Physical state that is fetched from an external source, e.g. an ETag. pub type Fetched<V> = External<V>; /// Physical state that depends on time, e.g. last execution time. pub type Timestamped<V> = External<V>;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cfg/src/state/external_opt.rs
crate/cfg/src/state/external_opt.rs
use std::fmt::{self, Display}; use serde::{Deserialize, Serialize}; /// Physical state that is externally defined -- computed, generated, or /// fetched. /// /// Compared to [`External`], this also has a `None` variant, to indicate that /// the external source has been queried, but it did not return a value. /// /// The following type aliases are available to semantically name the type in /// item implementations: /// /// * [`GeneratedOpt`] /// * [`FetchedOpt`] /// * [`TimestampedOpt`] /// /// [`External`]: crate::state::External #[enser::enser] #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] pub enum ExternalOpt<V> { /// Placeholder indicating this value is not yet defined. Tbd, /// The external source did not return a value. None, /// Value has been recorded after execution. Value(V), } impl<V> Display for ExternalOpt<V> where V: Clone + Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let type_name = tynm::type_name::<V>(); match self { Self::Tbd => write!(f, "{type_name} not yet determined"), Self::None => write!(f, "{type_name} does not exist on source"), Self::Value(v) => write!(f, "{type_name}: {v}"), } } } /// Physical state that is computed or generated externally, e.g. a server ID. pub type GeneratedOpt<V> = ExternalOpt<V>; /// Physical state that is fetched from an external source, e.g. an ETag. pub type FetchedOpt<V> = ExternalOpt<V>; /// Physical state that depends on time, e.g. last execution time. pub type TimestampedOpt<V> = ExternalOpt<V>;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cfg/src/state/nothing.rs
crate/cfg/src/state/nothing.rs
use std::fmt; use serde::{Deserialize, Serialize}; /// Represents no data. /// /// This is used to represent no separate physical state. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Nothing; impl fmt::Display for Nothing { fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { Ok(()) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cfg/src/accessors/stored.rs
crate/cfg/src/accessors/stored.rs
use std::{ any::TypeId, fmt::{Debug, Display}, marker::PhantomData, }; use peace_data::{ fn_graph::{ resman::{BorrowFail, Ref}, DataAccess, DataAccessDyn, Resources, TypeIds, }, Data, }; use peace_item_model::ItemId; use peace_resource_rt::{states::StatesCurrentStored, type_reg::untagged::DataType}; use serde::Serialize; /// The previously stored `T` state, if any. #[derive(Debug)] pub struct Stored<'borrow, T> { /// ID of the item the state should be retrieved for. item_id: &'borrow ItemId, /// The borrowed `StatesCurrentStored`. states_current_stored: Option<Ref<'borrow, StatesCurrentStored>>, /// Marker. marker: PhantomData<T>, } impl<'borrow, T> Stored<'borrow, T> where T: Clone + Debug + DataType + Display + Serialize + Send + Sync + 'static, { pub fn get(&'borrow self) -> Option<&'borrow T> { self.states_current_stored .as_ref() .and_then(|states_current_stored| states_current_stored.get(self.item_id)) } } impl<'borrow, T> Data<'borrow> for Stored<'borrow, T> where T: Debug + Send + Sync + 'static, { fn borrow(item_id: &'borrow ItemId, resources: &'borrow Resources) -> Self { let states_current_stored = resources .try_borrow::<StatesCurrentStored>() .map_err(|borrow_fail| match borrow_fail { e @ BorrowFail::ValueNotFound => e, BorrowFail::BorrowConflictImm | BorrowFail::BorrowConflictMut => { panic!("Encountered {borrow_fail:?}") } }) .ok(); Self { item_id, states_current_stored, marker: PhantomData, } } } impl<T> DataAccess for Stored<'_, T> { fn borrows() -> TypeIds where Self: Sized, { let mut type_ids = TypeIds::new(); type_ids.push(TypeId::of::<StatesCurrentStored>()); type_ids } fn borrow_muts() -> TypeIds where Self: Sized, { TypeIds::new() } } impl<T> DataAccessDyn for Stored<'_, T> { fn borrows(&self) -> TypeIds where Self: Sized, { let mut type_ids = TypeIds::new(); type_ids.push(TypeId::of::<StatesCurrentStored>()); type_ids } fn borrow_muts(&self) -> TypeIds where Self: Sized, { TypeIds::new() } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/fmt/src/lib.rs
crate/fmt/src/lib.rs
//! Presentation and formatting support for the peace automation framework. //! //! See [Output Presentation]. //! //! [Output Presentation]: https://peace.mk/book/technical_concepts/output/presentation.html // Re-exports pub use async_trait::async_trait; pub use crate::{ either::Either, presentable::Presentable, presentable_ext::PresentableExt, presenter::Presenter, }; pub mod presentable; mod either; mod presentable_ext; mod presenter; /// Ergonomically present multiple [`Presentable`]s. /// /// # Examples /// /// ```rust,ignore /// use peace_fmt::{present, Presentable}; /// /// present!(output, "a str", item, "\n"); /// ``` #[macro_export] macro_rules! present { ($output:ident, [$($p:expr),+]) => { $($output.present($p).await?;)+ }; } /// Ergonomically present multiple [`Presentable`]s. /// /// # Examples /// /// ```rust,ignore /// use peace_fmt::{present, Presentable}; /// /// presentln!(output, "a str", item, "\n"); /// ``` #[macro_export] macro_rules! presentln { ($output:ident, [$($p:expr),+]) => { $($output.present($p).await?;)+ $output.present("\n").await?; }; }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/fmt/src/presenter.rs
crate/fmt/src/presenter.rs
use crate::{presentable::HeadingLevel, Presentable}; /// Takes a `Presentable` type and presents it to the user. /// /// # Design /// /// ```text /// .--- Presentable::present(&self, presenter); /// : /// .--------. : .-----------. .---------------. /// | Caller | : | Peace's | | Implementor's | /// | | -----> | Presenter | ---> | Presenter | /// '--------' '-----------' '---------------' /// : /// : /// // Peace wraps the implementor's `Presenter` /// // in a tracking `Presenter`, which allows: /// // /// // * Implementors to perceive using a `Presenter` /// // in `Presentable` implementations. /// // * Peace to gatekeep how much detail is passed /// // through, by tracking depth of information. /// ``` /// /// ## List Presentation /// /// For output to be formatted aesthetically, certain formatters require the /// presented width of a list's entries to be known. /// /// However, the width of a `Presentable` entry's presentation can only be known /// when it is `present`ed, which requires rendering to an in-memory buffer, /// tracking the character count, then copying from that buffer to the actual /// output. /// /// Currently Peace does not support this staged approach, and instead streams /// each entry to the presenter as it is added. The benefit of this approach is /// the presentation can be rendered without needing intermediate data to be /// held in memory for each entry. #[async_trait::async_trait(?Send)] pub trait Presenter<'output> { /// Presents the given presentable as a heading. /// /// # Purposes /// /// * Headings. async fn heading<P>(&mut self, level: HeadingLevel, presentable: &P) -> Result<(), Self::Error> where P: Presentable + ?Sized; /// Error returned during a presentation failure. type Error: std::error::Error; /// Presents text as an item id. /// /// # Purposes /// /// * An ID with no spaces, e.g. "my_item" async fn id(&mut self, id: &str) -> Result<(), Self::Error>; /// Presents text as an item name. /// /// # Purposes /// /// * A display name with spaces, e.g. "My Item" async fn name(&mut self, name: &str) -> Result<(), Self::Error>; /// Presents text as plain text. async fn text(&mut self, text: &str) -> Result<(), Self::Error>; /// Presents the given presentable bolded. /// /// # Purposes /// /// * Emphasis. async fn bold<P>(&mut self, presentable: &P) -> Result<(), Self::Error> where P: Presentable + ?Sized; /// Presents text as inline code. /// /// # Purposes /// /// * Short bit of code, e.g. "my::module", "MyStruct", "function_name". async fn code_inline(&mut self, text: &str) -> Result<(), Self::Error>; /// Presents text as a tag. /// /// # Purposes /// /// * A profile, e.g. "development", "production". /// * A value used to categorize data, e.g. "stale". async fn tag(&mut self, tag: &str) -> Result<(), Self::Error>; /// Presents a numbered list. /// /// # Purposes /// /// * A list of steps. async fn list_numbered<'f, P, I>(&mut self, iter: I) -> Result<(), Self::Error> where P: Presentable + ?Sized + 'f, I: IntoIterator<Item = &'f P>; /// Presents a numbered list, computing the `Presentable` with the provided /// function. /// /// # Purposes /// /// * A list of steps. async fn list_numbered_with<'f, P, I, T, F>( &mut self, iter: I, f: F, ) -> Result<(), Self::Error> where P: Presentable, I: IntoIterator<Item = T>, T: 'f, F: Fn(T) -> P; /// Presents an aligned numbered list. /// /// Each item in the list has two parts: the "name", and the "description". /// /// The list will be rendered with all items' descriptions aligned to the /// item with the longest name. i.e. /// /// ```md /// 1. Short name: Description 1. /// 2. Longer name: Description 2. /// 3. Very long name: Another description. /// ``` /// /// # Purposes /// /// * A list of items. async fn list_numbered_aligned<'f, P0, P1, I>(&mut self, iter: I) -> Result<(), Self::Error> where P0: Presentable + 'f, P1: Presentable + 'f, I: IntoIterator<Item = &'f (P0, P1)>; /// Presents an aligned numbered list, computing the `Presentable` with the /// provided function. /// /// Each item in the list has two parts: the "name", and the "description". /// /// The list will be rendered with all items' descriptions aligned to the /// item with the longest name. i.e. /// /// ```md /// 1. Short name: Description 1. /// 2. Longer name: Description 2. /// 3. Very long name: Another description. /// ``` /// /// # Purposes /// /// * A list of items. async fn list_numbered_aligned_with<'f, P0, P1, I, T, F>( &mut self, iter: I, f: F, ) -> Result<(), Self::Error> where P0: Presentable + 'f, P1: Presentable + 'f, I: IntoIterator<Item = T>, T: 'f, F: Fn(T) -> &'f (P0, P1); /// Presents a bulleted list. /// /// # Purposes /// /// * A list of items. async fn list_bulleted<'f, P, I>(&mut self, iter: I) -> Result<(), Self::Error> where P: Presentable + ?Sized + 'f, I: IntoIterator<Item = &'f P>; /// Presents a bulleted list, computing the `Presentable` with the provided /// function. /// /// # Purposes /// /// * A list of items. async fn list_bulleted_with<'f, P, I, T, F>( &mut self, iter: I, f: F, ) -> Result<(), Self::Error> where P: Presentable, I: IntoIterator<Item = T>, T: 'f, F: Fn(T) -> P; /// Presents an aligned bulleted list. /// /// Each item in the list has two parts: the "name", and the "description". /// /// The list will be rendered with all items' descriptions aligned to the /// item with the longest name. i.e. /// /// ```md /// * Short name: Description 1. /// * Longer name: Description 2. /// * Very long name: Another description. /// ``` /// /// # Purposes /// /// * A list of items. async fn list_bulleted_aligned<'f, P0, P1, I>(&mut self, iter: I) -> Result<(), Self::Error> where P0: Presentable + 'f, P1: Presentable + 'f, I: IntoIterator<Item = &'f (P0, P1)>; /// Presents an aligned bulleted list, computing the `Presentable` with the /// provided function. /// /// Each item in the list has two parts: the "name", and the "description". /// /// The list will be rendered with all items' descriptions aligned to the /// item with the longest name. i.e. /// /// ```md /// * Short name: Description 1. /// * Longer name: Description 2. /// * Very long name: Another description. /// ``` /// /// # Purposes /// /// * A list of items. async fn list_bulleted_aligned_with<'f, P0, P1, I, T, F>( &mut self, iter: I, f: F, ) -> Result<(), Self::Error> where P0: Presentable + 'f, P1: Presentable + 'f, I: IntoIterator<Item = T>, T: 'f, F: Fn(T) -> &'f (P0, P1); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/fmt/src/either.rs
crate/fmt/src/either.rs
use serde::{Deserialize, Serialize}; use crate::{Presentable, Presenter}; /// Combines two different `Presentable`s into a single type. /// /// This is useful when conditionally choosing between two distinct /// `Presentable` types: /// /// ```rust,ignore /// use peace_fmt::{Either, Presentable}; /// /// let cond = true; /// /// let presentable = if cond { /// Either::Left(Bold::new(String::from("a"))); /// } else { /// Either::Right(CodeInline::new("b".into())); /// }; /// /// presentln!(output, &presentable); /// ``` #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub enum Either<A, B> { /// First branch of the type. Left(A), /// Second branch of the type. Right(B), } #[async_trait::async_trait(?Send)] impl<A, B> Presentable for Either<A, B> where A: Presentable, B: Presentable, { async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> where PR: Presenter<'output>, { match self { Self::Left(a) => a.present(presenter).await, Self::Right(b) => b.present(presenter).await, } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/fmt/src/presentable.rs
crate/fmt/src/presentable.rs
pub use self::{ bold::Bold, code_inline::CodeInline, heading::Heading, heading_level::HeadingLevel, list_bulleted::ListBulleted, list_bulleted_aligned::ListBulletedAligned, list_numbered::ListNumbered, list_numbered_aligned::ListNumberedAligned, }; use serde::Serialize; use crate::Presenter; mod bold; mod code_inline; mod heading; mod heading_level; mod list_bulleted; mod list_bulleted_aligned; mod list_numbered; mod list_numbered_aligned; mod tuple_impl; /// A type that is presentable to a user. /// /// This is analogous in concept to `std::fmt::Display`, and in implementation /// to `std::fmt::Debug`, with the difference that instead of formatting an /// unstyled string, implementations register how they are presented with a /// [`Presenter`]. /// /// # Implementors /// /// Currently it is not possible to store `Box<dyn Presentable>`, because of the /// following: /// /// * `Presentable` implies `Serialize`. /// * `Presentable::present<'_, PR>` and `Serialize::serialize<S>` are generic /// trait methods. /// * This means different concrete implementations of `Presentable`/`Serialize` /// will have different vtables (with different sizes), and Rust returns the /// following compilation error: /// /// ```text /// error[E0038]: the trait `Presentable` cannot be made into an object /// ``` /// /// See <https://doc.rust-lang.org/error_codes/E0038.html>. /// /// It is possible to store `Vec<Box<T>>` for any `T: Presentable` and invoke /// `boxed.present()`. /// /// # Examples /// /// Presenting a list item with a name and value: /// /// ```rust /// # use peace_fmt::{Presentable, Presenter}; /// # use serde::{Deserialize, Serialize}; /// // use peace::fmt::{Presentable, Presenter}; /// /// #[derive(Clone, Deserialize, Serialize)] /// struct Item { /// name: String, /// desc: String, /// } /// /// #[async_trait::async_trait(?Send)] /// impl Presentable for Item { /// async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> /// where /// PR: Presenter<'output>, /// { /// presenter.name(&self.name).await?; /// presenter.text(": ").await?; /// presenter.text(&self.desc).await?; /// Ok(()) /// } /// } /// ``` /// /// # Design /// /// `Presentable` implies `Serialize` because it is beneficial for anything that /// is presented to the user, to be able to be stored, so that it can be /// re-presented to them at a later time. However, it currently doesn't imply /// `DeserializeOwned`, which may mean the serialization half may not be /// worthwhile, and `Presentable` wrapper types may just wrap borrowed data. /// /// Previously, this was implemented as `Presentable: Serialize + /// OwnedDeserialize`, with `OwnedDeserialize` being the following trait: /// /// ```rust /// use serde::de::DeserializeOwned; /// /// /// Marker trait to allow `str` to implement `Presentable`. /// /// /// /// 1. `str` is not an owned type, so it doesn't `impl DeserializeOwned`. /// /// 2. We don't want to relax the constraints such that `Presentable` doesn't /// /// imply `DeserializeOwned`. /// pub trait OwnedDeserialize {} /// /// impl<T> OwnedDeserialize for T /// where /// T: ToOwned + ?Sized, /// <T as ToOwned>::Owned: DeserializeOwned, /// { /// } /// ``` /// /// However, because stateful deserialized types such as `TypeMap` don't /// implement `DeserializeOwned`, so any types based on that such as `States` /// would not be able to implement `Presentable` with this bound. #[async_trait::async_trait(?Send)] pub trait Presentable: Serialize { /// Presents this data type to the user. async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> where PR: Presenter<'output>; } #[async_trait::async_trait(?Send)] impl<T> Presentable for &T where T: Presentable + ?Sized, { async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> where PR: Presenter<'output>, { // The `*` is important -- without it the `present` will stack overflow. (*self).present(presenter).await } } #[async_trait::async_trait(?Send)] impl Presentable for str { async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> where PR: Presenter<'output>, { presenter.text(self).await } } #[async_trait::async_trait(?Send)] impl Presentable for String { async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> where PR: Presenter<'output>, { presenter.text(self).await } } /// **Note:** `T` must be `Sized`, as `Vec`s store sized types. #[async_trait::async_trait(?Send)] impl<T> Presentable for Vec<T> where T: Presentable, { async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> where PR: Presenter<'output>, { presenter.list_numbered(self.iter()).await } } /// **Note:** `T` must be `Sized`, as arrays store sized types. #[async_trait::async_trait(?Send)] impl<T> Presentable for [T] where T: Presentable, { async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> where PR: Presenter<'output>, { presenter.list_numbered(self.iter()).await } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/fmt/src/presentable_ext.rs
crate/fmt/src/presentable_ext.rs
use crate::{Either, Presentable}; /// Additional functionality for `Presentable` types. pub trait PresentableExt { /// Wraps this `Presentable` in an `Either`, making it the left-hand variant /// of that `Either`. /// /// This can be used in combination with the `right_presentable` method to /// write `if` statements that evaluate to different `Presentable`s in /// different branches. /// /// # Examples /// /// ```rust,ignore /// use peace_fmt::{Either, Presentable, PresentableExt}; /// /// let cond = true; /// /// let presentable = if cond { /// Bold::new(String::from("a")).left_presentable(); /// } else { /// CodeInline::new("b".into()).right_presentable(); /// }; /// /// presentln!(output, &presentable); /// ``` fn left_presentable<B>(self) -> Either<Self, B> where B: Presentable, Self: Sized; /// Wraps this `Presentable` in an `Either`, making it the right-hand /// variant of that `Either`. /// /// This can be used in combination with the `left_presentable` method to /// write `if` statements that evaluate to different `Presentable`s in /// different branches. /// /// # Examples /// /// ```rust,ignore /// use peace_fmt::{Either, Presentable, PresentableExt}; /// /// let cond = true; /// /// let presentable = if cond { /// Bold::new(String::from("a")).left_presentable(); /// } else { /// CodeInline::new("b".into()).right_presentable(); /// }; /// /// presentln!(output, &presentable); /// ``` fn right_presentable<A>(self) -> Either<A, Self> where A: Presentable, Self: Sized; } impl<T> PresentableExt for T where T: Presentable, { fn left_presentable<B>(self) -> Either<Self, B> where B: Presentable, Self: Sized, { Either::Left(self) } fn right_presentable<A>(self) -> Either<A, Self> where A: Presentable, Self: Sized, { Either::Right(self) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/fmt/src/presentable/list_numbered.rs
crate/fmt/src/presentable/list_numbered.rs
use serde::{Deserialize, Serialize}; use crate::{Presentable, Presenter}; /// Presents the given iterator as a numbered list. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct ListNumbered<P>(Vec<P>); impl<P> ListNumbered<P> { /// Returns a new `ListNumbered` wrapper. pub fn new(presentables: Vec<P>) -> Self { Self(presentables) } } #[async_trait::async_trait(?Send)] impl<P> Presentable for ListNumbered<P> where P: Presentable, { async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> where PR: Presenter<'output>, { presenter.list_numbered(&self.0).await } } impl<P> From<Vec<P>> for ListNumbered<P> where P: Presentable, { fn from(presentables: Vec<P>) -> Self { Self(presentables) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/fmt/src/presentable/heading_level.rs
crate/fmt/src/presentable/heading_level.rs
use serde::{Deserialize, Serialize}; /// Level of conceptual detail for a given topic. #[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)] pub enum HeadingLevel { /// Top level heading. Level1, /// Second level heading. Level2, /// Third level heading. Level3, /// Fourth level heading. Level4, /// Fifth level heading. Level5, /// Lowest level of conceptual detail. Level6, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/fmt/src/presentable/list_numbered_aligned.rs
crate/fmt/src/presentable/list_numbered_aligned.rs
use serde::{Deserialize, Serialize}; use crate::{Presentable, Presenter}; /// Presents the given iterator as an aligned numbered list. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct ListNumberedAligned<P0, P1>(Vec<(P0, P1)>); impl<P0, P1> ListNumberedAligned<P0, P1> { /// Returns a new `ListNumberedAligned` wrapper. pub fn new(presentables: Vec<(P0, P1)>) -> Self { Self(presentables) } } #[async_trait::async_trait(?Send)] impl<P0, P1> Presentable for ListNumberedAligned<P0, P1> where P0: Presentable, P1: Presentable, { async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> where PR: Presenter<'output>, { presenter.list_numbered_aligned(&self.0).await } } impl<P0, P1> From<Vec<(P0, P1)>> for ListNumberedAligned<P0, P1> where P0: Presentable, P1: Presentable, { fn from(presentables: Vec<(P0, P1)>) -> Self { Self(presentables) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/fmt/src/presentable/heading.rs
crate/fmt/src/presentable/heading.rs
use serde::{Deserialize, Serialize}; use crate::{presentable::HeadingLevel, Presentable, Presenter}; /// Presents the given string as a heading. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct Heading<P> { /// Level of conceptual detail for a given topic. level: HeadingLevel, /// The heading level. presentable: P, } impl<P> Heading<P> { /// Returns a new `Heading` wrapper. pub fn new(level: HeadingLevel, presentable: P) -> Self { Self { level, presentable } } } #[async_trait::async_trait(?Send)] impl<P> Presentable for Heading<P> where P: Presentable, { async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> where PR: Presenter<'output>, { presenter.heading(self.level, &self.presentable).await } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/fmt/src/presentable/tuple_impl.rs
crate/fmt/src/presentable/tuple_impl.rs
use crate::{Presentable, Presenter}; #[async_trait::async_trait(?Send)] impl<T0> Presentable for (T0,) where T0: Presentable, { async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> where PR: Presenter<'output>, { self.0.present(presenter).await?; Ok(()) } } macro_rules! tuple_presentable_impl { (($($Tn:ident),+), [$($n:tt),+]) => { #[async_trait::async_trait(?Send)] impl<$($Tn),+> Presentable for ($($Tn),+) where $($Tn: Presentable),+ { async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> where PR: Presenter<'output>, { $(self.$n.present(presenter).await?;)+ Ok(()) } } }; } tuple_presentable_impl!((T0, T1), [0, 1]); tuple_presentable_impl!((T0, T1, T2), [0, 1, 2]); tuple_presentable_impl!((T0, T1, T2, T3), [0, 1, 2, 3]); tuple_presentable_impl!((T0, T1, T2, T3, T4), [0, 1, 2, 3, 4]); tuple_presentable_impl!((T0, T1, T2, T3, T4, T5), [0, 1, 2, 3, 4, 5]); tuple_presentable_impl!((T0, T1, T2, T3, T4, T5, T6), [0, 1, 2, 3, 4, 5, 6]); tuple_presentable_impl!((T0, T1, T2, T3, T4, T5, T6, T7), [0, 1, 2, 3, 4, 5, 6, 7]); tuple_presentable_impl!( (T0, T1, T2, T3, T4, T5, T6, T7, T8), [0, 1, 2, 3, 4, 5, 6, 7, 8] ); tuple_presentable_impl!( (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ); tuple_presentable_impl!( (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ); tuple_presentable_impl!( (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] ); tuple_presentable_impl!( (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] ); tuple_presentable_impl!( (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] ); tuple_presentable_impl!( (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] ); tuple_presentable_impl!( (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] );
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/fmt/src/presentable/list_bulleted_aligned.rs
crate/fmt/src/presentable/list_bulleted_aligned.rs
use serde::{Deserialize, Serialize}; use crate::{Presentable, Presenter}; /// Presents the given iterator as an aligned bulleted list. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct ListBulletedAligned<P0, P1>(Vec<(P0, P1)>); impl<P0, P1> ListBulletedAligned<P0, P1> { /// Returns a new `ListBulletedAligned` wrapper. pub fn new(presentables: Vec<(P0, P1)>) -> Self { Self(presentables) } } #[async_trait::async_trait(?Send)] impl<P0, P1> Presentable for ListBulletedAligned<P0, P1> where P0: Presentable, P1: Presentable, { async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> where PR: Presenter<'output>, { presenter.list_bulleted_aligned(&self.0).await } } impl<P0, P1> From<Vec<(P0, P1)>> for ListBulletedAligned<P0, P1> where P0: Presentable, P1: Presentable, { fn from(presentables: Vec<(P0, P1)>) -> Self { Self(presentables) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/fmt/src/presentable/bold.rs
crate/fmt/src/presentable/bold.rs
use serde::{Deserialize, Serialize}; use crate::{Presentable, Presenter}; /// Presents the given presentable as bolded. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct Bold<P>(P); impl<P> Bold<P> { /// Returns a new `Bold` wrapper. pub fn new(presentable: P) -> Self { Self(presentable) } } #[async_trait::async_trait(?Send)] impl<P> Presentable for Bold<P> where P: Presentable, { async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> where PR: Presenter<'output>, { presenter.bold(&self.0).await } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/fmt/src/presentable/code_inline.rs
crate/fmt/src/presentable/code_inline.rs
use std::borrow::Cow; use serde::{Deserialize, Serialize}; use crate::{Presentable, Presenter}; /// Presents the given string as inline code. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct CodeInline<'s>(Cow<'s, str>); impl<'s> CodeInline<'s> { /// Returns a new `Code` wrapper. pub fn new(s: Cow<'s, str>) -> Self { Self(s) } } #[async_trait::async_trait(?Send)] impl Presentable for CodeInline<'_> { async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> where PR: Presenter<'output>, { presenter.code_inline(&self.0).await } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/fmt/src/presentable/list_bulleted.rs
crate/fmt/src/presentable/list_bulleted.rs
use serde::{Deserialize, Serialize}; use crate::{Presentable, Presenter}; /// Presents the given iterator as a bulleted list. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct ListBulleted<P>(Vec<P>); impl<P> ListBulleted<P> { /// Returns a new `ListBulleted` wrapper. pub fn new(presentables: Vec<P>) -> Self { Self(presentables) } } #[async_trait::async_trait(?Send)] impl<P> Presentable for ListBulleted<P> where P: Presentable, { async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> where PR: Presenter<'output>, { presenter.list_bulleted(&self.0).await } } impl<P> From<Vec<P>> for ListBulleted<P> where P: Presentable, { fn from(presentables: Vec<P>) -> Self { Self(presentables) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/profile_model/src/lib.rs
crate/profile_model/src/lib.rs
//! Serializable data model for profiles for the Peace framework. pub use peace_static_check_macros::profile; pub use crate::profile::{Profile, ProfileInvalidFmt}; mod profile;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/profile_model/src/profile.rs
crate/profile_model/src/profile.rs
use std::borrow::Cow; use serde::{Deserialize, Serialize}; /// Identifier or namespace to distinguish execution environments. /// /// Example suitable identifiers are: /// /// * `"dev_user1"` /// * `"dev_user2"` /// * `"prod_customer1"` /// /// Must begin with a letter or underscore, and contain only letters, numbers, /// and underscores. /// /// # Examples /// /// The following are all examples of valid `Profile`s: /// /// ```rust /// # use peace_profile_model::{profile, Profile}; /// # /// let _snake = profile!("snake_case"); /// let _camel = profile!("camelCase"); /// let _pascal = profile!("PascalCase"); /// ``` #[derive(Clone, Debug, Hash, PartialEq, Eq, Deserialize, Serialize, PartialOrd, Ord)] pub struct Profile(Cow<'static, str>); peace_core::id_newtype!(Profile, ProfileInvalidFmt, profile, tag);
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/core/src/lib.rs
crate/core/src/lib.rs
//! Low level data types for the peace automation framework. //! //! This crate exists because: //! //! * `peace_cfg` has a dependency on `peace_resource_rt` for `Resources`, used //! in `Item::setup`. //! * `peace_resource_rt` has a dependency on `ItemId`, as uses `TypeMap<ItemId, //! _>` for the `States` maps. //! //! When [peace#67] is implemented, the `progress` module can be moved out //! of `peace_core` into `peace_cfg`. //! //! [peace#67]: https://github.com/azriel91/peace/issues/67 pub extern crate id_newtype; // Re-exports // needed for dependencies' usage of our `id_newtype` macro to resolve pub use peace_fmt; pub use peace_static_check_macros::{app_name, profile}; pub use crate::app_name::{AppName, AppNameInvalidFmt}; mod app_name; /// Implements common behaviour for an ID type. /// /// The implemented behaviour includes: /// /// * `IdType::new` /// * `IdType::new_unchecked` /// * `IdType::is_valid_id` /// * `std::ops::Deref` /// * `std::ops::DerefMut` /// * `std::fmt::Display` /// * `std::str::FromStr` /// * `TryFrom<String>` /// * `TryFrom<&'static str>` /// * `peace_fmt::Presentable` /// /// A separate error type is also generated, which indicates an invalid value /// when the ID type is instantiated with `new`. /// /// # Usage /// /// ```rust /// use std::borrow::Cow; /// /// // replace this with your ID type's macro /// use peace_static_check_macros::my_id_type; /// use serde::{Deserialize, Serialize}; /// /// // Rename your ID type /// #[derive(Clone, Debug, Hash, PartialEq, Eq, Deserialize, Serialize)] /// pub struct MyIdType(Cow<'static, str>); /// /// crate::core_id_newtype!( /// MyIdType, // Name of the ID type /// MyIdTypeInvalidFmt, // Name of the invalid value error /// my_id_type, // Name of the static check macro /// tag, // The `peace_fmt::Presentable` method to style the ID /// ); /// ``` #[macro_export] macro_rules! id_newtype { ($ty_name:ident, $ty_err_name:ident, $macro_name:ident, $presentable_method:ident) => { use $crate::id_newtype::id_newtype; $crate::id_newtype::id_newtype!($ty_name, $ty_err_name, $macro_name); #[$crate::peace_fmt::async_trait(?Send)] impl $crate::peace_fmt::Presentable for $ty_name { async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error> where PR: $crate::peace_fmt::Presenter<'output>, { presenter.$presentable_method(self.as_str()).await } } }; }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/core/src/app_name.rs
crate/core/src/app_name.rs
use std::borrow::Cow; use serde::{Deserialize, Serialize}; /// Name of the application that is run by end users. /// /// This is usually the crate name of the final binary. It needs to be passed in /// from the executable crate, as it is not possible for Peace to detect it /// within the library itself. /// /// Must begin with a letter or underscore, and contain only letters, numbers, /// and underscores. /// /// # Examples /// /// The following are all examples of valid `AppName`s: /// /// ```rust /// # use peace_core::{app_name, AppName}; /// # /// let _default = app_name!(); // defaults to calling crate name /// let _snake = app_name!("snake_case"); /// let _camel = app_name!("camelCase"); /// let _pascal = app_name!("PascalCase"); /// ``` #[derive(Clone, Debug, Hash, PartialEq, Eq, Deserialize, Serialize)] pub struct AppName(Cow<'static, str>); crate::id_newtype!(AppName, AppNameInvalidFmt, app_name, name);
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cli/src/lib.rs
crate/cli/src/lib.rs
//! Command line interface for the peace automation framework. //! //! This is enabled though the `"cli"` feature on the `peace` crate. pub mod output;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cli/src/output.rs
crate/cli/src/output.rs
pub use self::{ cli_colorize::CliColorize, cli_colorize_opt::CliColorizeOpt, cli_colorize_parse_error::CliColorizeOptParseError, cli_md_presenter::CliMdPresenter, cli_output::CliOutput, cli_output_builder::CliOutputBuilder, cli_output_target::CliOutputTarget, }; mod cli_colorize; mod cli_colorize_opt; mod cli_colorize_parse_error; mod cli_md_presenter; mod cli_output; mod cli_output_builder; mod cli_output_target; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { pub use self::{ cli_progress_format::CliProgressFormat, cli_progress_format_opt::CliProgressFormatOpt, cli_progress_format_opt_parse_error::CliProgressFormatOptParseError, }; mod cli_progress_format; mod cli_progress_format_opt; mod cli_progress_format_opt_parse_error; } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cli/src/output/cli_progress_format_opt.rs
crate/cli/src/output/cli_progress_format_opt.rs
use std::str::FromStr; use crate::output::CliProgressFormatOptParseError; /// How to format progress on the CLI. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CliProgressFormatOpt { /// Automatically detect whether to render a progress bar or the outcome /// format. Auto, /// Render progress in the same format as the outcome. Outcome, /// Always render progress as a progress bar. ProgressBar, /// Don't render progress. None, } impl FromStr for CliProgressFormatOpt { type Err = CliProgressFormatOptParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "auto" => Ok(Self::Auto), "outcome" => Ok(Self::Outcome), "pb" | "progress_bar" => Ok(Self::ProgressBar), "none" => Ok(Self::None), _ => Err(CliProgressFormatOptParseError(s.to_string())), } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cli/src/output/cli_colorize.rs
crate/cli/src/output/cli_colorize.rs
/// Whether or not to render output with ANSI colour codes. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CliColorize { /// Render the output with ANSI colour codes. Colored, /// Render the output without ANSI colour codes. Uncolored, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cli/src/output/cli_colorize_opt.rs
crate/cli/src/output/cli_colorize_opt.rs
use std::str::FromStr; use crate::output::CliColorizeOptParseError; /// Whether to colourize output using ANSI codes on the CLI. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum CliColorizeOpt { /// Automatically detect whether to colourize the output. #[default] Auto, /// Always colourize the output. Always, /// Never colourize the output. Never, } impl FromStr for CliColorizeOpt { type Err = CliColorizeOptParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "auto" => Ok(Self::Auto), "always" => Ok(Self::Always), "never" => Ok(Self::Never), _ => Err(CliColorizeOptParseError(s.to_string())), } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cli/src/output/cli_progress_format.rs
crate/cli/src/output/cli_progress_format.rs
/// How to format progress on the CLI. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CliProgressFormat { /// Render progress in the same format as the outcome. Outcome, /// Always render progress as a progress bar. ProgressBar, /// Don't render progress. None, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cli/src/output/cli_output_builder.rs
crate/cli/src/output/cli_output_builder.rs
use std::io::IsTerminal; use peace_cli_model::OutputFormat; use tokio::io::{AsyncWrite, Stdout}; use crate::output::{CliColorize, CliColorizeOpt, CliOutput}; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { use crate::output::{CliOutputTarget, CliProgressFormatOpt, CliProgressFormat}; } } /// An `OutputWrite` implementation that writes to the command line. /// /// # Features /// /// ## `"output_progress"` /// /// When this feature is enabled, progress is written to `stderr` by default. /// /// By default, when the progress stream is a terminal (i.e. not piped to /// another process, or redirected to a file), then the progress output format /// is a progress bar. /// /// If it is piped to another process or redirected to a file, then the progress /// output format defaults to the same format at the outcome output format -- /// text, YAML, or JSON. /// /// These defaults may be overridden through the [`with_progress_target`] and /// [`with_progress_format`] methods. /// /// # Implementation Note /// /// `indicatif`'s internal writing to `stdout` / `stderr` is used, which is /// sync. I didn't figure out how to write the in-memory term contents to the /// `W` writer correctly. /// /// [`with_colorized`]: Self::with_colorized /// [`with_progress_format`]: Self::with_progress_format /// [`with_progress_target`]: Self::with_progress_target #[derive(Debug)] pub struct CliOutputBuilder<W> { /// Output stream to write the command outcome to. writer: W, /// How to format outcome output -- human readable or machine parsable. outcome_format: OutputFormat, /// Whether output should be colorized. colorize: CliColorizeOpt, /// Where to output progress updates to -- stdout or stderr. #[cfg(feature = "output_progress")] progress_target: CliOutputTarget, /// How to format progress output -- progress bar or mimic outcome format. /// /// This is detected on instantiation. #[cfg(feature = "output_progress")] progress_format: CliProgressFormatOpt, } impl CliOutputBuilder<Stdout> { /// Returns a new `CliOutputBuilder`. /// /// This uses: /// /// * `io::stdout()` as the outcome output stream. /// * `io::stderr()` as the progress output stream if `"output_progress"` is /// enabled. pub fn new() -> Self { Self::default() } } impl<W> CliOutputBuilder<W> where W: AsyncWrite + std::marker::Unpin, { /// Returns a new `CliOutput` using `io::stdout()` as the output stream. /// /// # Examples /// /// ```rust /// # use peace_rt_model_native::output::CliOutput; /// // use peace::rt_model::output::CliOutputBuilder; /// /// let mut buffer = Vec::<u8>::new(); /// let cli_output = CliOutputBuilder::new_with_writer(&mut buffer).build(); /// ``` pub fn new_with_writer(writer: W) -> Self { Self { writer, outcome_format: OutputFormat::Text, colorize: CliColorizeOpt::Auto, #[cfg(feature = "output_progress")] progress_target: CliOutputTarget::default(), #[cfg(feature = "output_progress")] progress_format: CliProgressFormatOpt::Auto, } } /// Returns how to format outcome output -- human readable or machine /// parsable. pub fn outcome_format(&self) -> OutputFormat { self.outcome_format } /// Returns whether output should be colorized. pub fn colorize(&self) -> CliColorizeOpt { self.colorize } /// Returns where to output progress updates to -- stdout or stderr. /// /// If the `"output_in_memory"` feature is enabled, there is a third /// `InMemory` variant that holds the buffer for progress output. This /// variant is intended to be used for verifying output in tests. #[cfg(feature = "output_progress")] pub fn progress_target(&self) -> &CliOutputTarget { &self.progress_target } /// Returns how to format progress output -- progress bar or mimic outcome /// format. #[cfg(feature = "output_progress")] pub fn progress_format(&self) -> CliProgressFormatOpt { self.progress_format } /// Sets the outcome output format for this `CliOutput`. /// /// # Examples /// /// ```rust /// # use peace_rt_model_core::output::OutputFormat; /// # use peace_rt_model_native::output::CliOutput; /// // use peace::rt_model::output::{CliOutput, OutputFormat}; /// /// let cli_output = CliOutput::builder().with_outcome_format(OutputFormat::Yaml); /// ``` pub fn with_outcome_format(mut self, output_format: OutputFormat) -> Self { self.outcome_format = output_format; self } /// Enables colorized output. /// /// # Examples /// /// ```rust /// # use peace_rt_model_native::output::CliOutput; /// // use peace::rt_model::output::{CliColorize, CliOutput}; /// /// let cli_output = CliOutput::new().with_colorized(CliColorize::Auto); /// ``` pub fn with_colorize(mut self, colorize: CliColorizeOpt) -> Self { self.colorize = colorize; self } /// Sets the progress output target -- stdout or stderr (default). #[cfg(feature = "output_progress")] pub fn with_progress_target(mut self, progress_target: CliOutputTarget) -> Self { self.progress_target = progress_target; self } /// Sets the progress output format. #[cfg(feature = "output_progress")] pub fn with_progress_format(mut self, progress_format: CliProgressFormatOpt) -> Self { self.progress_format = progress_format; self } /// Builds and returns the `CliOutput`. pub fn build(self) -> CliOutput<W> { let CliOutputBuilder { writer, outcome_format, colorize, #[cfg(feature = "output_progress")] progress_target, #[cfg(feature = "output_progress")] progress_format, } = self; let colorize = match colorize { CliColorizeOpt::Auto => { // Even though we're using `tokio::io::stdout` / `stderr`, `IsTerminal` is only // implemented on `std::io::stdout` / `stderr`. // // TODO: This should really determine this based on `W`, but: // // * We cannot easily tell if we are using `stdout`, `stderr`, or some arbitrary // thing. // * We *could* implement a function per `CliOutputBuilder<Stdout>` or // `CliOutputBuilder<Stderr>`, but then we're missing it for arbitrary `W`s. // * If we take in a `CliOutputTarget` for outcome output instead of `W`, then // we cannot pass in an arbitrary `AsyncWrite`. // * If we extend `CliOutputTarget` to support any `W`, that variant will no // longer be compatible with the progress output, handled by `indicatif`. // * We *could* add another enum just like `CliOutputTarget`, with the // additional variant. if std::io::stdout().is_terminal() { CliColorize::Colored } else { CliColorize::Uncolored } } CliColorizeOpt::Always => CliColorize::Colored, CliColorizeOpt::Never => CliColorize::Uncolored, }; #[cfg(feature = "output_progress")] let progress_format = { let progress_format = match progress_format { CliProgressFormatOpt::Auto => { // Even though we're using `tokio::io::stdout` / `stderr`, `IsTerminal` is only // implemented on `std::io::stdout` / `stderr`. match &progress_target { CliOutputTarget::Stdout => { if std::io::stdout().is_terminal() { CliProgressFormat::ProgressBar } else { CliProgressFormat::Outcome } } CliOutputTarget::Stderr => { if std::io::stderr().is_terminal() { CliProgressFormat::ProgressBar } else { CliProgressFormat::Outcome } } #[cfg(feature = "output_in_memory")] CliOutputTarget::InMemory(_) => CliProgressFormat::ProgressBar, } } CliProgressFormatOpt::Outcome => CliProgressFormat::Outcome, CliProgressFormatOpt::ProgressBar => CliProgressFormat::ProgressBar, CliProgressFormatOpt::None => CliProgressFormat::None, }; match (progress_format, outcome_format) { (CliProgressFormat::Outcome, OutputFormat::None) => CliProgressFormat::None, _ => progress_format, } }; // We need to suppress the `^C\n` characters that come through the terminal. // // This is a combination of reading the following: // // * <https://stackoverflow.com/questions/42563400/hide-c-pressing-ctrl-c-in-c> // * <https://docs.rs/libc/latest/libc/constant.ECHOCTL.html> // * <https://docs.rs/raw_tty/0.1.0/raw_tty/struct.TtyWithGuard.html> // // Also considered were: // // * [`uu_stty`](https://crates.io/crates/uu_stty)], but it doesn't look like it // supports modifying the terminal. // * [`unix_tty`](https://docs.rs/unix-tty/0.3.4/unix_tty/), which looks like it // can do the job, but `raw_tty` has a drop guard to restore the original tty // settings. #[cfg(unix)] let stdin_tty_with_guard = { use raw_tty::GuardMode; match std::io::stdin().guard_mode() { Ok(mut stdin_tty_with_guard) => { let mode_modify_result = stdin_tty_with_guard.modify_mode(|mut ios| { ios.c_lflag &= !libc::ECHOCTL; ios }); match mode_modify_result { Ok(()) => {} Err(error) => { #[cfg(debug_assertions)] eprintln!("warn: Failed to modify termios mode:\n{error}"); } } Some(stdin_tty_with_guard) } Err(error) => { #[cfg(debug_assertions)] eprintln!("warn: Failed to acquire stdin termios:\n{error}"); None } } }; #[cfg(feature = "error_reporting")] let report_handler = match colorize { CliColorize::Colored => { miette::GraphicalReportHandler::new().with_theme(miette::GraphicalTheme::unicode()) } CliColorize::Uncolored => miette::GraphicalReportHandler::new() .with_theme(miette::GraphicalTheme::unicode_nocolor()), }; CliOutput { writer, outcome_format, colorize, #[cfg(feature = "output_progress")] progress_target, #[cfg(feature = "output_progress")] progress_format, #[cfg(feature = "output_progress")] pb_item_id_width: None, #[cfg(unix)] stdin_tty_with_guard, #[cfg(feature = "error_reporting")] report_handler, } } } impl Default for CliOutputBuilder<Stdout> { fn default() -> Self { let stdout = tokio::io::stdout(); Self { writer: stdout, outcome_format: OutputFormat::Text, colorize: CliColorizeOpt::Auto, #[cfg(feature = "output_progress")] progress_target: CliOutputTarget::default(), #[cfg(feature = "output_progress")] progress_format: CliProgressFormatOpt::Auto, } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cli/src/output/cli_colorize_parse_error.rs
crate/cli/src/output/cli_colorize_parse_error.rs
use std::fmt; /// Failed to parse CLI colorize from string. #[derive(Clone, Debug, PartialEq, Eq)] pub struct CliColorizeOptParseError(pub String); impl fmt::Display for CliColorizeOptParseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "Failed to parse CLI colorize from string: `\"{}\"`.\n\ Valid values are [\"auto\", \"always\", \"never\"]", self.0 ) } } impl std::error::Error for CliColorizeOptParseError {}
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cli/src/output/cli_output.rs
crate/cli/src/output/cli_output.rs
#[cfg(unix)] use std::fmt; use std::fmt::Debug; use peace_cli_model::OutputFormat; use peace_fmt::Presentable; use peace_rt_model_core::{async_trait, output::OutputWrite, Error, NativeError}; use serde::Serialize; use tokio::io::{AsyncWrite, AsyncWriteExt, Stdout}; use crate::output::{CliColorize, CliMdPresenter, CliOutputBuilder}; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { use peace_item_model::ItemId; use peace_item_interaction_model::ItemLocationState; use peace_progress_model::{ CmdBlockItemInteractionType, ProgressComplete, ProgressLimit, ProgressStatus, ProgressTracker, ProgressUpdate, ProgressUpdateAndId, }; use peace_rt_model_core::{ indicatif::{ProgressDrawTarget, ProgressStyle}, CmdProgressTracker, }; use crate::output::{CliOutputTarget, CliProgressFormat}; } } /// An `OutputWrite` implementation that writes to the command line. /// /// # Features /// /// ## `"output_progress"` /// /// When this feature is enabled, progress is written to `stderr` by default. /// /// By default, when the progress stream is a terminal (i.e. not piped to /// another process, or redirected to a file), then the progress output format /// is a progress bar. /// /// If it is piped to another process or redirected to a file, then the progress /// output format defaults to the same format at the outcome output format -- /// text, YAML, or JSON. /// /// These defaults may be overridden through the [`with_progress_target`] and /// [`with_progress_format`] methods. /// /// # Implementation Note /// /// `indicatif`'s internal writing to `stdout` / `stderr` is used for rendering /// progress bars, which uses sync Rust. I didn't figure out how to write the /// in-memory term contents to the `W` writer correctly. /// /// [`with_colorized`]: CliOutputBuilder::with_colorized /// [`with_progress_format`]: CliOutputBuilder::with_progress_format /// [`with_progress_target`]: CliOutputBuilder::with_progress_target #[cfg_attr(not(unix), derive(Debug))] pub struct CliOutput<W> { /// Output stream to write the command outcome to. pub(crate) writer: W, /// How to format command outcome output -- human readable or machine /// parsable. pub(crate) outcome_format: OutputFormat, /// Whether output should be colorized. pub(crate) colorize: CliColorize, #[cfg(feature = "output_progress")] /// Where to output progress updates to -- stdout or stderr. pub(crate) progress_target: CliOutputTarget, /// Whether the writer is an interactive terminal. /// /// This is detected on instantiation. #[cfg(feature = "output_progress")] pub(crate) progress_format: CliProgressFormat, /// Width of the item ID column for progress bars #[cfg(feature = "output_progress")] pub(crate) pb_item_id_width: Option<usize>, /// The TTY guard that restores the terminal mode when `CliOutput` is /// dropped. /// /// This is used to suppress control character echo, e.g. `SIGINT` rendering /// `^C\n`. #[cfg(unix)] pub(crate) stdin_tty_with_guard: Option<raw_tty::TtyWithGuard<std::io::Stdin>>, /// The `miette::GraphicalReportHandler` to format errors nicely. #[cfg(feature = "error_reporting")] pub(crate) report_handler: miette::GraphicalReportHandler, } #[cfg(unix)] impl<W> Debug for CliOutput<W> where W: Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut debug_struct = f.debug_struct("CliOutput"); debug_struct .field("writer", &self.writer) .field("outcome_format", &self.outcome_format) .field("colorize", &self.colorize); #[cfg(feature = "output_progress")] { debug_struct .field("progress_target", &self.progress_target) .field("progress_format", &self.progress_format) .field("pb_item_id_width", &self.pb_item_id_width); } debug_struct.field( "stdin_tty_with_guard", if self.stdin_tty_with_guard.is_some() { &Some(..) } else { &None::<()> }, ); debug_struct.finish() } } impl CliOutput<Stdout> { /// Returns a new `CliOutput`. /// /// This uses: /// /// * `io::stdout()` as the outcome output stream. /// * `io::stderr()` as the progress output stream if `"output_progress"` is /// enabled. pub fn new() -> Self { Self::default() } /// Returns a new `CliOutputBuilder`. /// /// The builder allows additional options to be configured, such as forcing /// colorized output, outcome output format, and progress format. pub fn builder() -> CliOutputBuilder<Stdout> { CliOutputBuilder::new() } } /// This is used when we are rendering a bar that is not calculated by /// `ProgressBar`'s length and current value, #[cfg(feature = "output_progress")] const BAR_EMPTY: &str = "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±"; #[cfg(feature = "output_progress")] const BAR_FULL: &str = "β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°"; #[cfg(feature = "output_progress")] const SPINNER_EMPTY: &str = "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±"; #[cfg(feature = "output_progress")] const SPINNER_FULL: &str = "β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°β–°"; impl<W> CliOutput<W> where W: AsyncWrite + std::marker::Unpin, { /// Returns a new `CliOutput` using the given writer for the output stream. /// /// # Examples /// /// ```rust /// # use peace_rt_model_native::CliOutput; /// // use peace::rt_model::CliOutput; /// /// let mut buffer = Vec::<u8>::new(); /// let cli_output = CliOutput::new_with_writer(&mut buffer); /// ``` pub fn new_with_writer(writer: W) -> Self { CliOutputBuilder::new_with_writer(writer).build() } /// Returns a reference to the held writer. pub fn writer(&self) -> &W { &self.writer } /// Returns a mutable reference to the held writer. pub fn writer_mut(&mut self) -> &mut W { &mut self.writer } /// Returns how to format outcome output -- human readable or machine /// parsable. pub fn outcome_format(&self) -> OutputFormat { self.outcome_format } /// Returns whether output should be colorized. pub fn colorize(&self) -> CliColorize { self.colorize } /// Returns where to output progress updates to -- stdout or stderr. /// /// If the `"output_in_memory"` feature is enabled, there is a third /// `InMemory` variant that holds the buffer for progress output. This /// variant is intended to be used for verifying output in tests. #[cfg(feature = "output_progress")] pub fn progress_target(&self) -> &CliOutputTarget { &self.progress_target } /// Returns how to format progress output -- progress bar or mimic outcome /// format. #[cfg(feature = "output_progress")] pub fn progress_format(&self) -> CliProgressFormat { self.progress_format } async fn output_presentable<P>(&mut self, presentable: P) -> Result<(), Error> where P: Presentable, { let presenter = &mut CliMdPresenter::new(self); presentable .present(presenter) .await .map_err(NativeError::CliOutputPresent) .map_err(Error::Native)?; self.writer .flush() .await .map_err(NativeError::CliOutputPresent) .map_err(Error::Native)?; Ok(()) } async fn output_yaml<T, F>(&mut self, t: &T, fn_error: F) -> Result<(), Error> where T: Serialize + ?Sized, F: FnOnce(serde_yaml::Error) -> Error, { let t_serialized = serde_yaml::to_string(t).map_err(fn_error)?; self.writer .write_all(t_serialized.as_bytes()) .await .map_err(NativeError::StdoutWrite) .map_err(Error::Native)?; Ok(()) } async fn output_json<T, F>(&mut self, t: &T, fn_error: F) -> Result<(), Error> where T: Serialize + ?Sized, F: FnOnce(serde_json::Error) -> Error, { let t_serialized = serde_json::to_string(t).map_err(fn_error)?; self.writer .write_all(t_serialized.as_bytes()) .await .map_err(NativeError::StdoutWrite) .map_err(Error::Native)?; Ok(()) } #[cfg(feature = "output_progress")] fn progress_bar_style_update(&self, progress_tracker: &ProgressTracker) { let template = self.progress_bar_template(progress_tracker); let progress_bar = progress_tracker.progress_bar(); progress_bar.set_style( ProgressStyle::with_template(template.as_str()) .unwrap_or_else(|error| { panic!( "`ProgressStyle` template was invalid. Template: `{template:?}`. Error: {error}" ) }) .progress_chars("β–°β–±") .tick_strings(&[ SPINNER_EMPTY, "β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°β–±", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°β–°", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°β–°", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°β–°", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°β–°", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°β–°", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°β–°", "β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–±β–°", SPINNER_FULL, ]), ); // Rerender the progress bar after setting style. progress_bar.tick(); } #[cfg(feature = "output_progress")] fn progress_bar_template(&self, progress_tracker: &ProgressTracker) -> String { let icon = match progress_tracker.progress_status() { ProgressStatus::Initialized => "⚫", ProgressStatus::ExecPending => "βšͺ", ProgressStatus::Queued => "🟣", ProgressStatus::Running => "πŸ”΅", ProgressStatus::Interrupted => "🟑", ProgressStatus::RunningStalled => "🐒", ProgressStatus::UserPending => "πŸ‘€", ProgressStatus::Complete(ProgressComplete::Success) => "βœ…", ProgressStatus::Complete(ProgressComplete::Fail) => "❌", }; // These are used to tell `indicatif` how to style the computed bar. // // 40: width // // 32: blue pale (running) // 17: blue dark (running background) // 208: yellow-orange (stalled) // 220: yellow (interrupted) // 75: indigo pale (user pending, item id) // 35: green pale (success) // 22: green dark (success background) // 160: red slightly dim (fail) // 88: red dark (fail background) const BLUE_PALE: u8 = 32; const GRAY_DARK: u8 = 237; const GRAY_MED: u8 = 8; const GREEN_LIGHT: u8 = 35; const PURPLE: u8 = 128; const RED_DIM: u8 = 160; let bar_or_spinner = match self.colorize { CliColorize::Colored => { if progress_tracker.progress_limit().is_some() { // Colored, with progress limit match progress_tracker.progress_status() { ProgressStatus::Initialized => { console::style(BAR_EMPTY).color256(GRAY_DARK) } ProgressStatus::Interrupted => console::style("{bar:40.220}"), ProgressStatus::ExecPending | ProgressStatus::Queued | ProgressStatus::Running => console::style("{bar:40.32}"), ProgressStatus::RunningStalled => console::style("{bar:40.208}"), ProgressStatus::UserPending => console::style("{bar:40.75}"), ProgressStatus::Complete(progress_complete) => match progress_complete { // Ideally we just use `"{bar:40.35}"`, // and the `ProgressBar` renders the filled green bar. // // However, it's still rendered as blue because // the `ProgressBar` is abandoned before getting one // final render. ProgressComplete::Success => { console::style(BAR_FULL).color256(GREEN_LIGHT) } ProgressComplete::Fail => console::style("{bar:40.160}"), }, } } else { // Colored, no progress limit (as opposed to unknown) match progress_tracker.progress_status() { ProgressStatus::Initialized => { console::style(SPINNER_EMPTY).color256(GRAY_MED) } ProgressStatus::ExecPending | ProgressStatus::Queued => { console::style(SPINNER_EMPTY).color256(BLUE_PALE) } ProgressStatus::Running => console::style("{spinner:40.32}"), ProgressStatus::Interrupted => console::style("{spinner:40.220}"), ProgressStatus::RunningStalled => console::style("{spinner:40.208}"), ProgressStatus::UserPending => console::style("{spinner:40.75}"), ProgressStatus::Complete(progress_complete) => match progress_complete { // Ideally we just use `"{spinner:40.35}"`, // and the `ProgressBar` renders the filled green spinner. // However, for a spinner, it just renders it empty for some // reason. ProgressComplete::Success => { console::style(SPINNER_FULL).color256(GREEN_LIGHT) } ProgressComplete::Fail => { console::style(SPINNER_FULL).color256(RED_DIM) } }, } } } CliColorize::Uncolored => { if progress_tracker.progress_limit().is_some() { match progress_tracker.progress_status() { ProgressStatus::Initialized => console::style(BAR_EMPTY), ProgressStatus::Interrupted | ProgressStatus::ExecPending | ProgressStatus::Queued | ProgressStatus::Running | ProgressStatus::RunningStalled | ProgressStatus::UserPending | ProgressStatus::Complete(_) => console::style("{bar:40}"), } } else { console::style("{spinner:40}") } } }; let prefix_width = self.pb_item_id_width.unwrap_or(20); let prefix = format!("{{prefix:{prefix_width}}}"); let (progress_is_complete, completion_is_successful) = match progress_tracker.progress_status() { ProgressStatus::Complete(progress_complete) => { (true, progress_complete.is_successful()) } _ => (false, false), }; let units = if progress_is_complete && completion_is_successful { None } else { progress_tracker .progress_limit() .and_then(|progress_limit| match progress_limit { ProgressLimit::Unknown => None, ProgressLimit::Steps(_) => Some(" {pos}/{len}"), ProgressLimit::Bytes(_) => Some(" {bytes}/{total_bytes}"), }) }; let elapsed_eta = if progress_is_complete { None } else { let elapsed_eta = console::style("(el: {elapsed}, eta: {eta})"); match self.colorize { CliColorize::Colored => Some(elapsed_eta.color256(PURPLE)), CliColorize::Uncolored => Some(elapsed_eta), } }; // For showing `ProgressTracker` status for debugging: // // ```rust // // `fmt::Debug` doesn't support alignment, so we need to render the `Debug` string, // // then align it. // let progress_status = progress_tracker.progress_status(); // let progress_status = format!("{progress_status:?}"); // let mut format_str = format!("{icon} {progress_status:20} {prefix} {bar_or_spinner}"); // ``` // `prefix` is the item ID. let mut format_str = format!("{icon} {prefix} {bar_or_spinner}"); if let Some(units) = units { format_str.push_str(units); } if progress_tracker.message().is_some() { format_str.push_str(" {msg}"); } if let Some(elapsed_eta) = elapsed_eta { format_str.push_str(&format!(" {elapsed_eta}")); } format_str } } impl Default for CliOutput<Stdout> { fn default() -> Self { Self::builder().build() } } /// Outputs progress and `Presentable`s in either serialized or presentable /// form. #[async_trait(?Send)] impl<W> OutputWrite for CliOutput<W> where W: AsyncWrite + Debug + Unpin + 'static, { type Error = Error; #[cfg(feature = "output_progress")] async fn progress_begin(&mut self, cmd_progress_tracker: &CmdProgressTracker) { let progress_draw_target = match &self.progress_target { CliOutputTarget::Stdout => ProgressDrawTarget::stdout(), CliOutputTarget::Stderr => ProgressDrawTarget::stderr(), #[cfg(feature = "output_in_memory")] CliOutputTarget::InMemory(in_memory_term) => { ProgressDrawTarget::term_like(Box::new(in_memory_term.clone())) } }; // avoid reborrowing `self` within `for_each` let colorize = self.colorize; match self.progress_format { CliProgressFormat::ProgressBar => { cmd_progress_tracker .multi_progress() .set_draw_target(progress_draw_target); // TODO: test with multiple item IDs of varying length self.pb_item_id_width = { if cmd_progress_tracker.progress_trackers().is_empty() { Some(0) } else { let list_digit_width = { usize::checked_ilog10(cmd_progress_tracker.progress_trackers().len()) .and_then(|digit_width_u32| usize::try_from(digit_width_u32).ok()) .map(|digit_width| { let dot_width = 1; let space_width = 1; // +1 to cater for ilog10 rounding down digit_width + dot_width + space_width + 1 }) .unwrap_or(0) }; let item_id_width = cmd_progress_tracker.progress_trackers().iter().fold( 0, |pb_item_id_width, (item_id, _progress_tracker)| { std::cmp::max(item_id.len(), pb_item_id_width) }, ); Some(list_digit_width + item_id_width) } }; cmd_progress_tracker .progress_trackers() .iter() .enumerate() .for_each(|(index, (item_id, progress_tracker))| { let progress_bar = progress_tracker.progress_bar(); // Hack: colourization done in `progress_begin` to get // numerical index to be colorized. let index = index + 1; match colorize { CliColorize::Colored => { // white let index_colorized = console::Style::new() .color256(15) .apply_to(format!("{index}.")); // blue let item_id_colorized = console::Style::new() .color256(75) .apply_to(format!("{item_id}")); progress_bar .set_prefix(format!("{index_colorized} {item_id_colorized}")); } CliColorize::Uncolored => { progress_bar.set_prefix(format!("{index}. {item_id}")); } } self.progress_bar_style_update(progress_tracker); // Hack: This should be done with a timer in `ApplyCmd`. // This uses threads, which is not WASM compatible. progress_bar.enable_steady_tick(std::time::Duration::from_millis(100)); }); } CliProgressFormat::Outcome => { cmd_progress_tracker .multi_progress() .set_draw_target(progress_draw_target); let progress_style = ProgressStyle::with_template("").unwrap_or_else(|error| { panic!("`ProgressStyle` template was invalid. Template: `\"\"`. Error: {error}") }); cmd_progress_tracker.progress_trackers().iter().for_each( |(item_id, progress_tracker)| { let progress_bar = progress_tracker.progress_bar(); progress_bar.set_prefix(format!("{item_id}")); progress_bar.set_style(progress_style.clone()); }, ); } CliProgressFormat::None => {} } } #[cfg(feature = "output_progress")] async fn cmd_block_start( &mut self, _cmd_block_item_interaction_type: CmdBlockItemInteractionType, ) { } #[cfg(feature = "output_progress")] async fn item_location_state( &mut self, _item_id: ItemId, _item_location_state: ItemLocationState, ) { } #[cfg(feature = "output_progress")] async fn progress_update( &mut self, progress_tracker: &ProgressTracker, progress_update_and_id: &ProgressUpdateAndId, ) { match self.progress_format { CliProgressFormat::ProgressBar => { // Don't need to write anything, as `indicatif` handles output // to terminal. // * Need to update progress bar colour on the first delta (grey to blue) // * Need to update progress bar colour on finish (blue to green) // * Need to update progress bar colour on error (blue to red) if let Some(message) = progress_tracker.message().cloned() { progress_tracker.progress_bar().set_message(message); } match &progress_update_and_id.progress_update { ProgressUpdate::Reset | ProgressUpdate::ResetToPending | ProgressUpdate::Queued => { self.progress_bar_style_update(progress_tracker); } ProgressUpdate::Interrupt => { self.progress_bar_style_update(progress_tracker); let progress_bar = progress_tracker.progress_bar(); progress_bar.abandon(); } ProgressUpdate::Limit(_progress_limit) => { // Note: `progress_tracker` also carries the `progress_limit` self.progress_bar_style_update(progress_tracker); } ProgressUpdate::Delta(_delta) => { // Status may have changed from `ExecPending` to // `Running`. // // We don't have the previous status though. // // TODO: Is this too much of a performance hit, and we send another message // for spinners? self.progress_bar_style_update(progress_tracker); } ProgressUpdate::Complete(progress_complete) => match progress_complete { ProgressComplete::Success => { self.progress_bar_style_update(progress_tracker); let progress_bar = progress_tracker.progress_bar(); progress_bar.finish(); } ProgressComplete::Fail => { self.progress_bar_style_update(progress_tracker); let progress_bar = progress_tracker.progress_bar(); progress_bar.abandon(); } }, } } CliProgressFormat::Outcome => { let progress_bar = progress_tracker.progress_bar(); match self.outcome_format {
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
true
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cli/src/output/cli_md_presenter.rs
crate/cli/src/output/cli_md_presenter.rs
use console::Style; use futures::stream::{self, TryStreamExt}; use peace_fmt::{async_trait, presentable::HeadingLevel, Presentable, Presenter}; use tokio::io::{AsyncWrite, AsyncWriteExt}; use crate::output::{CliColorize, CliOutput}; /// Command line markdown presenter. /// /// Formats `Presentable` data as markdown on the CLI. #[derive(Debug)] pub struct CliMdPresenter<'output, W> { /// The CLI output to write to. output: &'output mut CliOutput<W>, /// Whether to render text in ANSI bold. cli_bold: CliBold, } impl<'output, W> CliMdPresenter<'output, W> where W: AsyncWrite + std::marker::Unpin, { /// Returns a new `CliMdPresenter`. /// /// # Parameters /// /// * `output`: Output to write to. pub fn new(output: &'output mut CliOutput<W>) -> Self { Self { output, cli_bold: CliBold::default(), } } async fn colorize_maybe( &mut self, s: &str, style: &console::Style, ) -> Result<(), std::io::Error> { let colorize = self.output.colorize; let writer = &mut self.output.writer; if colorize == CliColorize::Colored { let s_colorized = style.apply_to(s); if self.cli_bold.is_bold() { let s_colorized_bolded = s_colorized.bold(); writer .write_all(format!("{s_colorized_bolded}").as_bytes()) .await?; } else { writer .write_all(format!("{s_colorized}").as_bytes()) .await?; } } else { writer.write_all(s.as_bytes()).await?; } Ok(()) } fn number_column_count<I>(iterator: &I) -> usize where I: Iterator, { let (min, max_maybe) = iterator.size_hint(); let n = max_maybe.unwrap_or(min); n.checked_ilog10() .and_then(|log10| usize::try_from(log10).ok()) .unwrap_or(0) + 1 } /// Pedantic: Don't highlight surrounding spaces with white. async fn colorize_list_number( &mut self, style: &console::Style, number_column_count: usize, list_number: usize, ) -> Result<(), std::io::Error> { let colorize = self.output.colorize; let writer = &mut self.output.writer; let list_number_digits = list_number .checked_ilog10() .and_then(|log10| usize::try_from(log10).ok()) .unwrap_or(0) + 1; let leading_space_count: usize = number_column_count.saturating_sub(list_number_digits); if colorize == CliColorize::Colored { let list_number_colorized = style.apply_to(format!("{list_number}.")); let leading_spaces = " ".repeat(leading_space_count); writer .write_all(format!("{leading_spaces}{list_number_colorized} ").as_bytes()) .await?; } else { let list_number_padded = format!("{list_number:>number_column_count$}. "); writer.write_all(list_number_padded.as_bytes()).await?; } Ok(()) } async fn list_aligned_with<'f, P0, P1, I, T, F>( &mut self, list_type: ListType, iter: I, f: F, ) -> Result<(), std::io::Error> where P0: Presentable + 'f, P1: Presentable + 'f, I: IntoIterator<Item = T>, T: 'f, F: Fn(T) -> &'f (P0, P1), { let iterator = iter.into_iter(); let number_column_count = Self::number_column_count(&iterator); let mut buffer = Vec::<u8>::with_capacity(256); let mut cli_output_in_memory = CliOutput::new_with_writer(&mut buffer); let mut width_buffer_presenter = CliMdPresenter::new(&mut cli_output_in_memory); // Render the first presentable of all items, so we can determine the maximum // width. let (entries, max_width, _width_buffer_presenter, _f) = stream::iter(iterator.map(Result::<_, std::io::Error>::Ok)) .try_fold( (Vec::new(), None, &mut width_buffer_presenter, f), |(mut entries, mut max_width, width_buffer_presenter, f), entry| async move { let (presentable_0, presentable_1) = f(entry); presentable_0.present(width_buffer_presenter).await?; let rendered_0 = &width_buffer_presenter.output.writer; let rendered_0_lossy = String::from_utf8_lossy(rendered_0); let width = console::measure_text_width(&rendered_0_lossy); width_buffer_presenter.output.writer.clear(); if let Some(current_max) = max_width { if current_max < width { max_width = Some(width); } } else { max_width = Some(width); } entries.push(((presentable_0, width), presentable_1)); Ok((entries, max_width, width_buffer_presenter, f)) }, ) .await?; let style_white = &console::Style::new().color256(15); // white let max_width = max_width.unwrap_or(0); let padding_bytes = " ".repeat(max_width); match list_type { ListType::Numbered => { for (index, ((presentable_0, presentable_0_width), presentable_1)) in entries.into_iter().enumerate() { self.list_number_write(style_white, index, number_column_count) .await?; self.list_aligned_item_write( max_width, &padding_bytes, presentable_0, presentable_0_width, presentable_1, ) .await?; } } ListType::Bulleted => { for ((presentable_0, presentable_0_width), presentable_1) in entries.into_iter() { self.list_bullet_write(style_white).await?; self.list_aligned_item_write( max_width, &padding_bytes, presentable_0, presentable_0_width, presentable_1, ) .await?; } } } Ok(()) } async fn list_aligned_item_write<P0, P1>( &mut self, max_width: usize, padding_bytes: &str, presentable_0: &P0, presentable_0_width: usize, presentable_1: &P1, ) -> Result<(), std::io::Error> where P0: Presentable, P1: Presentable, { presentable_0.present(self).await?; let padding = max_width.saturating_sub(presentable_0_width); if padding > 0 { self.output .writer .write_all(&padding_bytes.as_bytes()[0..padding]) .await?; } self.output.writer.write_all(b": ").await?; presentable_1.present(self).await?; self.output.writer.write_all(b"\n").await?; Ok(()) } async fn list_bullet_write(&mut self, style_white: &Style) -> Result<(), std::io::Error> { self.colorize_maybe("*", style_white).await?; self.output.writer.write_all(b" ").await?; Ok(()) } async fn list_number_write( &mut self, style_white: &Style, index: usize, number_column_count: usize, ) -> Result<(), std::io::Error> { let list_number = index + 1; self.colorize_list_number(style_white, number_column_count, list_number) .await?; Ok(()) } } #[async_trait(?Send)] impl<'output, W> Presenter<'output> for CliMdPresenter<'output, W> where W: AsyncWrite + std::marker::Unpin, { type Error = std::io::Error; async fn heading<P>( &mut self, heading_level: HeadingLevel, presentable: &P, ) -> Result<(), Self::Error> where P: Presentable + ?Sized, { let hash_style = &console::Style::new().bold().color256(243); // grey; let leading_hashes = match heading_level { HeadingLevel::Level1 => "#", HeadingLevel::Level2 => "##", HeadingLevel::Level3 => "###", HeadingLevel::Level4 => "####", HeadingLevel::Level5 => "#####", HeadingLevel::Level6 => "######", }; self.cli_bold.increment(); self.colorize_maybe(leading_hashes, hash_style).await?; self.output.writer.write_all(b" ").await?; presentable.present(self).await?; self.cli_bold.decrement(); self.output.writer.write_all(b"\n\n").await?; Ok(()) } async fn id(&mut self, id: &str) -> Result<(), Self::Error> { let style = console::Style::new().color256(75); // blue self.colorize_maybe(id, &style).await?; Ok(()) } async fn name(&mut self, name: &str) -> Result<(), Self::Error> { let style = console::Style::new().bold(); self.colorize_maybe(format!("**{name}**").as_str(), &style) .await?; Ok(()) } async fn text(&mut self, text: &str) -> Result<(), Self::Error> { let style = console::Style::new(); self.colorize_maybe(text, &style).await?; Ok(()) } async fn bold<P>(&mut self, presentable: &P) -> Result<(), Self::Error> where P: Presentable + ?Sized, { self.cli_bold.increment(); self.output.writer.write_all(b"**").await?; presentable.present(self).await?; self.output.writer.write_all(b"**").await?; self.cli_bold.decrement(); Ok(()) } async fn tag(&mut self, tag: &str) -> Result<(), Self::Error> { let style = &console::Style::new().color256(219).bold(); // purple self.colorize_maybe(format!("β¦—{tag}⦘").as_str(), style) .await?; Ok(()) } async fn code_inline(&mut self, code: &str) -> Result<(), Self::Error> { let style = &console::Style::new().color256(75); // pale blue self.colorize_maybe(format!("`{code}`").as_str(), style) .await?; Ok(()) } async fn list_numbered<'f, P, I>(&mut self, iter: I) -> Result<(), Self::Error> where P: Presentable + ?Sized + 'f, I: IntoIterator<Item = &'f P>, { self.list_numbered_with(iter, std::convert::identity).await } async fn list_numbered_with<'f, P, I, T, F>(&mut self, iter: I, f: F) -> Result<(), Self::Error> where P: Presentable, I: IntoIterator<Item = T>, T: 'f, F: Fn(T) -> P, { let iterator = iter.into_iter(); let number_column_count = Self::number_column_count(&iterator); for (index, entry) in iterator.enumerate() { let list_number = index + 1; let style = &console::Style::new().color256(15); // white self.colorize_list_number(style, number_column_count, list_number) .await?; let presentable = f(entry); presentable.present(self).await?; self.output.writer.write_all(b"\n").await?; } Ok(()) } async fn list_numbered_aligned<'f, P0, P1, I>(&mut self, iter: I) -> Result<(), Self::Error> where P0: Presentable + 'f, P1: Presentable + 'f, I: IntoIterator<Item = &'f (P0, P1)>, { self.list_numbered_aligned_with(iter, std::convert::identity) .await } async fn list_numbered_aligned_with<'f, P0, P1, I, T, F>( &mut self, iter: I, f: F, ) -> Result<(), Self::Error> where P0: Presentable + 'f, P1: Presentable + 'f, I: IntoIterator<Item = T>, T: 'f, F: Fn(T) -> &'f (P0, P1), { self.list_aligned_with(ListType::Numbered, iter, f).await } async fn list_bulleted<'f, P, I>(&mut self, iter: I) -> Result<(), Self::Error> where P: Presentable + ?Sized + 'f, I: IntoIterator<Item = &'f P>, { self.list_bulleted_with(iter, std::convert::identity).await } async fn list_bulleted_with<'f, P, I, T, F>(&mut self, iter: I, f: F) -> Result<(), Self::Error> where P: Presentable, I: IntoIterator<Item = T>, T: 'f, F: Fn(T) -> P, { for entry in iter.into_iter() { let style = &console::Style::new().color256(15); // white self.colorize_maybe("*", style).await?; self.output.writer.write_all(b" ").await?; let presentable = f(entry); presentable.present(self).await?; self.output.writer.write_all(b"\n").await?; } Ok(()) } async fn list_bulleted_aligned<'f, P0, P1, I>(&mut self, iter: I) -> Result<(), Self::Error> where P0: Presentable + 'f, P1: Presentable + 'f, I: IntoIterator<Item = &'f (P0, P1)>, { self.list_bulleted_aligned_with(iter, std::convert::identity) .await } async fn list_bulleted_aligned_with<'f, P0, P1, I, T, F>( &mut self, iter: I, f: F, ) -> Result<(), Self::Error> where P0: Presentable + 'f, P1: Presentable + 'f, I: IntoIterator<Item = T>, T: 'f, F: Fn(T) -> &'f (P0, P1), { self.list_aligned_with(ListType::Bulleted, iter, f).await } } /// Whether to render text in ANSI bold. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct CliBold(u32); impl CliBold { /// Returns whether the CLI text should be rendered as bold. fn is_bold(self) -> bool { self.0 > 0 } fn increment(&mut self) { self.0 = self.0.saturating_add(1); } fn decrement(&mut self) { self.0 = self.0.saturating_sub(1); } } #[derive(Clone, Copy, Debug)] enum ListType { Numbered, Bulleted, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cli/src/output/cli_progress_format_opt_parse_error.rs
crate/cli/src/output/cli_progress_format_opt_parse_error.rs
use std::fmt; /// Failed to parse CLI progress format from string. #[derive(Clone, Debug, PartialEq, Eq)] pub struct CliProgressFormatOptParseError(pub String); impl fmt::Display for CliProgressFormatOptParseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "Failed to parse CLI progress format from string: `\"{}\"`.\n\ Valid values are [\"auto\", \"outcome\", \"pb\", \"progress_bar\", \"none\"]", self.0 ) } } impl std::error::Error for CliProgressFormatOptParseError {}
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false