From 698f8c2f01ea549d77d7dc3338a12e04c11057b9 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Wed, 17 Apr 2024 14:02:58 +0200 Subject: Adding upstream version 1.64.0+dfsg1. Signed-off-by: Daniel Baumann --- vendor/xflags/.cargo-checksum.json | 1 + vendor/xflags/Cargo.lock | 16 ++ vendor/xflags/Cargo.toml | 23 +++ vendor/xflags/LICENSE-APACHE | 201 +++++++++++++++++++++ vendor/xflags/LICENSE-MIT | 23 +++ vendor/xflags/README.md | 49 +++++ vendor/xflags/examples/hello-generated.rs | 52 ++++++ vendor/xflags/examples/hello.rs | 22 +++ vendor/xflags/examples/longer.rs | 93 ++++++++++ vendor/xflags/examples/non-utf8.rs | 43 +++++ vendor/xflags/src/lib.rs | 289 ++++++++++++++++++++++++++++++ vendor/xflags/src/rt.rs | 114 ++++++++++++ 12 files changed, 926 insertions(+) create mode 100644 vendor/xflags/.cargo-checksum.json create mode 100644 vendor/xflags/Cargo.lock create mode 100644 vendor/xflags/Cargo.toml create mode 100644 vendor/xflags/LICENSE-APACHE create mode 100644 vendor/xflags/LICENSE-MIT create mode 100644 vendor/xflags/README.md create mode 100644 vendor/xflags/examples/hello-generated.rs create mode 100644 vendor/xflags/examples/hello.rs create mode 100644 vendor/xflags/examples/longer.rs create mode 100644 vendor/xflags/examples/non-utf8.rs create mode 100644 vendor/xflags/src/lib.rs create mode 100644 vendor/xflags/src/rt.rs (limited to 'vendor/xflags') diff --git a/vendor/xflags/.cargo-checksum.json b/vendor/xflags/.cargo-checksum.json new file mode 100644 index 000000000..c5fd48200 --- /dev/null +++ b/vendor/xflags/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.lock":"76747bdf0a7c1643e62a7c8db6e65572906908415ba87daaa7444917cdf1d35b","Cargo.toml":"32dc60919f757b61d4a6602da24bdd59b77b76f284a1b55712a78e1159e2d249","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"d34d354ca65973ca9120ed16af11e188c91af2ede6894e0e842c10c874780f7b","examples/hello-generated.rs":"ac2d4864e238e664fb1b18db66aed75ac5a425877bc00729fed1135fb410b969","examples/hello.rs":"c1a5656bee529c3ef96a3afc3531e02bc9d5d309e1bcd60b76e6758fb4c2a95d","examples/longer.rs":"18ad0d00215fdf245830a581df32fbf9533f5ab47e736659e598b4ecd2d96e1a","examples/non-utf8.rs":"a9d4a03adb05c8b46c3251647b8dbf4e860277db995e14192cd8d445f3434186","src/lib.rs":"21843e64aba8010dcc877418927e5b0ad3615ff6e18020285849bbf4391f4ed0","src/rt.rs":"c3cb2d6c80ec9c0586a6e64441cee4c237d2fb420891dec2acb96d5b0c7d6937"},"package":"3f14fe1ed41a5a2b5ef3f565586c4a8a559ee55d3953faab360a771135bdee00"} \ No newline at end of file diff --git a/vendor/xflags/Cargo.lock b/vendor/xflags/Cargo.lock new file mode 100644 index 000000000..37ff98bb9 --- /dev/null +++ b/vendor/xflags/Cargo.lock @@ -0,0 +1,16 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "xflags" +version = "0.2.4" +dependencies = [ + "xflags-macros", +] + +[[package]] +name = "xflags-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45d11d5fc2a97287eded8b170ca80533b3c42646dd7fa386a5eb045817921022" diff --git a/vendor/xflags/Cargo.toml b/vendor/xflags/Cargo.toml new file mode 100644 index 000000000..542701052 --- /dev/null +++ b/vendor/xflags/Cargo.toml @@ -0,0 +1,23 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +name = "xflags" +version = "0.2.4" +authors = ["Aleksey Kladov "] +exclude = [".github/", "bors.toml", "rustfmt.toml"] +description = "Moderately simple command line arguments parser." +categories = ["command-line-interface"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/matklad/xflags" +[dependencies.xflags-macros] +version = "=0.2.4" diff --git a/vendor/xflags/LICENSE-APACHE b/vendor/xflags/LICENSE-APACHE new file mode 100644 index 000000000..16fe87b06 --- /dev/null +++ b/vendor/xflags/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/vendor/xflags/LICENSE-MIT b/vendor/xflags/LICENSE-MIT new file mode 100644 index 000000000..31aa79387 --- /dev/null +++ b/vendor/xflags/LICENSE-MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/vendor/xflags/README.md b/vendor/xflags/README.md new file mode 100644 index 000000000..bfebfb0c8 --- /dev/null +++ b/vendor/xflags/README.md @@ -0,0 +1,49 @@ +[![API reference](https://docs.rs/once_cell/badge.svg)](https://docs.rs/xflags/) + +# xflags + +Moderately simple command line arguments parsing: + +```rust +mod flags { + use std::path::PathBuf; + + xflags::xflags! { + src "./examples/basic.rs" + + cmd my-command + required path: PathBuf + { + optional -v, --verbose + } + } + + // generated start + // The following code is generated by `xflags` macro. + // Run `env UPDATE_XFLAGS=1 cargo build` to regenerate. + #[derive(Debug)] + pub struct MyCommand { + pub path: PathBuf, + + pub verbose: bool, + } + + impl MyCommand { + pub const HELP: &'static str = Self::HELP_; + + pub fn from_env() -> xflags::Result { + Self::from_env_() + } + + pub fn from_vec(args: Vec) -> xflags::Result { + Self::from_vec_(args) + } + } + // generated end +} + +fn main() { + let flags = flags::MyCommand::from_env(); + println!("{:#?}", flags); +} +``` diff --git a/vendor/xflags/examples/hello-generated.rs b/vendor/xflags/examples/hello-generated.rs new file mode 100644 index 000000000..b82884859 --- /dev/null +++ b/vendor/xflags/examples/hello-generated.rs @@ -0,0 +1,52 @@ +mod flags { + #![allow(unused)] + + xflags::xflags! { + src "./examples/hello-generated.rs" + + /// Prints a greeting. + cmd hello + /// Whom to greet. + required name: String + { + /// Use non-ascii symbols in the output. + optional -e, --emoji + } + } + + // generated start + // The following code is generated by `xflags` macro. + // Run `env UPDATE_XFLAGS=1 cargo build` to regenerate. + #[derive(Debug)] + pub struct Hello { + pub name: String, + + pub emoji: bool, + } + + impl Hello { + pub const HELP: &'static str = Self::HELP_; + + pub fn from_env() -> xflags::Result { + Self::from_env_() + } + + pub fn from_vec(args: Vec) -> xflags::Result { + Self::from_vec_(args) + } + } + // generated end +} + +fn main() { + match flags::Hello::from_env() { + Ok(flags) => { + let bang = if flags.emoji { "❣️" } else { "!" }; + println!("Hello {}{}", flags.name, bang); + } + Err(err) => { + eprintln!("{}\n\n{}", err, flags::Hello::HELP); + std::process::exit(1) + } + } +} diff --git a/vendor/xflags/examples/hello.rs b/vendor/xflags/examples/hello.rs new file mode 100644 index 000000000..98a19099f --- /dev/null +++ b/vendor/xflags/examples/hello.rs @@ -0,0 +1,22 @@ +mod flags { + xflags::xflags! { + cmd hello + required name: String + { + optional -e, --emoji + } + } +} + +fn main() { + match flags::Hello::from_env() { + Ok(flags) => { + let bang = if flags.emoji { "❣️" } else { "!" }; + println!("Hello {}{}", flags.name, bang); + } + Err(err) => { + eprintln!("{}", err); + std::process::exit(1) + } + } +} diff --git a/vendor/xflags/examples/longer.rs b/vendor/xflags/examples/longer.rs new file mode 100644 index 000000000..7ea9e18d5 --- /dev/null +++ b/vendor/xflags/examples/longer.rs @@ -0,0 +1,93 @@ +mod flags { + #![allow(unused)] + + use std::path::PathBuf; + + xflags::xflags! { + src "./examples/longer.rs" + + cmd rust-analyzer { + /// Set verbosity level + repeated -v, --verbose + /// Log to the specified file instead of stderr. + optional --log-file path: PathBuf + + default cmd run-server { + /// Print version + optional --version + } + + /// Parse tree + cmd parse { + /// Suppress printing + optional --no-dump + } + + /// Benchmark specific analysis operation + cmd analysis-bench + /// Directory with Cargo.toml + optional path: PathBuf + { + /// Compute syntax highlighting for this file + required --highlight path: PathBuf + /// Compute highlighting for this line + optional --line num: u32 + } + } + } + + // generated start + // The following code is generated by `xflags` macro. + // Run `env UPDATE_XFLAGS=1 cargo build` to regenerate. + #[derive(Debug)] + pub struct RustAnalyzer { + pub verbose: u32, + pub log_file: Option, + pub subcommand: RustAnalyzerCmd, + } + + #[derive(Debug)] + pub enum RustAnalyzerCmd { + RunServer(RunServer), + Parse(Parse), + AnalysisBench(AnalysisBench), + } + + #[derive(Debug)] + pub struct RunServer { + pub version: bool, + } + + #[derive(Debug)] + pub struct Parse { + pub no_dump: bool, + } + + #[derive(Debug)] + pub struct AnalysisBench { + pub path: Option, + + pub highlight: PathBuf, + pub line: Option, + } + + impl RustAnalyzer { + pub const HELP: &'static str = Self::HELP_; + + pub fn from_env() -> xflags::Result { + Self::from_env_() + } + + pub fn from_vec(args: Vec) -> xflags::Result { + Self::from_vec_(args) + } + } + // generated end +} + +fn main() { + match flags::RustAnalyzer::from_env() { + Ok(flags) => eprintln!("{:#?}", flags), + Err(err) => eprintln!("{}", err), + } +} diff --git a/vendor/xflags/examples/non-utf8.rs b/vendor/xflags/examples/non-utf8.rs new file mode 100644 index 000000000..d355b24f6 --- /dev/null +++ b/vendor/xflags/examples/non-utf8.rs @@ -0,0 +1,43 @@ +use std::ffi::OsString; + +mod flags { + use std::{ffi::OsString, path::PathBuf}; + + xflags::xflags! { + cmd Cmd + required a: OsString + required b: PathBuf + required c: String + { + } + } +} + +#[cfg(unix)] +fn main() { + use std::os::unix::ffi::OsStringExt; + + let flags = flags::Cmd::from_vec(vec![ + OsString::from_vec(vec![254].into()), + OsString::from_vec(vec![255].into()), + "utf8".into(), + ]); + + eprintln!("flags = {:?}", flags); +} + +#[cfg(windows)] +fn main() { + use std::os::windows::ffi::OsStringExt; + + let flags = flags::Cmd::from_vec(vec![ + OsString::from_wide(&[0xD800]), + OsString::from_wide(&[0xDC00]), + "utf8".into(), + ]); + + eprintln!("flags = {:?}", flags); +} + +#[cfg(not(any(unix, windows)))] +fn main() {} diff --git a/vendor/xflags/src/lib.rs b/vendor/xflags/src/lib.rs new file mode 100644 index 000000000..ae347f511 --- /dev/null +++ b/vendor/xflags/src/lib.rs @@ -0,0 +1,289 @@ +//! This crates provides a procedural macro for parsing command line arguments. +//! +//! It is intended for use in development tools, so it emphasizes fast compile +//! times and convenience at the expense of features. +//! +//! If you need something more fancy, consider using +//! [`clap`](https://docs.rs/clap/2.33.3/clap/) instead. +//! +//! ## Example +//! +//! ``` +//! mod flags { +//! use std::path::PathBuf; +//! +//! xflags::xflags! { +//! src "./examples/basic.rs" +//! +//! cmd my-command +//! required path: PathBuf +//! { +//! optional -v, --verbose +//! } +//! } +//! +//! // generated start +//! // The following code is generated by `xflags` macro. +//! // Run `env UPDATE_XFLAGS=1 cargo build` to regenerate. +//! #[derive(Debug)] +//! pub struct MyCommand { +//! pub path: PathBuf, +//! +//! pub verbose: bool, +//! } +//! +//! impl MyCommand { +//! pub const HELP: &'static str = Self::HELP_; +//! +//! pub fn from_env() -> xflags::Result { +//! Self::from_env_() +//! } +//! +//! pub fn from_vec(args: Vec) -> xflags::Result { +//! Self::from_vec_(args) +//! } +//! } +//! // generated end +//! } +//! +//! fn main() { +//! let flags = flags::MyCommand::from_env(); +//! println!("{:#?}", flags); +//! } +//! ``` +//! +//! To make the macro less opaque, `xflag` can generate `struct` describing the +//! CLI in-place. To disable this behavior, omit the `src` attribute. +//! +//! xflags correctly handles non-utf8 arguments. +//! +//! ## Syntax Reference +//! +//! The **cmd** keyword introduces a command that accepts positional arguments +//! and switches. +//! +//! ``` +//! xflags::xflags! { +//! cmd command-name { } +//! } +//! ``` +//! +//! Switches are specified inside the curly braces. Long names (`--switch`) are +//! mandatory, short names (`-s`) are optional. Each switch can be **optional**, +//! **required**, or **repeated**. Dashes are allowed in switch names. +//! +//! ``` +//! xflags::xflags! { +//! cmd switches { +//! optional -h, --help +//! repeated --verbose +//! required --pass-me +//! } +//! } +//! ``` +//! +//! Switches can also take values. If the value type is `OsString` or `PathBuf`, +//! it is created directly from the underlying argument. Otherwise, `FromStr` is +//! used for parsing +//! +//! ``` +//! use std::{path::PathBuf, ffi::OsString}; +//! +//! xflags::xflags! { +//! cmd switches-with-values { +//! optional --config path: PathBuf +//! repeated --data val: OsString +//! optional -j, --jobs n: u32 +//! } +//! } +//! ``` +//! +//! Positional arguments are specified before the opening curly brace: +//! +//! ``` +//! use std::{path::PathBuf, ffi::OsString}; +//! +//! xflags::xflags! { +//! cmd positional-arguments +//! required program: PathBuf +//! repeated args: OsString +//! { } +//! } +//! ``` +//! +//! Nesting **cmd** is allowed: +//! +//! ```ignore +//! xflags::xflags! { +//! src "./examples/subcommands.rs" +//! cmd app { +//! repeated -v, --verbose +//! cmd foo { optional -s, --switch } +//! cmd bar {} +//! } +//! } +//! +//! // generated start +//! // The following code is generated by `xflags` macro. +//! // Run `env UPDATE_XFLAGS=1 cargo build` to regenerate. +//! #[derive(Debug)] +//! pub struct App { +//! pub verbose: u32, +//! pub subcommand: AppCmd, +//! } +//! +//! #[derive(Debug)] +//! pub enum AppCmd { +//! Foo(Foo), +//! Bar(Bar), +//! } +//! +//! #[derive(Debug)] +//! pub struct Foo { +//! pub switch: bool, +//! } +//! +//! #[derive(Debug)] +//! pub struct Bar { +//! } +//! +//! impl App { +//! pub const HELP: &'static str = Self::HELP_; +//! +//! pub fn from_env() -> xflags::Result { +//! Self::from_env_() +//! } +//! +//! pub fn from_vec(args: Vec) -> xflags::Result { +//! Self::from_vec_(args) +//! } +//! } +//! // generated end +//! ``` +//! +//! To make subcommand name optional use the **default** keyword to mark a +//! subcommand to select if no subcommand name is passed. The name of the +//! default subcommand affects only the name of the generated Rust struct, it +//! can't be specified explicitly on the command line. +//! +//! ``` +//! xflags::xflags! { +//! cmd app { +//! repeated -v, --verbose +//! default cmd foo { optional -s, --switch } +//! cmd bar {} +//! } +//! } +//! ``` +//! +//! Commands, arguments, and switches can documented. Doc comments become a part +//! of generated help: +//! +//! ``` +//! mod flags { +//! use std::path::PathBuf; +//! +//! xflags::xflags! { +//! /// Run basic system diagnostics. +//! cmd healthck +//! /// Optional configuration file. +//! optional config: PathBuf +//! { +//! /// Verbosity level, can be repeated multiple times. +//! repeated -v, --verbose +//! /// Print the help message. +//! optional -h, --help +//! } +//! } +//! } +//! +//! fn main() { +//! match flags::Healthck::from_env() { +//! Ok(flags) => { +//! if flags.help { +//! println!("{}", flags::Healthck::HELP); +//! return; +//! } +//! run_checks(flags.config, flags.verbose); +//! } +//! Err(err) => { +//! eprintln!("{}", err); +//! } +//! } +//! } +//! +//! # fn run_checks(_config: Option, _verbosity: u32) {} +//! ``` +//! +//! The **src** keyword controlls how the code generation works. If it is +//! absent, `xflags` acts as a typical procedure macro, which generates a bunch +//! of structs and impls. +//! +//! If the **src** keyword is present, it should specify the path to the file +//! with `xflags!` invocation. The path should be relative to the directory with +//! Cargo.toml. The macro then will avoid generating the structs. Instead, if +//! the `UPDATE_XFLAGS` environmental variable is set, the macro will write them +//! directly to the specified file. +//! +//! By convention, `xflag!` macro should be invoked from the `flags` submodule. +//! The `flags::` preffix should be used to refer to command names. Additional +//! validation logic can go to the `flags` module: +//! +//! ``` +//! mod flags { +//! xflags::xflags! { +//! cmd my-command { +//! repeated -v, --verbose +//! optional -q, --quiet +//! } +//! } +//! +//! impl MyCommand { +//! fn validate(&self) -> xflags::Result<()> { +//! if self.quiet && self.verbose > 0 { +//! return Err(xflags::Error::new( +//! "`-q` and `-v` can't be specified at the same time" +//! )); +//! } +//! Ok(()) +//! } +//! } +//! } +//! ``` + +use std::fmt; + +/// Generates a parser for command line arguments from a DSL. +/// +/// See the module-level for detailed syntax specification. +pub use xflags_macros::xflags; + +pub type Result = std::result::Result; + +/// This type represents an error that can occur during command line argument +/// parsing. +#[derive(Debug)] +pub struct Error { + msg: String, +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&self.msg, f) + } +} + +impl std::error::Error for Error {} + +impl Error { + /// Creates a new `Error` from a given message. + /// + /// Use this to report custom validation errors. + pub fn new(message: impl Into) -> Error { + Error { msg: message.into() } + } +} + +/// Private impl details for macros. +#[doc(hidden)] +pub mod rt; diff --git a/vendor/xflags/src/rt.rs b/vendor/xflags/src/rt.rs new file mode 100644 index 000000000..3c33196af --- /dev/null +++ b/vendor/xflags/src/rt.rs @@ -0,0 +1,114 @@ +use std::{ffi::OsString, fmt, str::FromStr}; + +use crate::{Error, Result}; + +macro_rules! format_err { + ($($tt:tt)*) => { + Error { msg: format!($($tt)*) } + }; +} + +macro_rules! bail { + ($($tt:tt)*) => { + return Err(format_err!($($tt)*)) + }; +} + +pub struct Parser { + rargs: Vec, +} + +impl Parser { + pub fn new(mut args: Vec) -> Self { + args.reverse(); + Self { rargs: args } + } + + pub fn new_from_env() -> Self { + let mut args = std::env::args_os().collect::>(); + args.reverse(); + args.pop(); + Self { rargs: args } + } + + pub fn is_empty(&self) -> bool { + self.rargs.is_empty() + } + + pub fn peek_flag(&self) -> Option<&str> { + self.rargs.last().and_then(|it| it.to_str()).filter(|it| it.starts_with('-')) + } + pub fn pop_flag(&mut self) -> Option> { + if self.peek_flag().is_some() { + self.next().map(|it| it.into_string()) + } else { + self.next().map(Err) + } + } + pub fn push_back(&mut self, arg: Result) { + let arg = match arg { + Ok(it) => it.into(), + Err(it) => it, + }; + self.rargs.push(arg) + } + + pub fn next(&mut self) -> Option { + self.rargs.pop() + } + + pub fn next_value(&mut self, flag: &str) -> Result { + if self.peek_flag().is_some() { + bail!("expected a value for `{}`", flag) + } + self.next().ok_or_else(|| format_err!("expected a value for `{}`", flag)) + } + + pub fn next_value_from_str(&mut self, flag: &str) -> Result + where + T::Err: fmt::Display, + { + let value = self.next_value(flag)?; + self.value_from_str(flag, value) + } + + pub fn value_from_str(&mut self, flag: &str, value: OsString) -> Result + where + T::Err: fmt::Display, + { + match value.into_string() { + Ok(str) => { + str.parse::().map_err(|err| format_err!("can't parse `{}`, {}", flag, err)) + } + Err(it) => { + bail!("can't parse `{}`, invalid utf8: {:?}", flag, it) + } + } + } + + pub fn unexpected_flag(&self, flag: &str) -> Error { + format_err!("unexpected flag: `{}`", flag) + } + + pub fn unexpected_arg(&self, arg: OsString) -> Error { + format_err!("unexpected argument: {:?}", arg) + } + + pub fn optional(&self, flag: &str, mut vals: Vec) -> Result> { + if vals.len() > 1 { + bail!("flag specified more than once: `{}`", flag) + } + Ok(vals.pop()) + } + + pub fn required(&self, flag: &str, mut vals: Vec) -> Result { + if vals.len() > 1 { + bail!("flag specified more than once: `{}`", flag) + } + vals.pop().ok_or_else(|| format_err!("flag is required: `{}`", flag)) + } + + pub fn subcommand(&self, cmd: Option) -> Result { + cmd.ok_or_else(|| format_err!("subcommand is required")) + } +} -- cgit v1.2.3