Skip to content

Commit b687bc2

Browse files
committed
cleanup
1 parent 9848e66 commit b687bc2

File tree

6 files changed

+111
-151
lines changed

6 files changed

+111
-151
lines changed

crates/shell/src/error.rs

Lines changed: 1 addition & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,10 @@
1-
use std::path::PathBuf;
2-
31
use serde::{Serialize, Serializer};
42

53
#[derive(Debug, thiserror::Error)]
64
pub enum Error {
75
#[error(transparent)]
86
Io(#[from] std::io::Error),
97

10-
#[error("Current executable path has no parent")]
11-
CurrentExeHasNoParent,
12-
13-
#[error("Unknown program {0}")]
14-
UnknownProgramName(String),
15-
16-
#[error("Program not allowed on the configured shell scope: {0}")]
17-
ProgramNotAllowed(PathBuf),
18-
19-
#[error("Unknown encoding {0}")]
20-
UnknownEncoding(String),
21-
22-
#[error(transparent)]
23-
Json(#[from] serde_json::Error),
24-
25-
#[error(transparent)]
26-
Utf8(#[from] std::string::FromUtf8Error),
27-
288
#[error("Invalid buffer")]
299
InvalidBuffer,
3010
}
@@ -37,6 +17,6 @@ impl Serialize for Error {
3717
where
3818
S: Serializer,
3919
{
40-
serializer.serialize_str(self.to_string().as_ref())
20+
serializer.serialize_str(&self.to_string())
4121
}
4222
}

crates/shell/src/shell.rs

Lines changed: 41 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,8 @@ pub enum Buffer {
3030
}
3131

3232
impl Buffer {
33-
/// Creates a new buffer.
33+
/// Creates a `Buffer` instance, either containing raw bytes or text
34+
/// based on the `is_raw` flag.
3435
pub fn new(is_raw: bool) -> Buffer {
3536
if is_raw {
3637
Buffer::Raw(Vec::new())
@@ -80,25 +81,24 @@ impl Buffer {
8081
}
8182
}
8283

83-
/// A event sent to the command callback.
84+
/// Event emitted by child process execution.
8485
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
8586
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
86-
pub enum CommandEvent {
87-
/// If configured for raw output, all bytes written to stderr.
88-
/// Otherwise, bytes until a newline (\n) or carriage return (\r) is
89-
/// found.
90-
Stderr(Buffer),
91-
92-
/// If configured for raw output, all bytes written to stdout.
93-
/// Otherwise, bytes until a newline (\n) or carriage return (\r) is
94-
/// found.
87+
pub enum ChildProcessEvent {
88+
/// Raw or line-buffered stdout output. If configured for raw output,
89+
/// all bytes written to stdout. Otherwise, bytes until a newline (\n)
90+
/// or carriage return (\r) is found.
9591
Stdout(Buffer),
9692

97-
/// An error happened waiting for the command to finish or converting
98-
/// the stdout/stderr bytes to a UTF-8 string.
93+
/// Raw or line-buffered stderr output. If configured for raw output,
94+
/// all bytes written to stderr. Otherwise, bytes until a newline (\n)
95+
/// or carriage return (\r) is found.
96+
Stderr(Buffer),
97+
98+
/// An error occurred waiting for the child process to finish.
9999
Error(String),
100100

101-
/// Command process terminated.
101+
/// Child process terminated.
102102
Terminated(ExitStatus),
103103
}
104104

@@ -107,7 +107,7 @@ pub enum CommandEvent {
107107
pub struct ChildProcess {
108108
inner: Arc<SharedChild>,
109109
stdin_writer: PipeWriter,
110-
rx: mpsc::Receiver<CommandEvent>,
110+
rx: mpsc::Receiver<ChildProcessEvent>,
111111
}
112112

113113
impl ChildProcess {
@@ -129,7 +129,7 @@ impl ChildProcess {
129129
}
130130

131131
/// Returns a channel of events from the child process.
132-
pub fn events(&mut self) -> &mut mpsc::Receiver<CommandEvent> {
132+
pub fn events(&mut self) -> &mut mpsc::Receiver<ChildProcessEvent> {
133133
&mut self.rx
134134
}
135135
}
@@ -140,16 +140,11 @@ pub struct ExitStatus {
140140
/// Exit code of the process.
141141
pub code: Option<i32>,
142142

143-
/// If the process was terminated by a signal, represents that signal.
144-
pub signal: Option<i32>,
145-
}
143+
/// Whether the process exited with a zero exit code.
144+
pub success: bool,
146145

147-
impl ExitStatus {
148-
/// Returns true if exit status is zero. Signal termination is not
149-
/// considered a success, and success is defined as a zero exit status.
150-
pub fn success(&self) -> bool {
151-
self.code == Some(0)
152-
}
146+
/// Termination signal if process was killed.
147+
pub signal: Option<i32>,
153148
}
154149

155150
/// The output of a finished process.
@@ -159,10 +154,10 @@ pub struct ShellExecOutput {
159154
#[serde(flatten)]
160155
pub status: ExitStatus,
161156

162-
/// The data that the process wrote to stdout.
157+
/// The buffer that the process wrote to stdout.
163158
pub stdout: Buffer,
164159

165-
/// The data that the process wrote to stderr.
160+
/// The buffer that the process wrote to stderr.
166161
pub stderr: Buffer,
167162
}
168163

@@ -182,7 +177,7 @@ impl Shell {
182177
/// Shell::exec("echo", &["Hello!"], &CommandOptions::default())
183178
/// .await
184179
/// .unwrap();
185-
/// assert!(output.status.success());
180+
/// assert!(output.status.success);
186181
/// assert_eq!(output.stdout.as_str().unwrap(), "Hello!");
187182
/// ```
188183
pub async fn exec<I, S>(
@@ -202,16 +197,16 @@ impl Shell {
202197

203198
while let Some(event) = child.events().recv().await {
204199
match event {
205-
CommandEvent::Terminated(exit_status) => {
200+
ChildProcessEvent::Terminated(exit_status) => {
206201
status = exit_status;
207202
}
208-
CommandEvent::Stdout(line) => {
203+
ChildProcessEvent::Stdout(line) => {
209204
stdout.push(line)?;
210205
}
211-
CommandEvent::Stderr(line) => {
206+
ChildProcessEvent::Stderr(line) => {
212207
stderr.push(line)?;
213208
}
214-
CommandEvent::Error(_) => {}
209+
ChildProcessEvent::Error(_) => {}
215210
}
216211
}
217212

@@ -232,7 +227,7 @@ impl Shell {
232227
/// Shell::status("echo", ["Hello!"], CommandOptions::default())
233228
/// .await
234229
/// .unwrap();
235-
/// assert!(status.success());
230+
/// assert!(status.success);
236231
/// ```
237232
pub async fn status<I, S>(
238233
&self,
@@ -247,7 +242,7 @@ impl Shell {
247242
let mut child = Self::spawn(program, args, options)?;
248243

249244
while let Some(event) = child.events().recv().await {
250-
if let CommandEvent::Terminated(status) = event {
245+
if let ChildProcessEvent::Terminated(status) = event {
251246
return Ok(status);
252247
}
253248
}
@@ -307,15 +302,15 @@ impl Shell {
307302
tx.clone(),
308303
guard.clone(),
309304
stdout_reader,
310-
CommandEvent::Stdout,
305+
ChildProcessEvent::Stdout,
311306
options.encoding.clone(),
312307
);
313308

314309
Self::spawn_pipe_reader(
315310
tx.clone(),
316311
guard.clone(),
317312
stderr_reader,
318-
CommandEvent::Stderr,
313+
ChildProcessEvent::Stderr,
319314
options.encoding.clone(),
320315
);
321316

@@ -324,14 +319,15 @@ impl Shell {
324319
let _lock = guard.write().unwrap();
325320

326321
let event = match status {
327-
Ok(status) => CommandEvent::Terminated(ExitStatus {
322+
Ok(status) => ChildProcessEvent::Terminated(ExitStatus {
328323
code: status.code(),
324+
success: status.code().is_some_and(|code| code == 0),
329325
#[cfg(windows)]
330326
signal: None,
331327
#[cfg(unix)]
332328
signal: status.signal(),
333329
}),
334-
Err(err) => CommandEvent::Error(err.to_string()),
330+
Err(err) => ChildProcessEvent::Error(err.to_string()),
335331
};
336332

337333
let _ = tx.blocking_send(event);
@@ -379,20 +375,19 @@ impl Shell {
379375
/// Spawns a thread to read from stdout/stderr and emit the output
380376
/// through a channel.
381377
fn spawn_pipe_reader<F>(
382-
tx: mpsc::Sender<CommandEvent>,
378+
tx: mpsc::Sender<ChildProcessEvent>,
383379
guard: Arc<RwLock<()>>,
384380
pipe: os_pipe::PipeReader,
385381
wrapper: F,
386382
encoding: Encoding,
387383
) where
388-
F: Fn(Buffer) -> CommandEvent + Send + Copy + 'static,
384+
F: Fn(Buffer) -> ChildProcessEvent + Send + Copy + 'static,
389385
{
390386
spawn(move || {
391387
let _lock = guard.read().unwrap();
392388
let mut reader = StdoutReader::new(pipe, encoding);
393389

394390
while let Ok(Some(buffer)) = reader.read_next() {
395-
println!("buffer: {:?}", buffer);
396391
if tx.blocking_send(wrapper(buffer)).is_err() {
397392
break;
398393
}
@@ -415,7 +410,7 @@ mod tests {
415410
.await
416411
.unwrap();
417412

418-
assert!(output.status.success());
413+
assert!(output.status.success);
419414
assert!(output.stderr.as_str().unwrap().is_empty());
420415
assert!(output.stdout.as_str().unwrap().contains("hello world"));
421416
}
@@ -433,7 +428,7 @@ mod tests {
433428
.await
434429
.unwrap();
435430

436-
assert!(!output.status.success());
431+
assert!(!output.status.success);
437432
assert!(!output.stderr.as_str().unwrap().is_empty());
438433
}
439434

@@ -454,12 +449,12 @@ mod tests {
454449
let mut saw_stdout = false;
455450
while let Some(event) = child.events().recv().await {
456451
match event {
457-
CommandEvent::Stdout(Buffer::Raw(bytes)) => {
452+
ChildProcessEvent::Stdout(Buffer::Raw(bytes)) => {
458453
assert!(!bytes.is_empty());
459454
saw_stdout = true;
460455
}
461-
CommandEvent::Terminated(status) => {
462-
assert!(status.success());
456+
ChildProcessEvent::Terminated(status) => {
457+
assert!(status.success);
463458
}
464459
_ => {}
465460
}

examples/boilerplate-solid-ts/src/index.tsx

Lines changed: 0 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -13,36 +13,6 @@ const providers = zebar.createProviderGroup({
1313
media: { type: 'media' },
1414
});
1515

16-
console.log('xxxxxxxxx', await zebar.shellExec('echo', ['hdfldas']));
17-
18-
const test = await zebar.shellExec('ping', [
19-
'127.0.0.1',
20-
'-n',
21-
'10',
22-
'-w',
23-
'3000',
24-
]);
25-
console.log('test', test);
26-
const git = await zebar.shellSpawn('ping', [
27-
'127.0.0.1',
28-
'-n',
29-
'10',
30-
'-w',
31-
'3000',
32-
]);
33-
git.onStdout(output => console.log('stdout', output));
34-
git.onStderr(output => console.log('stderr', output));
35-
git.onExit(output => console.log('exit', output));
36-
console.log('xxxxxxxxx', await zebar.shellExec('node', ['fjdisa']));
37-
// console.log('xxxxxxxxx', await zebar.shellExec('code', ['.']));
38-
// console.log(
39-
// 'xxxxxxxxx',
40-
// await zebar.shellExec(
41-
// 'C:/Users/larsb/AppData/Local/Programs/cursor/resources/app/bin/code',
42-
// ),
43-
// );
44-
// console.log('xxxxxxxxx', await zebar.shellExec('code', ['.']));
45-
4616
render(() => <App />, document.getElementById('root')!);
4717

4818
function App() {

packages/desktop/src/main.rs

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -162,22 +162,6 @@ async fn start_app(app: &mut tauri::App, cli: Cli) -> anyhow::Result<()> {
162162
));
163163
app.manage(widget_factory.clone());
164164

165-
let shell =
166-
Shell::exec("code", &["--version"], &CommandOptions::default()).await;
167-
168-
println!(" aaaaaaaaaa {:?}", shell);
169-
170-
let shell = Shell::exec(
171-
r#"c:\Users\larsb\AppData\Local\Programs\cursor\resources\app\bin\code.cmd"#,
172-
&["--version"],
173-
&CommandOptions::default(),
174-
)
175-
.await;
176-
177-
println!(" bbb {:?}", shell);
178-
// .spawn("echo", ExecuteArgs::new(), on_event,
179-
// CommandOptions::default());
180-
181165
// If this is not the first instance of the app, this will emit within
182166
// the original instance and exit immediately. The CLI command is
183167
// guaranteed to be one of the open commands here.

0 commit comments

Comments
 (0)