use anyhow::bail;
use colored::Colorize;
use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use crate::actions::patch::PatchAction;
use crate::actions::storage_add::AddToStorageAction;
use crate::actions::test::TestAction;
use crate::actions::{Action, DefinedAction, UsedAction};
use crate::bmap;
use crate::entities::ansible_opts::AnsibleOpts;
use crate::entities::auto_version::AutoVersionExtractFromRule;
use crate::entities::compose_opts::{ComposeOpts, ComposeServiceOpts};
use crate::entities::containered_opts::{
ContainerExecutor, ContaineredOpts, ContainerizedBuildStrategyStep, PortBinding,
};
use crate::entities::custom_command::CustomCommand;
use crate::entities::driver::PipelineDriver;
use crate::entities::github_cicd_opts::GitHubOpts;
use crate::entities::gitlab_cicd_opts::GitLabOpts;
use crate::entities::info::{ActionInfo, ContentInfo, PipelineInfo, ShortName};
use crate::entities::placements::Placement;
use crate::entities::remote_host::RemoteHost;
use crate::entities::requirements::Requirement;
use crate::entities::variables::{VarValue, Variable};
use crate::globals::DeployerGlobalConfig;
use crate::pipelines::DescribedPipeline;
use crate::project::DeployerProjectOptions;
use crate::tui::add::{collect_af_placement, collect_path, collect_regex, specify_cmd};
use crate::tui::utils::{CopyFn, CreateFn, EditFn};
use crate::utils::tags_custom_type;
impl DeployerProjectOptions {
pub async fn edit_from_prompt(&mut self, opts: &mut DeployerGlobalConfig) -> anyhow::Result<()> {
let actions = vec![
"Edit project actions",
"Edit project pipelines",
"Edit project variables",
"Setup variables for pipelines",
"Select default pipeline",
"Rename project",
"Edit cache files",
"Edit ignore files",
];
while let Some(action) =
inquire_reorder::Select::new("Select an edit action (or hit `esc`):", actions.clone()).prompt_skippable()?
{
match action {
"Rename project" => {
self.project_name = inquire_reorder::Text::new("Enter new project name:")
.with_initial_value(self.project_name.as_str())
.prompt()?
}
"Select default pipeline" => self.select_default_pipeline()?,
"Edit cache files" => edit_paths(&mut self.cache_files).await?,
"Edit ignore files" => edit_paths(&mut self.ignore_files).await?,
"Edit project variables" => {
crate::tui::utils::edit_btreemap_entities(
&mut self.variables,
None,
"Edit variables:",
|(k, _)| k.as_str().to_string(),
Some(async |item: &mut (ShortName, Variable)| item.1.edit_variable_from_prompt()),
Some(async || Variable::new_from_prompt()),
None::<CopyFn<(ShortName, Variable)>>,
)
.await?
}
"Edit project actions" => {
let actions_registry = opts.actions_registry.clone();
crate::tui::utils::edit_btreeset_entities(
&mut self.actions,
Some(&actions_registry),
"Edit project actions:",
|action| action.info.to_str(),
Some(async |action: &mut DefinedAction| action.edit_action_from_prompt(Some(opts)).await),
Some(async || DefinedAction::new_from_prompt(None)),
Some(async |old: &DefinedAction| {
let mut new = old.clone();
let info = inquire_reorder::Text::new("Specify the Action's short name and version:")
.with_placeholder("action-name@0.1.0")
.prompt()?;
let info = ActionInfo::try_from_str(&info)?;
new.info = info;
Ok(new)
}),
)
.await?;
}
"Edit project pipelines" => {
let mut reg_vals = vec![];
let registry = opts.pipelines_registry.clone();
let registry = crate::tui::utils::btreeset_registry_to_vec(&mut reg_vals, Some(®istry));
let mut opts_1 = opts.clone();
let actions = self.actions.clone();
crate::tui::utils::edit_entities(
&mut self.pipelines,
registry,
"Edit pipelines:",
|pipe| format!("{} - {}", pipe.info.to_str(), pipe.title),
Some(async |pipe: &mut DescribedPipeline| {
pipe
.edit_pipeline_from_prompt(
&mut opts.pipelines_registry,
&actions,
Some(&self.variables),
&opts.remote_hosts,
false,
)
.await
}),
Some(async || DescribedPipeline::new_from_prompt(&mut opts_1, &mut self.actions)),
Some(async |old: &DescribedPipeline| {
let mut new = old.clone();
let info = inquire_reorder::Text::new("Specify the Pipeline's short name and version:")
.with_placeholder("pipeline-name@0.1.0")
.prompt()?;
let info = PipelineInfo::try_from_str(&info)?;
new.info = info;
Ok(new)
}),
true,
)
.await?;
opts.actions_registry = opts_1.actions_registry;
}
"Setup variables for pipelines" => {
if self.variables.is_empty() {
println!("Please, specify variables for project first!");
let mut needed = vec![];
for pipeline in &self.pipelines {
for action in &pipeline.actions {
let definition = action.definition(&self.actions)?;
for var in definition.collect_required_variables() {
needed.push(format!(
"\t- variable `{var}` for pipeline `{}`, action `{}`",
pipeline.info.to_str(),
action.used.to_str()
));
}
}
}
println!("These variables are required:");
needed.iter().for_each(|v| println!("{v}"));
continue;
}
for pipeline in self.pipelines.as_mut_slice() {
for action in &mut pipeline.actions {
if let Ok(setup) = action.prompt_setup_for_project(&self.variables, &self.actions) {
*action = setup;
}
}
}
}
_ => unreachable!(),
}
}
Ok(())
}
pub fn select_default_pipeline(&mut self) -> anyhow::Result<()> {
match self.pipelines.len() {
0 => {
println!("Current project have no specified pipelines to select the default one.");
}
1 => {
let pipeline = self.pipelines.first_mut().unwrap();
pipeline.default = Some(true);
println!("Default pipeline is now: `{}`", pipeline.title.as_str());
}
_ => {
let mut cmap = bmap!();
let mut cs = vec![];
self.pipelines.iter_mut().for_each(|c| {
let s = format!("Pipeline `{}`", c.title);
cmap.insert(s.clone(), c);
cs.push(s);
});
if let Some(pipe) =
inquire_reorder::Select::new("Select the default project's pipeline (hit `esc` when done):", cs)
.prompt_skippable()?
{
for (key, val) in cmap.iter_mut() {
if key.as_str().eq(pipe.as_str()) {
val.default = Some(true);
println!("Default pipeline is now: `{}`", val.title.as_str());
} else {
val.default = Some(false);
}
}
}
}
}
Ok(())
}
}
pub async fn edit_paths(paths: &mut BTreeSet<PathBuf>) -> anyhow::Result<()> {
crate::tui::utils::edit_btreeset_entities(
paths,
None,
"Edit paths:",
|path| format!("{path:?}"),
None::<EditFn<PathBuf>>,
Some(async || collect_path()),
None::<CopyFn<PathBuf>>,
)
.await
}
impl DefinedAction {
pub async fn edit_action_from_prompt(
&mut self,
mut globals: Option<&mut DeployerGlobalConfig>,
) -> anyhow::Result<()> {
let mut actions = vec![];
match &self.action {
Action::Custom(_) | Action::Observe(_) | Action::Staged(_) => {
actions.push("Edit command");
}
Action::Test(_) => {
actions.extend_from_slice(&["Edit command", "Edit regexes"]);
}
Action::Patch(_) => {
actions.push("Edit patch");
}
Action::AddToStorage(_) => {
actions.push("Edit automatical artifact-to-storage push rules");
}
Action::SyncToRemote { .. } | Action::SyncFromRemote { .. } => {
actions.push("Edit remote host short name");
}
Action::Interrupt | Action::UseFromStorage { .. } => {}
}
actions.extend_from_slice(&[
"Edit tags",
"Edit action requirements",
"Change action's execution path (run or project folder)",
]);
if globals.is_some() {
actions.push("Export this action to the Registry");
}
while let Some(action) =
inquire_reorder::Select::new("Select an edit action (hit `esc` when done):", actions.clone())
.prompt_skippable()?
{
match action {
"Edit tags" => {
let joined = self.tags.join(", ");
self.tags = tags_custom_type(
"Write action's tags, if any:",
if joined.is_empty() { None } else { Some(joined.as_str()) },
)
.prompt()?
}
"Edit command" => match &mut self.action {
Action::Staged(a) => a.command.edit_from_prompt()?,
Action::Test(a) => a.edit_from_prompt()?,
Action::Observe(a) => a.command.edit_from_prompt()?,
Action::Custom(a) => a.edit_from_prompt()?,
_ => {}
},
"Edit automatical artifact-to-storage push rules" => {
if let Action::AddToStorage(a) = &mut self.action {
a.edit_from_prompt()?;
}
}
"Edit regexes" => {
if let Action::Test(c_action) = &mut self.action {
c_action.change_regexes_from_prompt()?;
}
}
"Edit patch" => {
if let Action::Patch(patch) = &mut self.action {
patch.edit_from_prompt()?;
}
}
"Edit action requirements" => {
crate::tui::utils::edit_entities(
&mut self.requirements,
None,
"Edit requirements:",
Requirement::to_string,
Some(async |req: &mut Requirement| req.edit_requirement_from_prompt().await),
Some(async || Requirement::new_from_prompt()),
None::<CopyFn<Requirement>>,
false,
)
.await?;
}
"Edit remote host short name" => match &mut self.action {
Action::SyncToRemote { remote_host_name } => {
*remote_host_name = ShortName::new(
inquire_reorder::Text::new("Specify the remote host's short name:")
.with_initial_value(remote_host_name.as_str())
.prompt()?,
)?
}
Action::SyncFromRemote { remote_host_name } => {
*remote_host_name = ShortName::new(
inquire_reorder::Text::new("Specify the remote host's short name:")
.with_initial_value(remote_host_name.as_str())
.prompt()?,
)?
}
_ => {}
},
"Change action's execution path (run or project folder)" => {
self.exec_in_project_dir = if let Ok(Some(exec_in_project_dir)) = inquire_reorder::Confirm::new(
"Do you need execute this action in project's directory instead of run directory?",
)
.with_default(self.exec_in_project_dir.unwrap_or(false))
.prompt_skippable()
{
Some(exec_in_project_dir)
} else {
None
};
if self.exec_in_project_dir.is_some_and(|v| v) {
self.skip_sync = if let Ok(Some(skip_sync)) = inquire_reorder::Confirm::new(
"Should Deployer SKIP synchronization of project and run folders after executing this action?",
)
.with_default(self.skip_sync.unwrap_or(false))
.prompt_skippable()
{
Some(skip_sync)
} else {
None
};
}
}
"Export this action to the Registry" => {
let globals = globals.as_mut().unwrap();
globals.actions_registry.insert(self.clone());
println!("Action is exported successfully.");
}
_ => {}
}
}
Ok(())
}
}
impl DescribedPipeline {
pub async fn edit_pipeline_from_prompt(
&mut self,
pipelines_registry: &mut BTreeSet<DescribedPipeline>,
project_actions: &BTreeSet<DefinedAction>,
variables: Option<&BTreeMap<ShortName, Variable>>,
remotes: &BTreeMap<ShortName, RemoteHost>,
in_registry: bool,
) -> anyhow::Result<()> {
let mut actions = vec![
"Edit used actions",
"Set exclusive tag for run folder",
"Set the files that will be copied to the run folder",
"Set pipeline driver",
"Edit artifacts placements",
"Edit options for containered (Docker/Podman) runs",
"Edit options for Docker Compose runs",
"Edit options for Ansible runs",
"Edit options for GitHub Actions export",
"Edit options for GitLab CI export",
"Edit pipeline title",
"Edit pipeline description",
"Edit pipeline tags",
];
if !in_registry && variables.is_some() {
actions.extend_from_slice(&[
"Export pipeline to the global registry",
"Setup variables for the pipeline",
]);
}
while let Some(action) =
inquire_reorder::Select::new("Select an edit action (hit `esc` when done):", actions.clone())
.prompt_skippable()?
{
match action {
"Edit pipeline title" => {
self.title = inquire_reorder::Text::new("Write a short name for the pipeline:")
.with_placeholder("some-short-name")
.with_initial_value(self.title.as_str())
.prompt()?
}
"Edit pipeline description" => {
self.desc = inquire_reorder::Text::new("Write the pipeline's additional description")
.with_initial_value(self.desc.as_deref().unwrap_or(""))
.prompt_skippable()?
}
"Edit pipeline tags" => {
let joined = self.tags.join(", ");
self.tags = tags_custom_type(
"Write pipeline's tags, if any:",
if joined.is_empty() { None } else { Some(joined.as_str()) },
)
.prompt()?
}
"Edit used actions" => {
let empty_vars = bmap![];
crate::tui::utils::edit_entities(
&mut self.actions,
None,
"Edit used actions:",
|action: &UsedAction| {
format!(
"{}{}",
action.used.to_str(),
if let Some(title) = action.title.as_deref() {
format!(" - {title}")
} else {
String::new()
}
)
},
Some(async |action: &mut UsedAction| {
edit_optional_str(&mut action.title, |_| "Edit action title:".to_string())
}),
Some(async || UsedAction::make_from_defined(project_actions, variables.as_ref().unwrap_or(&&empty_vars))),
None::<CopyFn<UsedAction>>,
true,
)
.await?;
}
"Set exclusive tag for run folder" => {
self.exclusive_exec_tag = if let Some(exclusive_exec_tag) = &self.exclusive_exec_tag {
inquire_reorder::Text::new("Specify exclusive pipeline tag (or hit `esc`):")
.with_initial_value(exclusive_exec_tag)
.prompt_skippable()?
} else {
inquire_reorder::Text::new("Specify exclusive pipeline tag (or hit `esc`):").prompt_skippable()?
}
}
"Set pipeline driver" => {
self.driver = if inquire_reorder::Confirm::new(
"Do you wanna keep Deployer as pipeline driver? If no, shell driver will be opted. (y/n)",
)
.prompt()?
{
PipelineDriver::Deployer
} else {
PipelineDriver::Shell
};
}
"Edit artifacts placements" => {
crate::tui::utils::edit_entities(
&mut self.artifacts,
None,
"Edit artifacts placements:",
|ap: &Placement| format!("{:?} -> {:?}", ap.from, ap.to),
None::<EditFn<Placement>>,
Some(async || collect_af_placement()),
None::<CopyFn<Placement>>,
false,
)
.await?;
}
"Export pipeline to the global registry" => {
pipelines_registry.insert(self.clone());
println!("Pipeline is exported successfully.");
}
"Setup variables for the pipeline" => {
let variables = variables.unwrap();
if variables.is_empty() {
println!("Please, specify variables for project first!");
let mut needed = vec![];
for action in &self.actions {
let definition = action.definition(project_actions)?;
for var in definition.collect_required_variables() {
needed.push(format!(
"\t- variable `{var}` for pipeline `{}`, action `{}`",
self.info.to_str(),
action.used.to_str()
));
}
}
println!("These variables are required:");
needed.iter().for_each(|v| println!("{v}"));
continue;
}
for action in &mut self.actions {
if let Ok(setup) = action.prompt_setup_for_project(variables, project_actions) {
*action = setup;
}
}
}
"Edit options for containered (Docker/Podman) runs" => {
if self.containered_opts.is_none() {
self.containered_opts = ContaineredOpts::new_from_prompt(self.driver).ok();
}
if let Some(containered_opts) = self.containered_opts.as_mut() {
containered_opts.edit_from_prompt(self.driver, variables).await?;
}
}
"Edit options for Docker Compose runs" => {
if self.compose_opts.is_none() {
self.compose_opts = ComposeOpts::new_from_prompt(self.driver).ok();
}
if let Some(compose_opts) = self.compose_opts.as_mut() {
compose_opts.edit_from_prompt(self.driver, variables).await?;
}
}
"Edit options for Ansible runs" => {
if self.ansible_opts.is_none() {
self.ansible_opts = AnsibleOpts::new_from_prompt(remotes).ok();
}
if let Some(ansible_opts) = self.ansible_opts.as_mut() {
ansible_opts.edit_from_prompt(remotes).await?;
}
}
"Edit options for GitHub Actions export" => {
if self.gh_opts.is_none() {
self.gh_opts = GitHubOpts::new_from_prompt().ok();
}
if let Some(gh_opts) = self.gh_opts.as_mut() {
gh_opts.edit_from_prompt().await?;
}
}
"Edit options for GitLab CI export" => {
if self.gl_opts.is_none() {
self.gl_opts = GitLabOpts::new_from_prompt().ok();
}
if let Some(gl_opts) = self.gl_opts.as_mut() {
gl_opts.edit_from_prompt().await?;
}
}
"Set the files that will be copied to the run folder" => {
crate::tui::utils::edit_entities(
&mut self.copy_only,
None,
"Choose files to copy to the run folder (or leave empty to copy all):",
|path| path.to_string(),
Some(async |path: &mut String| {
*path = inquire_reorder::Text::new("Edit current path:")
.with_initial_value(path.as_str())
.prompt()?;
Ok(())
}),
Some(async || Ok(inquire_reorder::Text::new("Enter a path:").prompt()?)),
None::<CopyFn<String>>,
false,
)
.await?;
}
_ => {}
}
}
Ok(())
}
}
pub(crate) fn edit_optional<T>(
option: &mut Option<T>,
prompt: impl Fn(&Option<T>) -> String,
initial: impl Fn(T) -> Option<String>,
result: impl Fn(String) -> Option<T>,
) -> anyhow::Result<()> {
use inquire_reorder::Text;
let prpt = prompt(option);
let mut rslt = Text::new(prpt.as_str());
let initial = if let Some(inner) = option.take()
&& let Some(initial) = initial(inner)
{
initial
} else {
String::new()
};
rslt = rslt.with_initial_value(initial.as_str());
let rslt = rslt.prompt()?;
let result = result(rslt);
*option = result;
Ok(())
}
pub(crate) fn edit_optional_str(
option: &mut Option<String>,
prompt: impl Fn(&Option<String>) -> String,
) -> anyhow::Result<()> {
edit_optional::<String>(option, prompt, Some, |r| if r.is_empty() { None } else { Some(r) })
}
impl Requirement {
pub async fn edit_requirement_from_prompt(&mut self) -> anyhow::Result<()> {
match self {
Self::Exists { path, desc } => {
*path = PathBuf::from(
inquire_reorder::Text::new("Enter the path:")
.with_initial_value(path.to_str().unwrap())
.prompt()?,
);
*desc = inquire_reorder::Text::new("Describe your requirement, installation steps, or leave empty:")
.with_initial_value(desc.as_str())
.prompt()
.unwrap_or_default();
}
Self::ExistsAny { paths, desc } => {
edit_paths(paths).await?;
*desc = inquire_reorder::Text::new("Describe your requirement, installation steps, or leave empty:")
.with_initial_value(desc.as_str())
.prompt()
.unwrap_or_default();
}
Self::InPath { executable, desc } => {
*executable = inquire_reorder::Text::new("Enter the name of executable:")
.with_initial_value(executable.as_str())
.prompt()?;
*desc = inquire_reorder::Text::new("Describe your requirement, installation steps, or leave empty:")
.with_initial_value(desc.as_str())
.prompt()
.unwrap_or_default();
}
Self::CheckSuccess { action, desc } => {
action.edit_from_prompt()?;
*desc = inquire_reorder::Text::new("Describe your requirement, installation steps, or leave empty:")
.with_initial_value(desc.as_str())
.prompt()
.unwrap_or_default();
}
Self::RemoteAccessibleAndReady { remote_host_name } => {
*remote_host_name = ShortName::new(
inquire_reorder::Text::new("Specify the remote host's short name:")
.with_initial_value(remote_host_name.as_str())
.prompt()?,
)?
}
}
Ok(())
}
}
impl Variable {
pub fn edit_variable_from_prompt(&mut self) -> anyhow::Result<()> {
let actions = vec!["Change secret flag", "Edit value"];
while let Some(action) =
inquire_reorder::Select::new("Select an edit action (hit `esc` when done):", actions.clone())
.prompt_skippable()?
{
match action {
"Change secret flag" => {
self.is_secret = inquire_reorder::Confirm::new("Is this variable a secret?")
.with_default(false)
.prompt()?
}
"Edit value" => match &mut self.value {
VarValue::Plain { value } => {
*value = inquire_reorder::Text::new("Enter the variable's content:")
.with_initial_value(value)
.prompt()?
}
VarValue::FromEnvFile(_) => self.value = Variable::new_env_file_from_prompt()?,
VarValue::FromHcVaultKv2(_) => self.value = Variable::new_kv2_from_prompt()?,
VarValue::FromEnvVar { .. } => self.value = Variable::new_env_from_prompt()?,
VarValue::FromCmd { .. } => self.value = Variable::new_env_from_prompt()?,
},
_ => {}
}
}
Ok(())
}
}
impl CustomCommand {
pub fn edit_from_prompt(&mut self) -> anyhow::Result<()> {
while let Some(action) = inquire_reorder::Select::new(
&format!(
"Select an option to change in `{}` command (hit `esc` when done):",
self.cmd.green(),
),
vec![
"Edit shell command",
"Change command placeholders",
"Change required environment variables",
"Change command failure ignorance",
"Change whether command is displayed or not on run stage",
"Change whether command output is displayed or not when it executed successfully",
"Change command executing only at fresh runs",
"Change daemon behavior",
],
)
.prompt_skippable()?
{
match action {
"Edit shell command" => self.cmd = specify_cmd(Some(self.cmd.as_str()))?,
"Change command placeholders" => {
self.placeholders = if !self.placeholders.is_empty() {
let joined = self.placeholders.join(", ");
tags_custom_type("Enter command placeholders, if any:", Some(joined.as_str())).prompt()?
} else {
tags_custom_type("Enter command placeholders, if any:", None).prompt()?
};
}
"Change required environment variables" => {
self.env = if !self.env.is_empty() {
let joined = self.env.join(", ");
tags_custom_type("Enter required environment variables, if any:", Some(joined.as_str())).prompt()?
} else {
tags_custom_type("Enter required environment variables, if any:", None).prompt()?
};
}
"Change command failure ignorance" => {
self.ignore_fails = if inquire_reorder::Confirm::new("Ignore command failures?")
.with_default(false)
.prompt()?
{
Some(true)
} else {
None
};
}
"Change whether command is displayed or not on run stage" => {
self.show_cmd = if !inquire_reorder::Confirm::new("Show an entire command at pipeline's run?")
.with_default(true)
.prompt()?
{
Some(false)
} else {
None
};
}
"Change whether command output is displayed or not when it executed successfully" => {
self.show_success_output =
if inquire_reorder::Confirm::new("Show an output of command if it executed successfully?")
.with_default(false)
.prompt()?
{
Some(true)
} else {
None
};
}
"Change command executing only at fresh runs" => {
self.only_when_fresh = if inquire_reorder::Confirm::new("Start a command only in fresh runs?")
.with_default(false)
.prompt()?
{
Some(true)
} else {
None
};
}
"Change daemon behavior" => {
self.daemon = if inquire_reorder::Confirm::new("Run as a daemon until the pipeline is complete?")
.with_default(false)
.prompt()?
{
Some(true)
} else {
None
};
}
_ => {}
}
}
Ok(())
}
}
impl TestAction {
pub fn change_regexes_from_prompt(&mut self) -> anyhow::Result<()> {
println!("Current regexes are:");
println!("`success_when_found` = {:?}", self.success_when_found);
println!("`success_when_not_found` = {:?}", self.success_when_not_found);
if inquire_reorder::Confirm::new("Specify success when found some regex?")
.with_default(true)
.prompt()?
{
self.success_when_found = Some(collect_regex("for success on match")?);
}
if inquire_reorder::Confirm::new("Specify success when NOT found some regex?")
.with_default(true)
.prompt()?
{
self.success_when_not_found = Some(collect_regex("for success on mismatch")?);
}
Ok(())
}
}
impl TestAction {
pub fn edit_from_prompt(&mut self) -> anyhow::Result<()> {
while let Some(selected) = inquire_reorder::Select::new(
"Specify an action for Test Action:",
vec!["Edit check command", "Edit regexes"],
)
.prompt_skippable()?
{
match selected {
"Edit check command" => self.command.edit_from_prompt()?,
"Edit regexes" => self.change_regexes_from_prompt()?,
_ => {}
}
}
Ok(())
}
}
impl PatchAction {
pub fn edit_from_prompt(&mut self) -> anyhow::Result<()> {
self.patch = PathBuf::from(
inquire_reorder::Text::new("Specify patch location:")
.with_default(&self.patch.to_string_lossy())
.prompt()?,
);
Ok(())
}
}
impl AddToStorageAction {
pub fn edit_from_prompt(&mut self) -> anyhow::Result<()> {
loop {
let short_name = inquire_reorder::Text::new(
"Specify a short name for the content under which it will be loaded into the storage automatically:",
)
.with_default(&self.short_name)
.prompt()?;
if crate::entities::info::validate_short_name(&short_name) {
self.short_name = short_name;
break;
}
println!("Short names must only contain English characters and `_` and `-` characters.");
}
if inquire_reorder::Confirm::new(&format!(
"Do you want to change the way content is automatically versioned? Current method is: {}",
self.auto_version_rule.type_str(),
))
.with_default(false)
.prompt()?
{
let new_autover_rule = inquire_reorder::Select::new(
"Select the version detection method:",
vec![
"execute the command and get output from `stdout` as version",
"get a version from specified plain file",
],
)
.prompt()?;
self.auto_version_rule = match new_autover_rule {
"execute the command and get output from `stdout` as version" => AutoVersionExtractFromRule::CmdStdout {
cmd: {
let mut cmd = CustomCommand::new_observe_from_prompt()?;
cmd.show_success_output = Some(true);
cmd
},
},
"get a version from specified plain file" => AutoVersionExtractFromRule::PlainFile {
path: {
let path = inquire_reorder::Text::new("Specify the relative path to plain version file:").prompt()?;
PathBuf::from(path)
},
},
_ => bail!("There is no such type"),
};
}
Ok(())
}
}
impl RemoteHost {
pub fn edit_from_prompt(&mut self) -> anyhow::Result<()> {
self.short_name = ShortName::new(
inquire_reorder::Text::new("Specify the remote host's short name:")
.with_initial_value(self.short_name.as_str())
.prompt()?,
)?;
self.ip = inquire_reorder::Text::new("Specify the IP-address of a remote host's SSH server:")
.with_initial_value(self.ip.to_string().as_str())
.prompt()?
.parse()?;
self.port = inquire_reorder::Text::new("Specify the port of a remote host's SSH server:")
.with_initial_value(self.port.to_string().as_str())
.prompt()?
.parse()?;
self.username = inquire_reorder::Text::new("Specify the remote username:")
.with_initial_value(self.username.as_str())
.prompt()?;
self.ssh_private_key_file =
inquire_reorder::Text::new("Specify the path to private SSH key for remote host (or hit `esc`):")
.with_initial_value(
self
.ssh_private_key_file
.as_ref()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_default()
.as_str(),
)
.prompt_skippable()?
.map(PathBuf::from);
Ok(())
}
}
impl AnsibleOpts {
pub async fn edit_from_prompt(&mut self, remotes: &BTreeMap<ShortName, RemoteHost>) -> anyhow::Result<()> {
loop {
println!(
"Current Ansible config is {}.",
match (!self.create_inventory.is_empty(), self.use_inventory.is_some()) {
(true, false) => "automatically creating inventory from Deployer hosts".green().italic(),
(false, true) => "using existing inventory file".green().italic(),
_ => "invalid".red().bold(),
}
);
let mut opts = vec![
"Choose hosts to create inventory with",
"Choose existing inventory file",
];
if self.use_inventory.is_some() {
opts.push("Specify host group from inventory file");
}
let select = inquire_reorder::Select::new("Select action:", opts).prompt_skippable()?;
let Some(select) = select else { return Ok(()) };
match select {
"Choose hosts to create inventory with" => {
let remotes = remotes.keys().map(|k| k.to_owned()).collect::<BTreeSet<_>>();
crate::tui::utils::edit_btreeset_entities(
&mut self.create_inventory,
Some(&remotes),
"Choose hosts to create inventory with:",
|remote: &ShortName| format!("Remote {}", remote.as_str()),
None::<EditFn<ShortName>>,
None::<CreateFn<ShortName>>,
None::<CopyFn<ShortName>>,
)
.await?;
if !self.create_inventory.is_empty() {
self.use_inventory = None;
self.host_group = None;
}
}
"Choose existing inventory file" => {
let path = inquire_reorder::Text::new("Enter path to existing inventory `*.ini`-file:")
.with_initial_value(
self
.use_inventory
.as_ref()
.map(|p| p.to_str().unwrap_or_default())
.unwrap_or_default(),
)
.prompt()?;
if !path.is_empty() {
self.use_inventory = Some(PathBuf::from(path));
self.create_inventory.clear();
}
}
"Specify host group from inventory file" => {
let host_group = inquire_reorder::Text::new("Specify host group from inventory file:")
.with_initial_value(self.host_group.as_deref().unwrap_or_default())
.prompt()?;
if host_group.as_str().eq("all") {
self.host_group = None;
} else {
self.host_group = Some(host_group);
}
}
_ => unreachable!(),
}
}
}
}
impl ContaineredOpts {
pub async fn edit_from_prompt(
&mut self,
driver: PipelineDriver,
variables: Option<&BTreeMap<ShortName, Variable>>,
) -> anyhow::Result<()> {
loop {
let mut opts = vec!["Edit base image", "Edit preflight commands"];
if driver.is_deployer() {
opts.extend_from_slice(&[
"Edit base image to build Deployer",
"Edit Deployer's build preflight commands",
]);
}
if variables.is_some() {
opts.push("Edit variables");
}
opts.extend_from_slice(&[
"Edit port bindings",
"Edit cache strategy",
"Run detached or not?",
"Allow internal host bind (unsecure)",
"Choose executor (Docker/Podman/auto)",
]);
let select = inquire_reorder::Select::new("Choose action:", opts).prompt_skippable()?;
let Some(select) = select else { return Ok(()) };
match select {
"Edit base image" => {
self.base_image = inquire_reorder::Text::new("Enter the name of the base image to run with:")
.with_placeholder("image:version")
.with_initial_value(self.base_image.as_deref().unwrap_or(crate::containered::BASE_IMAGE))
.prompt()
.ok();
if let Some(crate::containered::BASE_IMAGE) = self.base_image.as_deref() {
self.base_image = None;
}
}
"Edit base image to build Deployer" => {
self.build_deployer_base_image =
inquire_reorder::Text::new("Enter the name of the base image to build Deployer with:")
.with_placeholder("image:version")
.with_initial_value(
self
.build_deployer_base_image
.as_deref()
.unwrap_or(crate::containered::BASE_IMAGE),
)
.prompt()
.ok();
if let Some(crate::containered::BASE_IMAGE) = self.build_deployer_base_image.as_deref() {
self.build_deployer_base_image = None;
}
}
"Edit preflight commands" => {
let cmds = self.preflight_cmds.join("\n");
let new_cmds = crate::tui::utils::edit_with_nano(
"Edit preflight commands.\nPlease, refer to https://docs.docker.com/reference/dockerfile/ for reference.\nWrite commands below this comment.",
cmds,
Some("Dockerfile"),
)
.await?;
self.preflight_cmds = new_cmds.split('\n').map(|l| l.to_string()).collect();
}
"Edit Deployer's build preflight commands" => {
let mut cmds = self.deployer_build_cmds.join("\n");
if cmds.is_empty() {
cmds = crate::containered::DEPL_DRIVER_INSTALL_CMDS.to_string();
}
let new_cmds = crate::tui::utils::edit_with_nano(
"Edit Deployer's build preflight commands.\nPlease, refer to https://docs.docker.com/reference/dockerfile/ for reference.\nWrite commands below this comment.",
cmds,
Some("Dockerfile"),
)
.await?;
if new_cmds.as_str().eq(crate::containered::DEPL_DRIVER_INSTALL_CMDS) {
self.deployer_build_cmds = vec![];
} else {
self.deployer_build_cmds = new_cmds.split('\n').map(|l| l.to_string()).collect();
}
}
"Run detached or not?" => {
self.run_detached = inquire_reorder::Confirm::new("Run pipeline detached (as deployment)?")
.with_default(false)
.prompt()?;
}
"Allow internal host bind (unsecure)" => {
self.allow_internal_host_bind =
inquire_reorder::Confirm::new("Allow to connect to internal host from container?")
.with_default(false)
.prompt()?;
}
"Edit port bindings" => {
crate::tui::utils::edit_entities(
&mut self.port_bindings,
None,
"Edit port bindings:",
|pb| format!("from {} to {}", pb.from, pb.to),
None::<EditFn<PortBinding>>,
Some(async || PortBinding::new_from_prompt()),
None::<CopyFn<PortBinding>>,
false,
)
.await?;
}
"Edit cache strategy" => {
crate::tui::utils::edit_entities(
&mut self.cache_strategies,
None,
"Cache strategy steps:",
|cbs| cbs.to_string(),
Some(async |strat: &mut ContainerizedBuildStrategyStep| strat.edit_from_prompt().await),
Some(async || Ok(ContainerizedBuildStrategyStep::default())),
None::<CopyFn<ContainerizedBuildStrategyStep>>,
true,
)
.await?;
}
"Edit variables" => {
let vars = variables.unwrap().keys().map(|v| v.to_string()).collect::<Vec<_>>();
crate::tui::utils::edit_btreemap_entities(
&mut self.with,
None,
"Edit variables for containerized configuration:",
|(placeholder, _): &(String, ShortName)| placeholder.to_string(),
None::<EditFn<(String, ShortName)>>,
Some(async || {
let placeholder = inquire_reorder::Text::new("Enter placeholder:").prompt()?;
let vars = vars.clone();
let var_shortname = inquire_reorder::Select::new("Select variable for substitution:", vars).prompt()?;
let var = ShortName::new(var_shortname)?;
Ok((placeholder, var))
}),
None::<CopyFn<(String, ShortName)>>,
)
.await?;
}
"Choose executor (Docker/Podman/auto)" => {
let msg = format!(
"Current executor is {}. Choose an executor for this pipeline:",
match self.executor {
ContainerExecutor::Docker => "Docker",
ContainerExecutor::Podman => "Podman",
ContainerExecutor::Auto => "in automatic resolution mode",
}
.green()
);
let opts = vec!["Docker", "Podman", "auto"];
let res = inquire_reorder::Select::new(&msg, opts).prompt()?;
self.executor = match res {
"Docker" => ContainerExecutor::Docker,
"Podman" => ContainerExecutor::Podman,
"auto" => ContainerExecutor::Auto,
_ => unreachable!(),
};
}
_ => unreachable!(),
}
}
}
}
impl ContainerizedBuildStrategyStep {
pub async fn edit_from_prompt(&mut self) -> anyhow::Result<()> {
loop {
println!("Current step: {}", self.to_string().green());
let opts = vec![
"Choose fake content to sync (if needed)",
"Edit copy commands",
"Edit cache commands",
];
let select = inquire_reorder::Select::new("Choose action:", opts).prompt_skippable()?;
let Some(select) = select else { return Ok(()) };
match select {
"Choose fake content to sync (if needed)" => {
self.fake_content = if let Some(info) =
inquire_reorder::Text::new("Specify fake content from Deployer's storage (or hit `esc`):")
.with_placeholder("content-info@{semver2.0-specified-version OR `latest`}")
.with_initial_value(
self
.fake_content
.as_ref()
.map(|fc| fc.to_str())
.unwrap_or_default()
.as_str(),
)
.prompt_skippable()?
{
Some(ContentInfo::try_from_str_wl(info.as_str())?)
} else {
None
};
}
"Edit copy commands" => {
let cmds = self.copy_cmds.join("\n");
let new_cmds = crate::tui::utils::edit_with_nano(
"Edit copy commands.\nPlease, refer to https://docs.docker.com/reference/dockerfile/ for reference.\n\nNote that copy commands copies only necessary-to-cache files.\nDo not copy files that are supposed to change oftenly.\n\nWrite commands below this comment.",
cmds,
Some("Dockerfile"),
)
.await?;
self.copy_cmds = new_cmds.split('\n').map(|l| l.to_string()).collect();
}
"Edit cache commands" => {
let cmds = self.pre_cache_cmds.join("\n");
let new_cmds = crate::tui::utils::edit_with_nano(
"Edit cache commands.\nPlease, refer to https://docs.docker.com/reference/dockerfile/ for reference.\n\nNote that cache commands describes how you should create cache files.\nFor example, them builds your project with copied files.\nWrite `DEPL` command to execute current Deployer's pipeline.\n\nWrite commands below this comment.",
cmds,
Some("Dockerfile"),
)
.await?;
self.pre_cache_cmds = new_cmds.split('\n').map(|l| l.to_string()).collect();
}
_ => unreachable!(),
}
}
}
}
impl ComposeServiceOpts {
pub async fn edit_from_prompt(&mut self) -> anyhow::Result<()> {
loop {
println!("Current service: {}", self.to_string().green());
let opts = vec![
"Edit image",
"Edit environment variables",
"Edit port bindings",
"Edit volumes",
"Edit command override",
"Edit healthcheck",
];
let select = inquire_reorder::Select::new("Choose action (hit `esc` when done):", opts).prompt_skippable()?;
let Some(select) = select else { return Ok(()) };
match select {
"Edit image" => {
self.image = inquire_reorder::Text::new("Enter Docker image for this service:")
.with_placeholder("postgres:16")
.with_initial_value(self.image.as_str())
.prompt()?;
}
"Edit environment variables" => {
crate::tui::utils::edit_btreemap_entities(
&mut self.environment,
None,
"Edit service environment variables:",
|(key, value): &(String, String)| format!("{key}={value}"),
Some(async |item: &mut (String, String)| {
item.0 = inquire_reorder::Text::new("Edit variable name:")
.with_initial_value(item.0.as_str())
.prompt()?;
item.1 = inquire_reorder::Text::new("Edit variable value:")
.with_initial_value(item.1.as_str())
.prompt()?;
Ok(())
}),
Some(async || {
let key = inquire_reorder::Text::new("Enter variable name:")
.with_placeholder("POSTGRES_PASSWORD")
.prompt()?;
let value = inquire_reorder::Text::new("Enter variable value:")
.with_placeholder("secret")
.prompt()?;
Ok((key, value))
}),
None::<CopyFn<(String, String)>>,
)
.await?;
}
"Edit port bindings" => {
crate::tui::utils::edit_entities(
&mut self.ports,
None,
"Edit service port bindings:",
|pb| format!("from {} to {}", pb.from, pb.to),
None::<EditFn<PortBinding>>,
Some(async || PortBinding::new_from_prompt()),
None::<CopyFn<PortBinding>>,
false,
)
.await?;
}
"Edit volumes" => {
crate::tui::utils::edit_entities(
&mut self.volumes,
None,
"Edit service volumes:",
|v| v.to_string(),
Some(async |vol: &mut String| {
*vol = inquire_reorder::Text::new("Edit volume:")
.with_initial_value(vol.as_str())
.prompt()?;
Ok(())
}),
Some(async || {
Ok(
inquire_reorder::Text::new("Enter volume (e.g. `pgdata:/var/lib/postgresql/data`):")
.with_placeholder("volume_name:/path/in/container")
.prompt()?,
)
}),
None::<CopyFn<String>>,
false,
)
.await?;
}
"Edit command override" => {
edit_optional_str(&mut self.command, |_| {
"Enter custom command for this service:".to_string()
})?;
}
"Edit healthcheck" => {
edit_optional_str(&mut self.healthcheck_cmd, |_| {
"Enter healthcheck command (e.g. `pg_isready -U postgres`):".to_string()
})?;
if self.healthcheck_cmd.is_some() {
let interval_str = inquire_reorder::Text::new("Healthcheck interval (seconds):")
.with_initial_value(&self.healthcheck_interval_secs.to_string())
.prompt()?;
if let Ok(v) = interval_str.parse::<u64>() {
self.healthcheck_interval_secs = v;
}
let retries_str = inquire_reorder::Text::new("Healthcheck retries:")
.with_initial_value(&self.healthcheck_retries.to_string())
.prompt()?;
if let Ok(v) = retries_str.parse::<u32>() {
self.healthcheck_retries = v;
}
}
}
_ => unreachable!(),
}
}
}
}
impl ComposeOpts {
pub async fn edit_from_prompt(
&mut self,
driver: PipelineDriver,
variables: Option<&BTreeMap<ShortName, Variable>>,
) -> anyhow::Result<()> {
loop {
let mut opts = vec![
"Edit app (main service) containerized options",
"Edit services",
"Edit compose-level variables",
"Edit compose project name",
"Run detached or not?",
"Abort on container exit?",
"Remove containers on exit?",
"Choose executor (Docker/Podman/auto)",
];
if variables.is_none() {
opts.retain(|o| *o != "Edit compose-level variables");
}
let select = inquire_reorder::Select::new("Choose action (hit `esc` when done):", opts).prompt_skippable()?;
let Some(select) = select else { return Ok(()) };
match select {
"Edit app (main service) containerized options" => {
self.app.edit_from_prompt(driver, variables).await?;
}
"Edit services" => {
crate::tui::utils::edit_btreemap_entities(
&mut self.services,
None,
"Edit Compose services:",
|(name, service): &(String, ComposeServiceOpts)| format!("{name}: {service}"),
Some(async |item: &mut (String, ComposeServiceOpts)| {
println!("Editing service `{}`:", item.0.green());
item.1.edit_from_prompt().await
}),
Some(async || {
let name = inquire_reorder::Text::new("Enter service name:")
.with_placeholder("postgres")
.prompt()?;
let image = inquire_reorder::Text::new("Enter Docker image for this service:")
.with_placeholder("postgres:16")
.prompt()?;
Ok((
name,
ComposeServiceOpts {
image,
..Default::default()
},
))
}),
None::<CopyFn<(String, ComposeServiceOpts)>>,
)
.await?;
}
"Edit compose-level variables" => {
let vars = variables.unwrap().keys().map(|v| v.to_string()).collect::<Vec<_>>();
crate::tui::utils::edit_btreemap_entities(
&mut self.with,
None,
"Edit variables for Compose configuration:",
|(placeholder, _): &(String, ShortName)| placeholder.to_string(),
None::<EditFn<(String, ShortName)>>,
Some(async || {
let placeholder = inquire_reorder::Text::new("Enter placeholder:").prompt()?;
let vars = vars.clone();
let var_shortname = inquire_reorder::Select::new("Select variable for substitution:", vars).prompt()?;
let var = ShortName::new(var_shortname)?;
Ok((placeholder, var))
}),
None::<CopyFn<(String, ShortName)>>,
)
.await?;
}
"Edit compose project name" => {
edit_optional_str(&mut self.project_name, |_| {
"Enter Compose project name (or leave empty for default):".to_string()
})?;
}
"Run detached or not?" => {
self.detach = inquire_reorder::Confirm::new("Run Compose in detached mode?")
.with_default(self.detach)
.prompt()?;
}
"Abort on container exit?" => {
self.abort_on_container_exit = inquire_reorder::Confirm::new("Abort all services when any container exits?")
.with_default(self.abort_on_container_exit)
.prompt()?;
}
"Remove containers on exit?" => {
self.remove_on_exit = inquire_reorder::Confirm::new("Remove containers after run?")
.with_default(self.remove_on_exit)
.prompt()?;
}
"Choose executor (Docker/Podman/auto)" => {
let executor = self.effective_executor();
let msg = format!(
"Current executor is {}. Choose an executor:",
match executor {
ContainerExecutor::Docker => "Docker",
ContainerExecutor::Podman => "Podman",
ContainerExecutor::Auto => "in automatic resolution mode",
}
.green()
);
let opts = vec!["Docker", "Podman", "auto"];
let res = inquire_reorder::Select::new(&msg, opts).prompt()?;
self.executor = match res {
"Docker" => ContainerExecutor::Docker,
"Podman" => ContainerExecutor::Podman,
"auto" => ContainerExecutor::Auto,
_ => unreachable!(),
};
}
_ => unreachable!(),
}
}
}
}