Debian Codegraph @

cli/src/commands/config/edit.rs

raw
1 // Copyright 2020 The Jujutsu Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use jj_lib::config::ConfigLayer;
16 use tracing::instrument;
17
18 use super::ConfigTargetArgs;
19 use crate::cli_util::CommandHelper;
20 use crate::command_error::CommandError;
21 use crate::command_error::print_error_sources;
22 use crate::ui::Ui;
23
24 /// Start an editor on a jj config file.
25 ///
26 /// Creates the file if it doesn't already exist regardless of what the editor
27 /// does.
28 #[derive(clap::Args, Clone, Debug)]
29 pub struct ConfigEditArgs {
30 #[command(flatten)]
31 pub target: ConfigTargetArgs,
32 }
33
34 #[instrument(skip_all)]
35 pub async fn cmd_config_edit(
36 ui: &mut Ui,
37 command: &CommandHelper,
38 args: &ConfigEditArgs,
39 ) -> Result<(), CommandError> {
40 let editor = command.text_editor()?;
41 let file = args.target.edit_config_file(ui, command)?;
42 if !file.path().exists() {
43 file.save()?;
44 }
45
46 // Editing again and again until either of these conditions is met
47 // 1. The config is OK
48 // 2. The user restores previous one
49 writeln!(ui.status(), "Editing file: {}", file.path().display())?;
50 loop {
51 editor.edit_file(file.path())?;
52
53 // Trying to load back config. If error, prompt to continue editing
54 if let Err(e) = ConfigLayer::load_from_file(file.layer().source, file.path().to_path_buf())
55 {
56 writeln!(
57 ui.warning_default(),
58 "An error has been found inside the config:"
59 )?;
60 print_error_sources(ui, Some(&e))?;
61 let continue_editing = ui.prompt_yes_no(
62 "Do you want to keep editing the file? If not, previous config will be restored.",
63 Some(true),
64 )?;
65 if !continue_editing {
66 // Saving back previous config
67 file.save()?;
68 break;
69 }
70 } else {
71 // config is OK
72 break;
73 }
74 }
75 Ok(())
76 }