製作自己的 CLI
Tauri 讓您的應用程式透過 clap(一個強大的命令列引數剖析器)擁有 CLI。透過在 tauri.conf.json
檔案中加入簡單的 CLI 定義,您可以定義介面,並在 JavaScript 和/或 Rust 上讀取其引數比對清單。
基本設定
在 tauri.conf.json
中,您有以下結構來設定介面
{
"tauri": {
"cli": {
"description": "", // command description that's shown on help
"longDescription": "", // command long description that's shown on help
"beforeHelp": "", // content to show before the help text
"afterHelp": "", // content to show after the help text
"args": [], // list of arguments of the command, we'll explain it later
"subcommands": {
"subcommand-name": {
// configures a subcommand that is accessible
// with `./app subcommand-name --arg1 --arg2 --etc`
// configuration as above, with "description", "args", etc.
}
}
}
}
}
這裡的所有 JSON 設定都只是範例,為了清楚起見,已省略許多其他欄位。
新增引數
args
陣列表示其指令或子指令接受的引數清單。您可以在 這裡 找到有關如何設定它們的更多詳細資訊。
位置引數
位置引數由其在引數清單中的位置識別。使用以下設定
{
"args": [
{
"name": "source",
"index": 1,
"takesValue": true
},
{
"name": "destination",
"index": 2,
"takesValue": true
}
]
}
使用者可以將您的應用程式執行為 ./app tauri.txt dest.txt
,而引數比對會將 source
定義為 "tauri.txt"
,並將 destination
定義為 "dest.txt"
。
命名引數
命名參數是 (key, value) 成對,其中 key 會識別 value。使用下列設定
{
"args": [
{
"name": "type",
"short": "t",
"takesValue": true,
"multiple": true,
"possibleValues": ["foo", "bar"]
}
]
}
使用者可以執行應用程式為 ./app --type foo bar
、./app -t foo -t bar
或 ./app --type=foo,bar
,而 arg matches map 會將 type
定義為 ["foo", "bar"]
。
旗標參數
旗標參數是一個獨立的 key,其存在與否會提供資訊給您的應用程式。使用下列設定
{
"args": [
{
"name": "verbose",
"short": "v",
"multipleOccurrences": true
}
]
}
使用者可以執行應用程式為 ./app -v -v -v
、./app --verbose --verbose --verbose
或 ./app -vvv
,而 arg matches map 會將 verbose
定義為 true
,且 occurrences = 3
。
子命令
有些 CLI 應用程式有額外的介面作為子命令。例如,git
CLI 有 git branch
、git commit
和 git push
。您可以使用 subcommands
陣列定義額外的巢狀介面
{
"cli": {
...
"subcommands": {
"branch": {
"args": []
},
"push": {
"args": []
}
}
}
}
其設定與根應用程式設定相同,包含 description
、longDescription
、args
等。
讀取 matches
Rust
fn main() {
tauri::Builder::default()
.setup(|app| {
match app.get_cli_matches() {
// `matches` here is a Struct with { args, subcommand }.
// `args` is `HashMap<String, ArgData>` where `ArgData` is a struct with { value, occurrences }.
// `subcommand` is `Option<Box<SubcommandMatches>>` where `SubcommandMatches` is a struct with { name, matches }.
Ok(matches) => {
println!("{:?}", matches)
}
Err(_) => {}
}
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
JavaScript
import { getMatches } from '@tauri-apps/api/cli'
getMatches().then((matches) => {
// do something with the { args, subcommand } matches
})
完整文件
您可以在 這裡 找到更多關於 CLI 設定的資訊。