depl 2.4.3

Toolkit for a bunch of local and remote CI/CD actions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
//! `Edit` menus.

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 {
  /// Edits project options from terminal.
  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(&registry));
          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(())
  }

  /// Chooses default Pipeline to run.
  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(())
  }
}

/// Edits set of paths.
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 {
  /// Edits an Action from terminal.
  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 {
  /// Edits a Pipeline from terminal.
  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 {
  /// Edits a requirement from terminal.
  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 {
  /// Edits a variable from terminal.
  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 {
  /// Edits a custom command from prompt.
  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 {
  /// Edits regular expressions for `Test` Action from terminal.
  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 {
  /// Edits test action from prompt.
  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 {
  /// Edits patch action from prompt.
  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 {
  /// Edits add-to-storage action from prompt.
  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 {
  /// Edits remote host from prompt.
  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 {
  /// Edits Ansible options from prompt.
  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 {
  /// Edits containered (Docker/Podman) options from prompt.
  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 {
  /// Edits containerized build strategy from prompt.
  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 {
  /// Edits a Compose service from prompt.
  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 {
  /// Edits Docker Compose options from prompt.
  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() {
        // Remove compose-level variables option if no project variables
        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!(),
      }
    }
  }
}