feat: add completions (#97)

This commit is contained in:
sigoden
2022-07-06 12:11:00 +08:00
committed by GitHub
parent 140a360e37
commit 76e967fa59
6 changed files with 75 additions and 14 deletions

View File

@@ -1,4 +1,5 @@
use clap::{AppSettings, Arg, ArgMatches, Command};
use clap::{value_parser, AppSettings, Arg, ArgMatches, Command};
use clap_complete::{generate, Generator, Shell};
#[cfg(feature = "tls")]
use rustls::{Certificate, PrivateKey};
use std::env;
@@ -11,7 +12,7 @@ use crate::auth::AuthMethod;
use crate::tls::{load_certs, load_private_key};
use crate::BoxResult;
fn app() -> Command<'static> {
pub fn build_cli() -> Command<'static> {
let app = Command::new(env!("CARGO_CRATE_NAME"))
.version(env!("CARGO_PKG_VERSION"))
.author(env!("CARGO_PKG_AUTHORS"))
@@ -118,6 +119,13 @@ fn app() -> Command<'static> {
Arg::new("render-spa")
.long("render-spa")
.help("Serve SPA(Single Page Application)"),
)
.arg(
Arg::new("completions")
.long("completions")
.value_name("shell")
.value_parser(value_parser!(Shell))
.help("Print shell completion script for <shell>"),
);
#[cfg(feature = "tls")]
@@ -138,8 +146,8 @@ fn app() -> Command<'static> {
app
}
pub fn matches() -> ArgMatches {
app().get_matches()
pub fn print_completions<G: Generator>(gen: G, cmd: &mut Command) {
generate(gen, cmd, cmd.get_name().to_string(), &mut std::io::stdout());
}
#[derive(Debug)]

View File

@@ -10,7 +10,7 @@ mod utils;
#[macro_use]
extern crate log;
use crate::args::{matches, Args};
use crate::args::{build_cli, print_completions, Args};
use crate::server::{Request, Server};
#[cfg(feature = "tls")]
use crate::tls::{TlsAcceptor, TlsStream};
@@ -19,6 +19,7 @@ use std::net::{IpAddr, SocketAddr, TcpListener as StdTcpListener};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use clap_complete::Shell;
use futures::future::join_all;
use tokio::net::TcpListener;
use tokio::task::JoinHandle;
@@ -37,7 +38,14 @@ async fn main() {
async fn run() -> BoxResult<()> {
logger::init().map_err(|e| format!("Failed to init logger, {}", e))?;
let args = Args::parse(matches())?;
let cmd = build_cli();
let matches = cmd.get_matches();
if let Some(generator) = matches.get_one::<Shell>("completions") {
let mut cmd = build_cli();
print_completions(*generator, &mut cmd);
return Ok(());
}
let args = Args::parse(matches)?;
let args = Arc::new(args);
let running = Arc::new(AtomicBool::new(true));
let handles = serve(args.clone(), running.clone())?;