nu_command/filesystem/
start.rs1use itertools::Itertools;
2use nu_engine::{command_prelude::*, env_to_strings};
3use nu_protocol::ShellError;
4use std::{
5 ffi::{OsStr, OsString},
6 process::Stdio,
7};
8
9#[derive(Clone)]
10pub struct Start;
11
12impl Command for Start {
13 fn name(&self) -> &str {
14 "start"
15 }
16
17 fn description(&self) -> &str {
18 "Open a folder, file, or website in the default application or viewer."
19 }
20
21 fn search_terms(&self) -> Vec<&str> {
22 vec!["load", "folder", "directory", "run", "open"]
23 }
24
25 fn signature(&self) -> nu_protocol::Signature {
26 Signature::build("start")
27 .input_output_types(vec![(Type::Nothing, Type::Any)])
28 .required("path", SyntaxShape::String, "Path or URL to open.")
29 .category(Category::FileSystem)
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 let path = call.req::<Spanned<String>>(engine_state, stack, 0)?;
40 let path = Spanned {
41 item: nu_utils::strip_ansi_string_unlikely(path.item),
42 span: path.span,
43 };
44 let path_no_whitespace = path.item.trim_end_matches(|x| matches!(x, '\x09'..='\x0d'));
45 if let Ok(url) = url::Url::parse(path_no_whitespace) {
47 open_path(url.as_str(), engine_state, stack, path.span)?;
48 return Ok(PipelineData::Empty);
49 }
50 let cwd = engine_state.cwd(Some(stack))?;
52 let full_path = cwd.join(path_no_whitespace);
53 if full_path.exists() {
55 open_path(full_path, engine_state, stack, path.span)?;
56 return Ok(PipelineData::Empty);
57 }
58 Err(ShellError::GenericError {
60 error: format!("Cannot find file or URL: {}", &path.item),
61 msg: "".into(),
62 span: Some(path.span),
63 help: Some("Ensure the path or URL is correct and try again.".into()),
64 inner: vec![],
65 })
66 }
67 fn examples(&self) -> Vec<nu_protocol::Example> {
68 vec![
69 Example {
70 description: "Open a text file with the default text editor",
71 example: "start file.txt",
72 result: None,
73 },
74 Example {
75 description: "Open an image with the default image viewer",
76 example: "start file.jpg",
77 result: None,
78 },
79 Example {
80 description: "Open the current directory with the default file manager",
81 example: "start .",
82 result: None,
83 },
84 Example {
85 description: "Open a PDF with the default PDF viewer",
86 example: "start file.pdf",
87 result: None,
88 },
89 Example {
90 description: "Open a website with the default browser",
91 example: "start https://www.nushell.sh",
92 result: None,
93 },
94 Example {
95 description: "Open an application-registered protocol URL",
96 example: "start obsidian://open?vault=Test",
97 result: None,
98 },
99 ]
100 }
101}
102
103fn open_path(
104 path: impl AsRef<OsStr>,
105 engine_state: &EngineState,
106 stack: &Stack,
107 span: Span,
108) -> Result<(), ShellError> {
109 try_commands(open::commands(path), engine_state, stack, span)
110}
111
112fn try_commands(
113 commands: Vec<std::process::Command>,
114 engine_state: &EngineState,
115 stack: &Stack,
116 span: Span,
117) -> Result<(), ShellError> {
118 let env_vars_str = env_to_strings(engine_state, stack)?;
119 let mut last_err = None;
120
121 for mut cmd in commands {
122 let status = cmd
123 .envs(&env_vars_str)
124 .stdin(Stdio::null())
125 .stdout(Stdio::null())
126 .stderr(Stdio::null())
127 .status();
128
129 match status {
130 Ok(status) if status.success() => return Ok(()),
131 Ok(status) => {
132 last_err = Some(format!(
133 "Command `{}` failed with exit code: {}",
134 format_command(&cmd),
135 status.code().unwrap_or(-1)
136 ));
137 }
138 Err(err) => {
139 last_err = Some(format!(
140 "Command `{}` failed with error: {}",
141 format_command(&cmd),
142 err
143 ));
144 }
145 }
146 }
147
148 Err(ShellError::ExternalCommand {
149 label: "Failed to start the specified path or URL".to_string(),
150 help: format!(
151 "Try a different path or install the appropriate application.\n{}",
152 last_err.unwrap_or_default()
153 ),
154 span,
155 })
156}
157
158fn format_command(command: &std::process::Command) -> String {
159 let parts_iter = std::iter::once(command.get_program()).chain(command.get_args());
160 Itertools::intersperse(parts_iter, OsStr::new(" "))
161 .collect::<OsString>()
162 .to_string_lossy()
163 .into_owned()
164}