1use 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 = nu_path::expand_path_with(path_no_whitespace, &cwd, true);
53
54 if full_path.exists() {
56 open_path(full_path, engine_state, stack, path.span)?;
57 return Ok(PipelineData::Empty);
58 }
59 Err(ShellError::GenericError {
61 error: format!("Cannot find file or URL: {}", &path.item),
62 msg: "".into(),
63 span: Some(path.span),
64 help: Some("Ensure the path or URL is correct and try again.".into()),
65 inner: vec![],
66 })
67 }
68 fn examples(&self) -> Vec<nu_protocol::Example> {
69 vec![
70 Example {
71 description: "Open a text file with the default text editor",
72 example: "start file.txt",
73 result: None,
74 },
75 Example {
76 description: "Open an image with the default image viewer",
77 example: "start file.jpg",
78 result: None,
79 },
80 Example {
81 description: "Open the current directory with the default file manager",
82 example: "start .",
83 result: None,
84 },
85 Example {
86 description: "Open a PDF with the default PDF viewer",
87 example: "start file.pdf",
88 result: None,
89 },
90 Example {
91 description: "Open a website with the default browser",
92 example: "start https://www.nushell.sh",
93 result: None,
94 },
95 Example {
96 description: "Open an application-registered protocol URL",
97 example: "start obsidian://open?vault=Test",
98 result: None,
99 },
100 ]
101 }
102}
103
104fn open_path(
105 path: impl AsRef<OsStr>,
106 engine_state: &EngineState,
107 stack: &Stack,
108 span: Span,
109) -> Result<(), ShellError> {
110 try_commands(open::commands(path), engine_state, stack, span)
111}
112
113fn try_commands(
114 commands: Vec<std::process::Command>,
115 engine_state: &EngineState,
116 stack: &Stack,
117 span: Span,
118) -> Result<(), ShellError> {
119 let env_vars_str = env_to_strings(engine_state, stack)?;
120 let mut last_err = None;
121
122 for mut cmd in commands {
123 let status = cmd
124 .envs(&env_vars_str)
125 .stdin(Stdio::null())
126 .stdout(Stdio::null())
127 .stderr(Stdio::null())
128 .status();
129
130 match status {
131 Ok(status) if status.success() => return Ok(()),
132 Ok(status) => {
133 last_err = Some(format!(
134 "Command `{}` failed with exit code: {}",
135 format_command(&cmd),
136 status.code().unwrap_or(-1)
137 ));
138 }
139 Err(err) => {
140 last_err = Some(format!(
141 "Command `{}` failed with error: {}",
142 format_command(&cmd),
143 err
144 ));
145 }
146 }
147 }
148
149 Err(ShellError::ExternalCommand {
150 label: "Failed to start the specified path or URL".to_string(),
151 help: format!(
152 "Try a different path or install the appropriate application.\n{}",
153 last_err.unwrap_or_default()
154 ),
155 span,
156 })
157}
158
159fn format_command(command: &std::process::Command) -> String {
160 let parts_iter = std::iter::once(command.get_program()).chain(command.get_args());
161 Itertools::intersperse(parts_iter, OsStr::new(" "))
162 .collect::<OsString>()
163 .to_string_lossy()
164 .into_owned()
165}