Skip to main content

nu_command/env/config/
config_.rs

1use nu_cmd_base::util::get_editor;
2use nu_config::ConfigFileKind;
3use nu_engine::{command_prelude::*, env_to_strings, get_full_help};
4use nu_protocol::{PipelineMetadata, shell_error::io::IoError};
5use nu_system::ForegroundChild;
6
7#[cfg(feature = "os")]
8use nu_protocol::process::PostWaitCallback;
9
10#[derive(Clone)]
11pub struct ConfigMeta;
12
13impl Command for ConfigMeta {
14    fn name(&self) -> &str {
15        "config"
16    }
17
18    fn signature(&self) -> Signature {
19        Signature::build(self.name())
20            .category(Category::Env)
21            .input_output_types(vec![(Type::Nothing, Type::String)])
22    }
23
24    fn description(&self) -> &str {
25        "Edit nushell configuration files."
26    }
27
28    fn extra_description(&self) -> &str {
29        "You must use one of the following subcommands. Using this command as-is will only produce this help message."
30    }
31
32    fn run(
33        &self,
34        engine_state: &EngineState,
35        stack: &mut Stack,
36        call: &Call,
37        _input: PipelineData,
38    ) -> Result<PipelineData, ShellError> {
39        Ok(Value::string(
40            get_full_help(self, engine_state, stack, call.head),
41            call.head,
42        )
43        .into_pipeline_data())
44    }
45
46    fn search_terms(&self) -> Vec<&str> {
47        vec!["options", "setup"]
48    }
49}
50
51#[cfg(not(feature = "os"))]
52pub(super) fn start_editor(
53    _: ConfigFileKind,
54    _: &EngineState,
55    _: &mut Stack,
56    call: &Call,
57) -> Result<PipelineData, ShellError> {
58    Err(ShellError::DisabledOsSupport {
59        msg: "Running external commands is not available without OS support.".to_string(),
60        span: call.head,
61    })
62}
63
64#[cfg(feature = "os")]
65pub(super) fn start_editor(
66    kind: ConfigFileKind,
67    engine_state: &EngineState,
68    stack: &mut Stack,
69    call: &Call,
70) -> Result<PipelineData, ShellError> {
71    // Find the editor executable.
72
73    let (editor_name, editor_args) = get_editor(engine_state, stack, call.head)?;
74    let paths = nu_engine::env::path_str(engine_state, stack, call.head)?;
75    let cwd = engine_state.cwd(Some(stack))?;
76    let editor_executable =
77        crate::which(&editor_name, &paths, cwd.as_ref()).ok_or(ShellError::ExternalCommand {
78            label: format!("`{editor_name}` not found"),
79            help: "Failed to find the editor executable".into(),
80            span: call.head,
81        })?;
82
83    let config_path = match kind {
84        ConfigFileKind::Config => engine_state.config_dirs.config_file.as_path(),
85        ConfigFileKind::Env => engine_state.config_dirs.env_file.as_path(),
86    };
87    let config_path = config_path.to_string_lossy().to_string();
88
89    // Create the command.
90    let mut command = std::process::Command::new(editor_executable);
91
92    // Configure PWD.
93    command.current_dir(cwd);
94
95    // Configure environment variables.
96    let envs = env_to_strings(engine_state, stack)?;
97    command.env_clear();
98    command.envs(envs);
99
100    // Configure args.
101    command.args(editor_args);
102    command.arg(config_path);
103
104    // Spawn the child process. On Unix, also put the child process to
105    // foreground if we're in an interactive session.
106    #[cfg(windows)]
107    let child = ForegroundChild::spawn(command);
108    #[cfg(unix)]
109    let child = ForegroundChild::spawn(
110        command,
111        engine_state.is_interactive,
112        engine_state.is_background_job(),
113        &engine_state.pipeline_externals_state,
114    );
115
116    let child = child.map_err(|err| {
117        IoError::new_with_additional_context(
118            err,
119            call.head,
120            None,
121            "Could not spawn foreground child",
122        )
123    })?;
124
125    let post_wait_callback = PostWaitCallback::for_job_control(engine_state, None, None);
126
127    // Wrap the output into a `PipelineData::byte_stream`.
128    let child = nu_protocol::process::ChildProcess::new(
129        child,
130        None,
131        false,
132        call.head,
133        Some(post_wait_callback),
134    )?;
135
136    Ok(PipelineData::byte_stream(
137        ByteStream::child(child, call.head),
138        None,
139    ))
140}
141
142pub(super) fn handle_call(
143    kind: ConfigFileKind,
144    engine_state: &EngineState,
145    stack: &mut Stack,
146    call: &Call,
147) -> Result<PipelineData, ShellError> {
148    let default_flag = call.has_flag(engine_state, stack, "default")?;
149    let doc_flag = call.has_flag(engine_state, stack, "doc")?;
150
151    Ok(match (default_flag, doc_flag) {
152        (false, false) => {
153            return super::config_::start_editor(kind, engine_state, stack, call);
154        }
155        (true, true) => {
156            return Err(ShellError::IncompatibleParameters {
157                left_message: "can't use `--default` at the same time".into(),
158                left_span: call.get_flag_span(stack, "default").expect("has flag"),
159                right_message: "because of `--doc`".into(),
160                right_span: call.get_flag_span(stack, "doc").expect("has flag"),
161            });
162        }
163        (true, false) => kind.default(),
164        (false, true) => kind.doc(),
165    }
166    .into_value(call.head)
167    .into_pipeline_data_with_metadata(
168        PipelineMetadata::default().with_content_type(Some("application/x-nuscript".into())),
169    ))
170}