mirror of
https://github.com/tauri-apps/tauri.git
synced 2024-11-28 03:47:37 +03:00
docs(core): add examples to the API module (#3450)
This commit is contained in:
parent
c6031c7070
commit
e1b8fc739a
2
.github/workflows/artifacts-updater.yml
vendored
2
.github/workflows/artifacts-updater.yml
vendored
@ -98,7 +98,7 @@ jobs:
|
||||
${{ matrix.platform }}-
|
||||
|
||||
- name: build and install cli.rs
|
||||
run: cargo install --path tooling/cli
|
||||
run: cargo install --path tooling/cli --force
|
||||
- name: Check whether code signing should be enabled
|
||||
id: enablecodesigning
|
||||
env:
|
||||
|
@ -26,7 +26,7 @@ pub fn command(attributes: TokenStream, item: TokenStream) -> TokenStream {
|
||||
|
||||
/// Accepts a list of commands functions. Creates a handler that allows commands to be called from JS with invoke().
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
/// ```rust,ignore
|
||||
/// use tauri_macros::{command, generate_handler};
|
||||
/// #[command]
|
||||
|
@ -188,7 +188,7 @@ impl Menu {
|
||||
|
||||
/// Creates a new window menu with the given items.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// # use tauri_runtime::menu::{Menu, MenuItem, CustomMenuItem, Submenu};
|
||||
/// Menu::with_items([
|
||||
|
@ -64,6 +64,17 @@ impl Matches {
|
||||
}
|
||||
|
||||
/// Gets the argument matches of the CLI definition.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::api::cli::get_matches;
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// let matches = get_matches(app.config().tauri.cli.as_ref().unwrap(), app.package_info()).unwrap();
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
pub fn get_matches(cli: &CliConfig, package_info: &PackageInfo) -> crate::api::Result<Matches> {
|
||||
let about = cli
|
||||
.description()
|
||||
|
@ -115,7 +115,7 @@ pub mod blocking {
|
||||
/// This is a blocking operation,
|
||||
/// and should *NOT* be used when running on the main thread context.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::api::dialog::blocking::FileDialogBuilder;
|
||||
@ -134,7 +134,7 @@ pub mod blocking {
|
||||
/// This is a blocking operation,
|
||||
/// and should *NOT* be used when running on the main thread context.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::api::dialog::blocking::FileDialogBuilder;
|
||||
@ -153,7 +153,7 @@ pub mod blocking {
|
||||
/// This is a blocking operation,
|
||||
/// and should *NOT* be used when running on the main thread context.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::api::dialog::blocking::FileDialogBuilder;
|
||||
@ -172,7 +172,7 @@ pub mod blocking {
|
||||
/// This is a blocking operation,
|
||||
/// and should *NOT* be used when running on the main thread context.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::api::dialog::blocking::FileDialogBuilder;
|
||||
@ -193,7 +193,7 @@ pub mod blocking {
|
||||
/// This is a blocking operation,
|
||||
/// and should *NOT* be used when running on the main thread context.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::api::dialog::blocking::ask;
|
||||
@ -216,7 +216,7 @@ pub mod blocking {
|
||||
/// This is a blocking operation,
|
||||
/// and should *NOT* be used when running on the main thread context.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::api::dialog::blocking::confirm;
|
||||
@ -239,7 +239,7 @@ pub mod blocking {
|
||||
/// This is a blocking operation,
|
||||
/// and should *NOT* be used when running on the main thread context.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::api::dialog::blocking::message;
|
||||
@ -290,7 +290,7 @@ mod nonblocking {
|
||||
///
|
||||
/// For usage in other contexts such as commands, prefer [`Self::pick_file`].
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::api::dialog::FileDialogBuilder;
|
||||
@ -312,7 +312,7 @@ mod nonblocking {
|
||||
/// This is not a blocking operation,
|
||||
/// and should be used when running on the main thread to avoid deadlocks with the event loop.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::api::dialog::FileDialogBuilder;
|
||||
@ -334,7 +334,7 @@ mod nonblocking {
|
||||
/// This is not a blocking operation,
|
||||
/// and should be used when running on the main thread to avoid deadlocks with the event loop.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::api::dialog::FileDialogBuilder;
|
||||
@ -357,7 +357,7 @@ mod nonblocking {
|
||||
/// This is not a blocking operation,
|
||||
/// and should be used when running on the main thread to avoid deadlocks with the event loop.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::api::dialog::FileDialogBuilder;
|
||||
@ -381,7 +381,7 @@ mod nonblocking {
|
||||
/// This is not a blocking operation,
|
||||
/// and should be used when running on the main thread to avoid deadlocks with the event loop.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::api::dialog::ask;
|
||||
@ -406,7 +406,7 @@ mod nonblocking {
|
||||
/// This is not a blocking operation,
|
||||
/// and should be used when running on the main thread to avoid deadlocks with the event loop.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::api::dialog::confirm;
|
||||
@ -437,7 +437,7 @@ mod nonblocking {
|
||||
/// This is not a blocking operation,
|
||||
/// and should be used when running on the main thread to avoid deadlocks with the event loop.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::api::dialog::message;
|
||||
|
@ -12,12 +12,12 @@ use std::{fs, path::Path};
|
||||
pub use extract::*;
|
||||
pub use file_move::*;
|
||||
|
||||
/// Reads a string file.
|
||||
/// Reads the entire contents of a file into a string.
|
||||
pub fn read_string<P: AsRef<Path>>(file: P) -> crate::api::Result<String> {
|
||||
fs::read_to_string(file).map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Reads a binary file.
|
||||
/// Reads the entire contents of a file into a bytes vector.
|
||||
pub fn read_binary<P: AsRef<Path>>(file: P) -> crate::api::Result<Vec<u8>> {
|
||||
fs::read(file).map_err(Into::into)
|
||||
}
|
||||
|
@ -35,7 +35,7 @@ impl ClientBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the connection timeout.
|
||||
/// Sets the connection timeout in seconds.
|
||||
#[must_use]
|
||||
pub fn connect_timeout(mut self, connect_timeout: u64) -> Self {
|
||||
self.connect_timeout = Some(connect_timeout);
|
||||
@ -78,10 +78,24 @@ pub struct Client(ClientBuilder);
|
||||
|
||||
#[cfg(not(feature = "reqwest-client"))]
|
||||
impl Client {
|
||||
/// Executes an HTTP request
|
||||
/// Executes an HTTP request.
|
||||
///
|
||||
/// The response will be transformed to String.
|
||||
/// If reading the response as binary, the byte array will be serialized using [`serde_json`].
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::api::http::{ClientBuilder, HttpRequestBuilder, ResponseType};
|
||||
/// async fn run_request() {
|
||||
/// let client = ClientBuilder::new().build().unwrap();
|
||||
/// let response = client.send(
|
||||
/// HttpRequestBuilder::new("GET", "https://www.rust-lang.org")
|
||||
/// .unwrap()
|
||||
/// .response_type(ResponseType::Binary)
|
||||
/// ).await;
|
||||
/// if let Ok(response) = response {
|
||||
/// let bytes = response.bytes();
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub async fn send(&self, request: HttpRequestBuilder) -> crate::api::Result<Response> {
|
||||
let method = Method::from_bytes(request.method.to_uppercase().as_bytes())?;
|
||||
|
||||
@ -137,8 +151,7 @@ impl Client {
|
||||
impl Client {
|
||||
/// Executes an HTTP request
|
||||
///
|
||||
/// The response will be transformed to String.
|
||||
/// If reading the response as binary, the byte array will be serialized using serde_json.
|
||||
/// # Examples
|
||||
pub async fn send(&self, request: HttpRequestBuilder) -> crate::api::Result<Response> {
|
||||
let method = Method::from_bytes(request.method.to_uppercase().as_bytes())?;
|
||||
|
||||
@ -245,16 +258,15 @@ pub enum Body {
|
||||
/// The builder for a HTTP request.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```no_run
|
||||
/// use tauri::api::http::{ HttpRequestBuilder, ResponseType, ClientBuilder };
|
||||
/// ```rust,no_run
|
||||
/// use tauri::api::http::{HttpRequestBuilder, ResponseType, ClientBuilder};
|
||||
/// async fn run() {
|
||||
/// let client = ClientBuilder::new()
|
||||
/// .max_redirections(3)
|
||||
/// .build()
|
||||
/// .unwrap();
|
||||
/// let mut request_builder = HttpRequestBuilder::new("GET", "http://example.com").unwrap();
|
||||
/// let request = request_builder.response_type(ResponseType::Text);
|
||||
///
|
||||
/// let request = HttpRequestBuilder::new("GET", "http://example.com").unwrap()
|
||||
/// .response_type(ResponseType::Text);
|
||||
/// if let Ok(response) = client.send(request).await {
|
||||
/// println!("got response");
|
||||
/// } else {
|
||||
@ -351,7 +363,9 @@ impl Response {
|
||||
Ok(RawResponse { status, data })
|
||||
}
|
||||
|
||||
/// Reads the response and returns its info.
|
||||
/// Reads the response.
|
||||
///
|
||||
/// Note that the body is serialized to a [`Value`].
|
||||
pub async fn read(self) -> crate::api::Result<ResponseData> {
|
||||
#[cfg(feature = "reqwest-client")]
|
||||
let url = self.1.url().clone();
|
||||
|
@ -48,7 +48,7 @@ const MIN_JSON_PARSE_LEN: usize = 10_240;
|
||||
/// 2. JavaScript engines not accepting anything except another unescaped, literal single quote
|
||||
/// character to end a string that was opened with it.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use tauri::api::ipc::{serialize_js_with, SerializeOptions};
|
||||
@ -103,7 +103,7 @@ pub fn serialize_js_with<T: Serialize, F: FnOnce(&str) -> String>(
|
||||
///
|
||||
/// For usage in functions where performance is more important than code readability, see [`serialize_js_with`].
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
/// ```rust,no_run
|
||||
/// use tauri::{Manager, api::ipc::serialize_js};
|
||||
/// use serde::Serialize;
|
||||
|
@ -11,14 +11,23 @@ use std::path::MAIN_SEPARATOR;
|
||||
///
|
||||
/// Allows you to construct a Notification data and send it.
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// # Examples
|
||||
/// ```rust,no_run
|
||||
/// use tauri::api::notification::Notification;
|
||||
/// // first we build the application to access the Tauri configuration
|
||||
/// let app = tauri::Builder::default()
|
||||
/// // on an actual app, remove the string argument
|
||||
/// .build(tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json"))
|
||||
/// .expect("error while building tauri application");
|
||||
///
|
||||
/// // shows a notification with the given title and body
|
||||
/// Notification::new("studio.tauri.example")
|
||||
/// Notification::new(&app.config().tauri.bundle.identifier)
|
||||
/// .title("New message")
|
||||
/// .body("You've got a new message.")
|
||||
/// .show();
|
||||
///
|
||||
/// // run the app
|
||||
/// app.run(|_app_handle, _event| {});
|
||||
/// ```
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, Default)]
|
||||
|
@ -58,8 +58,8 @@ pub enum BaseDirectory {
|
||||
/// Resolves to [`BaseDirectory::Config`].
|
||||
App,
|
||||
/// The Log directory.
|
||||
/// Resolves to [`BaseDirectory::Home/Library/Logs/{bundle_identifier}`] on macOS
|
||||
/// and [`BaseDirectory::Config/{bundle_identifier}/logs`] on linux and windows.
|
||||
/// Resolves to `BaseDirectory::Home/Library/Logs/{bundle_identifier}` on macOS
|
||||
/// and `BaseDirectory::Config/{bundle_identifier}/logs` on linux and windows.
|
||||
Log,
|
||||
}
|
||||
|
||||
@ -118,6 +118,18 @@ impl BaseDirectory {
|
||||
}
|
||||
|
||||
/// Parse the given path, resolving a [`BaseDirectory`] variable if the path starts with one.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::Manager;
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// let path = tauri::api::path::parse(&app.config(), app.package_info(), &app.env(), "$HOME/.bashrc").unwrap();
|
||||
/// assert_eq!(path.to_str().unwrap(), "/home/${whoami}/.bashrc");
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
pub fn parse<P: AsRef<Path>>(
|
||||
config: &Config,
|
||||
package_info: &PackageInfo,
|
||||
@ -152,24 +164,44 @@ pub fn parse<P: AsRef<Path>>(
|
||||
|
||||
/// Resolves the path with the optional base directory.
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// use tauri::{api::path::{resolve_path, BaseDirectory}, PackageInfo};
|
||||
/// // we use the default config and a mock PackageInfo, but in an actual app you should get the
|
||||
/// // Config created from `tauri.conf.json` and the app's PackageInfo instance.
|
||||
/// This is a low level API. If the application has been built,
|
||||
/// prefer the [path resolver API](`crate::AppHandle#method.path_resolver`).
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ## Before initializing the application
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::{api::path::{BaseDirectory, resolve_path}, Env};
|
||||
/// // on an actual app, remove the string argument
|
||||
/// let context = tauri::generate_context!("test/fixture/src-tauri/tauri.conf.json");
|
||||
/// let path = resolve_path(
|
||||
/// &Default::default(),
|
||||
/// &PackageInfo {
|
||||
/// name: "app".into(),
|
||||
/// version: "1.0.0".into(),
|
||||
/// authors: "tauri",
|
||||
/// description: "a tauri test",
|
||||
/// },
|
||||
/// &Default::default(),
|
||||
/// "path/to/something",
|
||||
/// Some(BaseDirectory::Config)
|
||||
/// ).expect("failed to resolve path");
|
||||
/// // path is equal to "/home/${whoami}/.config/path/to/something" on Linux
|
||||
/// context.config(),
|
||||
/// context.package_info(),
|
||||
/// &Env::default(),
|
||||
/// "db/tauri.sqlite",
|
||||
/// Some(BaseDirectory::App))
|
||||
/// .expect("failed to resolve path");
|
||||
/// assert_eq!(path.to_str().unwrap(), "/home/${whoami}/.config/com.tauri.app/db/tauri.sqlite");
|
||||
///
|
||||
/// tauri::Builder::default().run(context).expect("error while running tauri application");
|
||||
/// ```
|
||||
///
|
||||
/// ## With an initialized app
|
||||
/// ```rust,no_run
|
||||
/// use tauri::{api::path::{BaseDirectory, resolve_path}, Manager};
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// let path = resolve_path(
|
||||
/// &app.config(),
|
||||
/// app.package_info(),
|
||||
/// &app.env(),
|
||||
/// "path/to/something",
|
||||
/// Some(BaseDirectory::Config)
|
||||
/// ).expect("failed to resolve path");
|
||||
/// assert_eq!(path.to_str().unwrap(), "/home/${whoami}/.config/path/to/something");
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
pub fn resolve_path<P: AsRef<Path>>(
|
||||
config: &Config,
|
||||
|
@ -38,6 +38,19 @@ pub use command::*;
|
||||
///
|
||||
/// See [`tauri_utils::platform::current_exe`] for possible security implications.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::{api::process::current_binary, Env, Manager};
|
||||
/// let current_binary_path = current_binary(&Env::default()).unwrap();
|
||||
///
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// let current_binary_path = current_binary(&app.env()).unwrap();
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
///
|
||||
/// [AppImage]: https://appimage.org/
|
||||
pub fn current_binary(_env: &Env) -> std::io::Result<PathBuf> {
|
||||
// if we are running from an AppImage, we ONLY want the set AppImage path
|
||||
@ -53,6 +66,18 @@ pub fn current_binary(_env: &Env) -> std::io::Result<PathBuf> {
|
||||
///
|
||||
/// See [`current_binary`] for platform specific behavior, and
|
||||
/// [`tauri_utils::platform::current_exe`] for possible security implications.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::{api::process::restart, Env, Manager};
|
||||
///
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// restart(&app.env());
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
pub fn restart(env: &Env) {
|
||||
use std::process::{exit, Command};
|
||||
|
||||
|
@ -215,6 +215,30 @@ impl Command {
|
||||
}
|
||||
|
||||
/// Spawns the command.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::api::process::{Command, CommandEvent};
|
||||
/// tauri::async_runtime::spawn(async move {
|
||||
/// let (mut rx, mut child) = Command::new("cargo")
|
||||
/// .args(["tauri", "dev"])
|
||||
/// .spawn()
|
||||
/// .expect("Failed to spawn cargo");
|
||||
///
|
||||
/// let mut i = 0;
|
||||
/// while let Some(event) = rx.recv().await {
|
||||
/// if let CommandEvent::Stdout(line) = event {
|
||||
/// println!("got: {}", line);
|
||||
/// i += 1;
|
||||
/// if i == 4 {
|
||||
/// child.write("message from Rust\n".as_bytes()).unwrap();
|
||||
/// i = 0;
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// });
|
||||
/// ```
|
||||
pub fn spawn(self) -> crate::api::Result<(Receiver<CommandEvent>, CommandChild)> {
|
||||
let mut command = get_std_command!(self);
|
||||
let (stdout_reader, stdout_writer) = pipe()?;
|
||||
@ -299,6 +323,13 @@ impl Command {
|
||||
|
||||
/// 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 {
|
||||
@ -316,6 +347,15 @@ impl Command {
|
||||
|
||||
/// 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()?;
|
||||
|
||||
|
@ -89,12 +89,28 @@ impl Program {
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens path or URL with program specified in `with`, or system default if `None`.
|
||||
/// Opens path or URL with the program specified in `with`, or system default if `None`.
|
||||
///
|
||||
/// The path will be matched against the shell open validation regex, defaulting to `^https?://`.
|
||||
/// A custom validation regex may be supplied in the config in `tauri > allowlist > scope > open`.
|
||||
pub fn open(scope: &ShellScope, path: String, with: Option<Program>) -> crate::api::Result<()> {
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::{api::shell::open, Manager};
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// // open the given URL on the system default browser
|
||||
/// open(&app.shell_scope(), "https://github.com/tauri-apps/tauri", None).unwrap();
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
pub fn open<P: AsRef<str>>(
|
||||
scope: &ShellScope,
|
||||
path: P,
|
||||
with: Option<Program>,
|
||||
) -> crate::api::Result<()> {
|
||||
scope
|
||||
.open(&path, with)
|
||||
.open(path.as_ref(), with)
|
||||
.map_err(|err| crate::api::Error::Shell(format!("failed to open: {}", err)))
|
||||
}
|
||||
|
@ -2,13 +2,31 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//! Types and functions related to semantics versioning.
|
||||
//! Compare two semantic versions.
|
||||
//!
|
||||
//! [Semantic Versioning](https://semver.org) is a guideline for how version numbers are assigned and incremented.
|
||||
//! The functions on this module are helpers around [semver](https://docs.rs/semver/latest/semver/).
|
||||
|
||||
use semver::Version;
|
||||
use std::cmp::Ordering;
|
||||
|
||||
/// Compare two semver versions
|
||||
pub fn compare(first: &str, second: &str) -> crate::api::Result<i32> {
|
||||
/// Compare two semver versions.
|
||||
///
|
||||
/// If the `first` semver is greater, returns -1.
|
||||
/// If the `second` semver is greater, returns 1.
|
||||
/// If they are equal, returns 0.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use tauri::api::version::compare;
|
||||
/// assert_eq!(compare("0.15.0", "0.15.5").unwrap(), 1);
|
||||
/// assert_eq!(compare("0.15.10", "0.15.9").unwrap(), -1);
|
||||
/// assert_eq!(compare("0.15.10", "0.16.10").unwrap(), 1);
|
||||
/// assert_eq!(compare("1.57.0", "2.17.4").unwrap(), 1);
|
||||
/// assert_eq!(compare("0.0.0", "0.0.0").unwrap(), 0);
|
||||
/// ```
|
||||
pub fn compare(first: &str, second: &str) -> crate::api::Result<i8> {
|
||||
let v1 = Version::parse(first)?;
|
||||
let v2 = Version::parse(second)?;
|
||||
match v1.cmp(&v2) {
|
||||
@ -18,7 +36,19 @@ pub fn compare(first: &str, second: &str) -> crate::api::Result<i32> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if the "second" semver is compatible with the "first"
|
||||
/// Check if the "second" semver is compatible with the "first".
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use tauri::api::version::is_compatible;
|
||||
/// assert!(is_compatible("0.15.0", "0.15.5").unwrap());
|
||||
/// assert!(!is_compatible("0.15.0", "0.16.5").unwrap());
|
||||
///
|
||||
/// assert!(is_compatible("1.5.0", "1.5.10").unwrap());
|
||||
/// assert!(is_compatible("1.54.0", "1.55.0").unwrap());
|
||||
/// assert!(!is_compatible("2.17.0", "3.17.0").unwrap());
|
||||
/// ```
|
||||
pub fn is_compatible(first: &str, second: &str) -> crate::api::Result<bool> {
|
||||
let first = Version::parse(first)?;
|
||||
let second = Version::parse(second)?;
|
||||
@ -33,28 +63,69 @@ pub fn is_compatible(first: &str, second: &str) -> crate::api::Result<bool> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Check if a the "other" version is a major bump from the "current"
|
||||
/// Check if a the "other" version is a major bump from the "current".
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use tauri::api::version::is_major;
|
||||
/// assert!(is_major("1.0.0", "2.0.0").unwrap());
|
||||
/// assert!(is_major("1.5.0", "2.17.10").unwrap());
|
||||
/// assert!(is_major("0.5.0", "2.17.10").unwrap());
|
||||
/// assert!(!is_major("1.1.5", "1.2.5").unwrap());
|
||||
/// assert!(!is_major("0.14.0", "0.15.0").unwrap());
|
||||
/// ```
|
||||
pub fn is_major(current: &str, other: &str) -> crate::api::Result<bool> {
|
||||
let current = Version::parse(current)?;
|
||||
let other = Version::parse(other)?;
|
||||
Ok(other.major > current.major)
|
||||
}
|
||||
|
||||
/// Check if a the "other" version is a minor bump from the "current"
|
||||
/// Check if a the "other" version is a minor bump from the "current".
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use tauri::api::version::is_minor;
|
||||
/// assert!(is_minor("0.15.10", "0.16.110").unwrap());
|
||||
/// assert!(is_minor("1.0.0", "1.1.1").unwrap());
|
||||
/// assert!(!is_minor("2.1.9", "3.2.0").unwrap());
|
||||
/// assert!(!is_minor("1.0.0", "1.0.10").unwrap());
|
||||
/// ```
|
||||
pub fn is_minor(current: &str, other: &str) -> crate::api::Result<bool> {
|
||||
let current = Version::parse(current)?;
|
||||
let other = Version::parse(other)?;
|
||||
Ok(current.major == other.major && other.minor > current.minor)
|
||||
}
|
||||
|
||||
/// Check if a the "other" version is a patch bump from the "current"
|
||||
/// Check if a the "other" version is a patch bump from the "current".
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use tauri::api::version::is_patch;
|
||||
/// assert!(is_patch("0.15.0", "0.15.1").unwrap());
|
||||
/// assert!(is_patch("1.0.0", "1.0.1").unwrap());
|
||||
/// assert!(!is_patch("2.2.0", "2.3.1").unwrap());
|
||||
/// assert!(!is_patch("2.2.1", "1.1.0").unwrap());
|
||||
/// ```
|
||||
pub fn is_patch(current: &str, other: &str) -> crate::api::Result<bool> {
|
||||
let current = Version::parse(current)?;
|
||||
let other = Version::parse(other)?;
|
||||
Ok(current.major == other.major && current.minor == other.minor && other.patch > current.patch)
|
||||
}
|
||||
|
||||
/// Check if a version is greater than the current
|
||||
/// Check if a version is greater than the current.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use tauri::api::version::is_greater;
|
||||
/// assert!(is_greater("0.15.10", "0.16.0").unwrap());
|
||||
/// assert!(is_greater("1.0.0", "1.0.1").unwrap());
|
||||
/// assert!(is_greater("1.1.9", "1.2.0").unwrap());
|
||||
/// assert!(is_greater("1.0.0", "2.0.0").unwrap());
|
||||
/// ```
|
||||
pub fn is_greater(current: &str, other: &str) -> crate::api::Result<bool> {
|
||||
Ok(Version::parse(other)? > Version::parse(current)?)
|
||||
}
|
||||
|
@ -445,7 +445,7 @@ impl<R: Runtime> App<R> {
|
||||
|
||||
/// Sets the activation policy for the application. It is set to `NSApplicationActivationPolicyRegular` by default.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
/// ```rust,no_run
|
||||
/// let mut app = tauri::Builder::default()
|
||||
/// // on an actual app, remove the string argument
|
||||
@ -467,7 +467,7 @@ impl<R: Runtime> App<R> {
|
||||
|
||||
/// Runs the application.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
/// ```rust,no_run
|
||||
/// let app = tauri::Builder::default()
|
||||
/// // on an actual app, remove the string argument
|
||||
@ -505,7 +505,7 @@ impl<R: Runtime> App<R> {
|
||||
/// The cleanup calls [`crate::api::process::kill_children`] so you may want to call that function before exiting the application.
|
||||
/// Additionally, the cleanup calls [AppHandle#remove_system_tray](`AppHandle#method.remove_system_tray`) (Windows only).
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
/// ```rust,no_run
|
||||
/// let mut app = tauri::Builder::default()
|
||||
/// // on an actual app, remove the string argument
|
||||
@ -589,7 +589,7 @@ impl<R: Runtime> App<R> {
|
||||
|
||||
/// Builds a Tauri application.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
/// ```rust,no_run
|
||||
/// tauri::Builder::default()
|
||||
/// // on an actual app, remove the string argument
|
||||
@ -689,7 +689,7 @@ impl<R: Runtime> Builder<R> {
|
||||
|
||||
/// Defines the JS message handler callback.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
/// ```rust,no_run
|
||||
/// #[tauri::command]
|
||||
/// fn command_1() -> String {
|
||||
@ -728,7 +728,7 @@ impl<R: Runtime> Builder<R> {
|
||||
|
||||
/// Defines the setup hook.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
/// ```rust,no_run
|
||||
/// use tauri::Manager;
|
||||
/// tauri::Builder::default()
|
||||
@ -814,7 +814,7 @@ impl<R: Runtime> Builder<R> {
|
||||
/// .expect("error while running tauri application");
|
||||
/// ```
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::State;
|
||||
@ -856,7 +856,7 @@ impl<R: Runtime> Builder<R> {
|
||||
|
||||
/// Creates a new webview window.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
/// ```rust,no_run
|
||||
/// use tauri::WindowBuilder;
|
||||
/// tauri::Builder::default()
|
||||
@ -903,7 +903,7 @@ impl<R: Runtime> Builder<R> {
|
||||
|
||||
/// Sets the menu to use on all windows.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
/// ```rust,no_run
|
||||
/// use tauri::{MenuEntry, Submenu, MenuItem, Menu, CustomMenuItem};
|
||||
///
|
||||
@ -927,7 +927,7 @@ impl<R: Runtime> Builder<R> {
|
||||
|
||||
/// Registers a menu event handler for all windows.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
/// ```rust,no_run
|
||||
/// use tauri::{Menu, MenuEntry, Submenu, CustomMenuItem, api, Manager};
|
||||
/// tauri::Builder::default()
|
||||
@ -967,7 +967,7 @@ impl<R: Runtime> Builder<R> {
|
||||
|
||||
/// Registers a window event handler for all windows.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
/// ```rust,no_run
|
||||
/// tauri::Builder::default()
|
||||
/// .on_window_event(|event| match event.event() {
|
||||
@ -991,7 +991,7 @@ impl<R: Runtime> Builder<R> {
|
||||
|
||||
/// Registers a system tray event handler.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
/// ```rust,no_run
|
||||
/// use tauri::Manager;
|
||||
/// tauri::Builder::default()
|
||||
|
@ -218,7 +218,7 @@ fn default_runtime() -> GlobalRuntime {
|
||||
/// For convinience, this method takes a [`TokioHandle`].
|
||||
/// Note that you cannot drop the underlying [`TokioRuntime`].
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// #[tokio::main]
|
||||
|
@ -161,7 +161,7 @@ impl<R: Runtime, C: DeserializeOwned> Builder<R, C> {
|
||||
/// Defines the JS message handler callback.
|
||||
/// It is recommended you use the [tauri::generate_handler] to generate the input to this method, as the input type is not considered stable yet.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// use tauri::{plugin::{Builder, TauriPlugin}, runtime::Runtime};
|
||||
@ -196,7 +196,7 @@ impl<R: Runtime, C: DeserializeOwned> Builder<R, C> {
|
||||
///
|
||||
/// It's guaranteed that this script is executed before the page is loaded.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// use tauri::{plugin::{Builder, TauriPlugin}, runtime::Runtime};
|
||||
@ -225,7 +225,7 @@ impl<R: Runtime, C: DeserializeOwned> Builder<R, C> {
|
||||
///
|
||||
/// The closure gets called before the [setup_with_config] closure.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// use tauri::{plugin::{Builder, TauriPlugin}, runtime::Runtime, Manager};
|
||||
@ -263,7 +263,7 @@ impl<R: Runtime, C: DeserializeOwned> Builder<R, C> {
|
||||
///
|
||||
/// The closure gets called after the [setup] closure.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// #[derive(serde::Deserialize)]
|
||||
@ -295,7 +295,7 @@ impl<R: Runtime, C: DeserializeOwned> Builder<R, C> {
|
||||
|
||||
/// Callback invoked when the webview performs a navigation to a page.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// use tauri::{plugin::{Builder, TauriPlugin}, runtime::Runtime};
|
||||
@ -319,7 +319,7 @@ impl<R: Runtime, C: DeserializeOwned> Builder<R, C> {
|
||||
|
||||
/// Callback invoked when the webview is created.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// use tauri::{plugin::{Builder, TauriPlugin}, runtime::Runtime};
|
||||
@ -343,7 +343,7 @@ impl<R: Runtime, C: DeserializeOwned> Builder<R, C> {
|
||||
|
||||
/// Callback invoked when the event loop receives a new event.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// use tauri::{plugin::{Builder, TauriPlugin}, RunEvent, runtime::Runtime};
|
||||
|
@ -413,7 +413,7 @@ impl<R: Runtime> Window<R> {
|
||||
/// - **macOS**: This is a private API on macOS,
|
||||
/// so you cannot use this if your application will be published on the App Store.
|
||||
///
|
||||
/// # Example
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri::Manager;
|
||||
|
Loading…
Reference in New Issue
Block a user