Function tauri::async_runtime::block_on

source ·
pub fn block_on<F: Future>(task: F) -> F::Output
Expand description

Runs a future to completion on runtime.

Examples found in repository?
src/async_runtime.rs (line 301)
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
pub(crate) fn safe_block_on<F>(task: F) -> F::Output
where
  F: Future + Send + 'static,
  F::Output: Send + 'static,
{
  if let Ok(handle) = tokio::runtime::Handle::try_current() {
    let (tx, rx) = std::sync::mpsc::sync_channel(1);
    let handle_ = handle.clone();
    handle.spawn_blocking(move || {
      tx.send(handle_.block_on(task)).unwrap();
    });
    rx.recv().unwrap()
  } else {
    block_on(task)
  }
}
More examples
Hide additional examples
src/api/process/command.rs (lines 293-302)
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
  pub fn spawn(self) -> crate::api::Result<(Receiver<CommandEvent>, CommandChild)> {
    let encoding = self.encoding;
    let mut command: StdCommand = self.into();
    let (stdout_reader, stdout_writer) = pipe()?;
    let (stderr_reader, stderr_writer) = pipe()?;
    let (stdin_reader, stdin_writer) = pipe()?;
    command.stdout(stdout_writer);
    command.stderr(stderr_writer);
    command.stdin(stdin_reader);

    let shared_child = SharedChild::spawn(&mut command)?;
    let child = Arc::new(shared_child);
    let child_ = child.clone();
    let guard = Arc::new(RwLock::new(()));

    commands().lock().unwrap().insert(child.id(), child.clone());

    let (tx, rx) = channel(1);

    spawn_pipe_reader(
      tx.clone(),
      guard.clone(),
      stdout_reader,
      CommandEvent::Stdout,
      encoding,
    );
    spawn_pipe_reader(
      tx.clone(),
      guard.clone(),
      stderr_reader,
      CommandEvent::Stderr,
      encoding,
    );

    spawn(move || {
      let _ = match child_.wait() {
        Ok(status) => {
          let _l = guard.write().unwrap();
          commands().lock().unwrap().remove(&child_.id());
          block_on_task(async move {
            tx.send(CommandEvent::Terminated(TerminatedPayload {
              code: status.code(),
              #[cfg(windows)]
              signal: None,
              #[cfg(unix)]
              signal: status.signal(),
            }))
            .await
          })
        }
        Err(e) => {
          let _l = guard.write().unwrap();
          block_on_task(async move { tx.send(CommandEvent::Error(e.to_string())).await })
        }
      };
    });

    Ok((
      rx,
      CommandChild {
        inner: child,
        stdin_writer,
      },
    ))
  }

  /// Executes a command as a child process, waiting for it to finish and collecting its exit status.
  /// Stdin, stdout and stderr are ignored.
  ///
  /// # Examples
  /// ```rust,no_run
  /// use tauri::api::process::Command;
  /// let status = Command::new("which").args(["ls"]).status().unwrap();
  /// println!("`which` finished with status: {:?}", status.code());
  /// ```
  pub fn status(self) -> crate::api::Result<ExitStatus> {
    let (mut rx, _child) = self.spawn()?;
    let code = crate::async_runtime::safe_block_on(async move {
      let mut code = None;
      #[allow(clippy::collapsible_match)]
      while let Some(event) = rx.recv().await {
        if let CommandEvent::Terminated(payload) = event {
          code = payload.code;
        }
      }
      code
    });
    Ok(ExitStatus { code })
  }

  /// Executes the command as a child process, waiting for it to finish and collecting all of its output.
  /// Stdin is ignored.
  ///
  /// # Examples
  ///
  /// ```rust,no_run
  /// use tauri::api::process::Command;
  /// let output = Command::new("echo").args(["TAURI"]).output().unwrap();
  /// assert!(output.status.success());
  /// assert_eq!(output.stdout, "TAURI");
  /// ```
  pub fn output(self) -> crate::api::Result<Output> {
    let (mut rx, _child) = self.spawn()?;

    let output = crate::async_runtime::safe_block_on(async move {
      let mut code = None;
      let mut stdout = String::new();
      let mut stderr = String::new();
      while let Some(event) = rx.recv().await {
        match event {
          CommandEvent::Terminated(payload) => {
            code = payload.code;
          }
          CommandEvent::Stdout(line) => {
            stdout.push_str(line.as_str());
            stdout.push('\n');
          }
          CommandEvent::Stderr(line) => {
            stderr.push_str(line.as_str());
            stderr.push('\n');
          }
          CommandEvent::Error(_) => {}
        }
      }
      Output {
        status: ExitStatus { code },
        stdout,
        stderr,
      }
    });

    Ok(output)
  }
}

fn spawn_pipe_reader<F: Fn(String) -> CommandEvent + Send + Copy + 'static>(
  tx: Sender<CommandEvent>,
  guard: Arc<RwLock<()>>,
  pipe_reader: PipeReader,
  wrapper: F,
  character_encoding: Option<&'static Encoding>,
) {
  spawn(move || {
    let _lock = guard.read().unwrap();
    let mut reader = BufReader::new(pipe_reader);

    let mut buf = Vec::new();
    loop {
      buf.clear();
      match tauri_utils::io::read_line(&mut reader, &mut buf) {
        Ok(n) => {
          if n == 0 {
            break;
          }
          let tx_ = tx.clone();
          let line = match character_encoding {
            Some(encoding) => Ok(encoding.decode_with_bom_removal(&buf).0.into()),
            None => String::from_utf8(buf.clone()),
          };
          block_on_task(async move {
            let _ = match line {
              Ok(line) => tx_.send(wrapper(line)).await,
              Err(e) => tx_.send(CommandEvent::Error(e.to_string())).await,
            };
          });
        }
        Err(e) => {
          let tx_ = tx.clone();
          let _ = block_on_task(async move { tx_.send(CommandEvent::Error(e.to_string())).await });
        }
      }
    }
  });
}