diff options
| author | 魏曹先生 <1992414357@qq.com> | 2026-03-29 21:48:23 +0800 |
|---|---|---|
| committer | 魏曹先生 <1992414357@qq.com> | 2026-03-29 21:48:23 +0800 |
| commit | 596e5e2440df2d32f1cf3e052dc633e774edf6ee (patch) | |
| tree | dc98eb6a1789847b899207d0b99337bb3ccd92a5 /mingling | |
| parent | 25a164f74c011e6e78846f226cbd7a8bd87db92f (diff) | |
Rename mingling to mingling_core and update dependencies
Diffstat (limited to 'mingling')
| -rw-r--r-- | mingling/Cargo.lock | 297 | ||||
| -rw-r--r-- | mingling/Cargo.toml | 24 | ||||
| -rw-r--r-- | mingling/LICENSE-APACHE | 202 | ||||
| -rw-r--r-- | mingling/LICENSE-MIT | 9 | ||||
| -rw-r--r-- | mingling/README.md | 70 | ||||
| -rw-r--r-- | mingling/src/any.rs | 128 | ||||
| -rw-r--r-- | mingling/src/asset.rs | 4 | ||||
| -rw-r--r-- | mingling/src/asset/chain.rs | 8 | ||||
| -rw-r--r-- | mingling/src/asset/chain/error.rs | 13 | ||||
| -rw-r--r-- | mingling/src/asset/dispatcher.rs | 195 | ||||
| -rw-r--r-- | mingling/src/asset/node.rs | 54 | ||||
| -rw-r--r-- | mingling/src/asset/renderer.rs | 6 | ||||
| -rw-r--r-- | mingling/src/lib.rs | 39 | ||||
| -rw-r--r-- | mingling/src/program.rs | 132 | ||||
| -rw-r--r-- | mingling/src/program/config.rs | 26 | ||||
| -rw-r--r-- | mingling/src/program/exec.rs | 126 | ||||
| -rw-r--r-- | mingling/src/program/exec/error.rs | 46 | ||||
| -rw-r--r-- | mingling/src/program/flag.rs | 148 | ||||
| -rw-r--r-- | mingling/src/program/hint.rs | 62 | ||||
| -rw-r--r-- | mingling/src/program/setup.rs | 19 | ||||
| -rw-r--r-- | mingling/src/program/setup/basic.rs | 31 | ||||
| -rw-r--r-- | mingling/src/renderer.rs | 1 | ||||
| -rw-r--r-- | mingling/src/renderer/render_result.rs | 38 |
23 files changed, 0 insertions, 1678 deletions
diff --git a/mingling/Cargo.lock b/mingling/Cargo.lock deleted file mode 100644 index cf6b520..0000000 --- a/mingling/Cargo.lock +++ /dev/null @@ -1,297 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "bitflags" -version = "2.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" - -[[package]] -name = "bytes" -version = "1.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" - -[[package]] -name = "cfg-if" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" - -[[package]] -name = "errno" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" -dependencies = [ - "libc", - "windows-sys", -] - -[[package]] -name = "just_fmt" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5454cda0d57db59778608d7a47bff5b16c6705598265869fb052b657f66cf05e" - -[[package]] -name = "libc" -version = "0.2.183" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d" - -[[package]] -name = "lock_api" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" -dependencies = [ - "scopeguard", -] - -[[package]] -name = "mingling" -version = "0.1.0" -dependencies = [ - "just_fmt", - "mingling_macros", - "serde", - "thiserror", - "tokio", -] - -[[package]] -name = "mingling_macros" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3790886e4504e486d8c963988e5780212ccc05c5d03a5d27fa2ba67e1dd3f13b" -dependencies = [ - "just_fmt", - "once_cell", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "mio" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" -dependencies = [ - "libc", - "wasi", - "windows-sys", -] - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - -[[package]] -name = "parking_lot" -version = "0.12.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall", - "smallvec", - "windows-link", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - -[[package]] -name = "proc-macro2" -version = "1.0.106" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quote" -version = "1.0.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "redox_syscall" -version = "0.5.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" -dependencies = [ - "bitflags", -] - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "serde" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde_core" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "signal-hook-registry" -version = "1.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" -dependencies = [ - "errno", - "libc", -] - -[[package]] -name = "smallvec" -version = "1.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" - -[[package]] -name = "socket2" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" -dependencies = [ - "libc", - "windows-sys", -] - -[[package]] -name = "syn" -version = "2.0.117" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "thiserror" -version = "2.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tokio" -version = "1.50.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27ad5e34374e03cfffefc301becb44e9dc3c17584f414349ebe29ed26661822d" -dependencies = [ - "bytes", - "libc", - "mio", - "parking_lot", - "pin-project-lite", - "signal-hook-registry", - "socket2", - "tokio-macros", - "windows-sys", -] - -[[package]] -name = "tokio-macros" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c55a2eff8b69ce66c84f85e1da1c233edc36ceb85a2058d11b0d6a3c7e7569c" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "unicode-ident" -version = "1.0.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" - -[[package]] -name = "wasi" -version = "0.11.1+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] diff --git a/mingling/Cargo.toml b/mingling/Cargo.toml deleted file mode 100644 index d7e820c..0000000 --- a/mingling/Cargo.toml +++ /dev/null @@ -1,24 +0,0 @@ -[package] -name = "mingling" -version = "0.1.0" -edition = "2024" -authors = ["Weicao-CatilGrass"] -license = "MIT OR Apache-2.0" -readme = "README.md" -description = "A procedural command-line framework with subcommand support" -keywords = ["cli", "framework", "procedural", "subcommand", "command-line"] -categories = ["command-line-interface"] -repository = "https://github.com/catilgrass/mingling" - -[features] -full = ["macros", "general_renderer"] -default = ["macros"] -macros = ["mingling_macros"] -general_renderer = ["dep:serde", "mingling_macros/serde"] - -[dependencies] -mingling_macros = { version = "0.1.0", optional = true } -just_fmt = "0.1.2" -serde = { version = "1.0", features = ["derive"], optional = true } -thiserror = "2" -tokio = { version = "1", features = ["full"] } diff --git a/mingling/LICENSE-APACHE b/mingling/LICENSE-APACHE deleted file mode 100644 index 506aeb9..0000000 --- a/mingling/LICENSE-APACHE +++ /dev/null @@ -1,202 +0,0 @@ - - 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 2026 MinglingRS Team, Weicao-CatilGrass - - 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/mingling/LICENSE-MIT b/mingling/LICENSE-MIT deleted file mode 100644 index ec48781..0000000 --- a/mingling/LICENSE-MIT +++ /dev/null @@ -1,9 +0,0 @@ -# The MIT License (MIT) - -Copyright © 2026 MinglingRS Team, Weicao-CatilGrass - -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/mingling/README.md b/mingling/README.md deleted file mode 100644 index 506d5ce..0000000 --- a/mingling/README.md +++ /dev/null @@ -1,70 +0,0 @@ -# Mìng Lìng - 命令 - -> [!WARNING] -> -> **Note**: Mingling is still under active development, and its API may change. Feel free to try it out and give us feedback! - -`Mingling` is a Rust command-line framework. Its name comes from the Chinese Pinyin for "命令", which means "Command". - -## Quick Start - -The example below shows how to use `Mingling` to create a simple command-line program: - -```rust -use mingling::{ - hint::NoDispatcherFound, - macros::{dispatcher, program, r_println, renderer}, -}; - -#[tokio::main] -async fn main() { - let mut program = MyProgram::new(); - program.with_dispatcher(HelloCommand); - program.exec().await; -} - -dispatcher!("hello", HelloCommand => HelloEntry); - -#[renderer] -pub fn render_hello(_prev: HelloEntry) { - r_println!("Hello, World!") -} - -#[renderer] -pub fn render_no_dispatcher_found(prev: NoDispatcherFound) { - r_println!("Subcommand not found: '{}'", prev.args.join(", ")) -} - -program!(MyProgram); -``` - -Output: - -``` -> mycmd hello -Hello, World! -> mycmd hallo -Subcommand not found: 'mycmd hallo' -``` - -## Core Concepts - -Mingling abstracts command execution into the following parts: - -1. **Dispatcher** - Routes user input to a specific renderer or chain based on the command node name. -2. **Chain** - Transforms the incoming type into another type, passing it to the next chain or renderer. -3. **Renderer** - Stops the chain and prints the currently processed type to the terminal. -4. **Program** - Manages the lifecycle and configuration of the entire CLI application. - -## Project Structure - -The Mingling project consists of two main parts: - -- **[mingling/](mingling/)** - The core runtime library, containing type definitions, error handling, and basic functionality. -- **[mingling_macros/](mingling_macros/)** - The procedural macro library, providing declarative macros to simplify development. - -## License - -This project is licensed under the MIT License. - -See [LICENSE-MIT](LICENSE-MIT) or [LICENSE-APACHE](LICENSE-APACHE) file for details. diff --git a/mingling/src/any.rs b/mingling/src/any.rs deleted file mode 100644 index 1bce96a..0000000 --- a/mingling/src/any.rs +++ /dev/null @@ -1,128 +0,0 @@ -#[cfg(feature = "general_renderer")] -use serde::Serialize; - -use crate::error::ChainProcessError; - -#[derive(Debug)] -pub struct AnyOutput { - inner: Box<dyn std::any::Any + Send + 'static>, - pub type_id: std::any::TypeId, -} - -impl AnyOutput { - #[cfg(feature = "general_renderer")] - pub fn new<T>(value: T) -> Self - where - T: Send + Serialize + 'static, - { - Self { - inner: Box::new(value), - type_id: std::any::TypeId::of::<T>(), - } - } - - #[cfg(not(feature = "general_renderer"))] - pub fn new<T>(value: T) -> Self - where - T: Send + 'static, - { - Self { - inner: Box::new(value), - type_id: std::any::TypeId::of::<T>(), - } - } - - pub fn downcast<T: 'static>(self) -> Result<T, Self> { - if self.type_id == std::any::TypeId::of::<T>() { - Ok(*self.inner.downcast::<T>().unwrap()) - } else { - Err(self) - } - } - - pub fn is<T: 'static>(&self) -> bool { - self.type_id == std::any::TypeId::of::<T>() - } - - /// Route the output to the next Chain - pub fn route_chain(self) -> ChainProcess { - ChainProcess::Ok((self, Next::Chain)) - } - - /// Route the output to the Renderer, ending execution - pub fn route_renderer(self) -> ChainProcess { - ChainProcess::Ok((self, Next::Renderer)) - } -} - -impl std::ops::Deref for AnyOutput { - type Target = dyn std::any::Any + Send + 'static; - - fn deref(&self) -> &Self::Target { - &*self.inner - } -} - -impl std::ops::DerefMut for AnyOutput { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut *self.inner - } -} - -pub enum ChainProcess { - Ok((AnyOutput, Next)), - Err(ChainProcessError), -} - -pub enum Next { - Chain, - Renderer, -} - -impl ChainProcess { - pub fn is_next(&self) -> bool { - matches!(self, Self::Ok(_)) - } - - pub fn is_err(&self) -> bool { - matches!(self, Self::Err(_)) - } - - pub fn next(&self) -> Option<&Next> { - match self { - Self::Ok((_, next)) => Some(next), - Self::Err(_) => None, - } - } - - pub fn err(&self) -> Option<&ChainProcessError> { - match self { - Self::Ok(_) => None, - Self::Err(err) => Some(err), - } - } - - pub fn unwrap(self) -> (AnyOutput, Next) { - match self { - Self::Ok(tuple) => tuple, - Self::Err(_) => panic!("called `ChainProcess2::unwrap()` on an `Error` value"), - } - } - - pub fn unwrap_or(self, default: (AnyOutput, Next)) -> (AnyOutput, Next) { - match self { - Self::Ok(tuple) => tuple, - Self::Err(_) => default, - } - } - - pub fn unwrap_or_else<F>(self, f: F) -> (AnyOutput, Next) - where - F: FnOnce(ChainProcessError) -> (AnyOutput, Next), - { - match self { - Self::Ok(tuple) => tuple, - Self::Err(err) => f(err), - } - } -} diff --git a/mingling/src/asset.rs b/mingling/src/asset.rs deleted file mode 100644 index c2adf4e..0000000 --- a/mingling/src/asset.rs +++ /dev/null @@ -1,4 +0,0 @@ -pub mod chain; -pub mod dispatcher; -pub mod node; -pub mod renderer; diff --git a/mingling/src/asset/chain.rs b/mingling/src/asset/chain.rs deleted file mode 100644 index 1ea1125..0000000 --- a/mingling/src/asset/chain.rs +++ /dev/null @@ -1,8 +0,0 @@ -use crate::ChainProcess; - -pub mod error; - -pub trait Chain { - type Previous; - fn proc(p: Self::Previous) -> impl Future<Output = ChainProcess> + Send; -} diff --git a/mingling/src/asset/chain/error.rs b/mingling/src/asset/chain/error.rs deleted file mode 100644 index d4da4ac..0000000 --- a/mingling/src/asset/chain/error.rs +++ /dev/null @@ -1,13 +0,0 @@ -use crate::AnyOutput; - -#[derive(thiserror::Error, Debug)] -pub enum ChainProcessError { - #[error("Other error: {0}")] - Other(String), - - #[error("IO error: {0}")] - IO(#[from] std::io::Error), - - #[error("Broken chain")] - Broken(AnyOutput), -} diff --git a/mingling/src/asset/dispatcher.rs b/mingling/src/asset/dispatcher.rs deleted file mode 100644 index 13e35f7..0000000 --- a/mingling/src/asset/dispatcher.rs +++ /dev/null @@ -1,195 +0,0 @@ -use crate::{ChainProcess, Program, asset::node::Node}; - -pub trait Dispatcher { - fn node(&self) -> Node; - fn begin(&self, args: Vec<String>) -> ChainProcess; - fn clone_dispatcher(&self) -> Box<dyn Dispatcher>; -} - -impl Clone for Box<dyn Dispatcher> { - fn clone(&self) -> Self { - self.clone_dispatcher() - } -} - -impl<C: crate::program::ProgramCollect> Program<C> { - /// Adds a dispatcher to the program. - pub fn with_dispatcher<D>(&mut self, dispatcher: D) - where - D: Into<Dispatchers>, - { - let dispatchers = dispatcher.into().dispatcher; - self.dispatcher.extend(dispatchers); - } -} - -pub struct Dispatchers { - dispatcher: Vec<Box<dyn Dispatcher + 'static>>, -} - -impl<D> From<D> for Dispatchers -where - D: Dispatcher + 'static, -{ - fn from(dispatcher: D) -> Self { - Self { - dispatcher: vec![Box::new(dispatcher)], - } - } -} - -impl From<Vec<Box<dyn Dispatcher>>> for Dispatchers { - fn from(dispatcher: Vec<Box<dyn Dispatcher>>) -> Self { - Self { dispatcher } - } -} - -impl From<Box<dyn Dispatcher>> for Dispatchers { - fn from(dispatcher: Box<dyn Dispatcher>) -> Self { - Self { - dispatcher: vec![dispatcher], - } - } -} - -impl<D> From<(D,)> for Dispatchers -where - D: Dispatcher + 'static, -{ - fn from(dispatcher: (D,)) -> Self { - Self { - dispatcher: vec![Box::new(dispatcher.0)], - } - } -} - -impl<D1, D2> From<(D1, D2)> for Dispatchers -where - D1: Dispatcher + 'static, - D2: Dispatcher + 'static, -{ - fn from(dispatchers: (D1, D2)) -> Self { - Self { - dispatcher: vec![Box::new(dispatchers.0), Box::new(dispatchers.1)], - } - } -} - -impl<D1, D2, D3> From<(D1, D2, D3)> for Dispatchers -where - D1: Dispatcher + 'static, - D2: Dispatcher + 'static, - D3: Dispatcher + 'static, -{ - fn from(dispatchers: (D1, D2, D3)) -> Self { - Self { - dispatcher: vec![ - Box::new(dispatchers.0), - Box::new(dispatchers.1), - Box::new(dispatchers.2), - ], - } - } -} - -impl<D1, D2, D3, D4> From<(D1, D2, D3, D4)> for Dispatchers -where - D1: Dispatcher + 'static, - D2: Dispatcher + 'static, - D3: Dispatcher + 'static, - D4: Dispatcher + 'static, -{ - fn from(dispatchers: (D1, D2, D3, D4)) -> Self { - Self { - dispatcher: vec![ - Box::new(dispatchers.0), - Box::new(dispatchers.1), - Box::new(dispatchers.2), - Box::new(dispatchers.3), - ], - } - } -} - -impl<D1, D2, D3, D4, D5> From<(D1, D2, D3, D4, D5)> for Dispatchers -where - D1: Dispatcher + 'static, - D2: Dispatcher + 'static, - D3: Dispatcher + 'static, - D4: Dispatcher + 'static, - D5: Dispatcher + 'static, -{ - fn from(dispatchers: (D1, D2, D3, D4, D5)) -> Self { - Self { - dispatcher: vec![ - Box::new(dispatchers.0), - Box::new(dispatchers.1), - Box::new(dispatchers.2), - Box::new(dispatchers.3), - Box::new(dispatchers.4), - ], - } - } -} - -impl<D1, D2, D3, D4, D5, D6> From<(D1, D2, D3, D4, D5, D6)> for Dispatchers -where - D1: Dispatcher + 'static, - D2: Dispatcher + 'static, - D3: Dispatcher + 'static, - D4: Dispatcher + 'static, - D5: Dispatcher + 'static, - D6: Dispatcher + 'static, -{ - fn from(dispatchers: (D1, D2, D3, D4, D5, D6)) -> Self { - Self { - dispatcher: vec![ - Box::new(dispatchers.0), - Box::new(dispatchers.1), - Box::new(dispatchers.2), - Box::new(dispatchers.3), - Box::new(dispatchers.4), - Box::new(dispatchers.5), - ], - } - } -} - -impl<D1, D2, D3, D4, D5, D6, D7> From<(D1, D2, D3, D4, D5, D6, D7)> for Dispatchers -where - D1: Dispatcher + 'static, - D2: Dispatcher + 'static, - D3: Dispatcher + 'static, - D4: Dispatcher + 'static, - D5: Dispatcher + 'static, - D6: Dispatcher + 'static, - D7: Dispatcher + 'static, -{ - fn from(dispatchers: (D1, D2, D3, D4, D5, D6, D7)) -> Self { - Self { - dispatcher: vec![ - Box::new(dispatchers.0), - Box::new(dispatchers.1), - Box::new(dispatchers.2), - Box::new(dispatchers.3), - Box::new(dispatchers.4), - Box::new(dispatchers.5), - Box::new(dispatchers.6), - ], - } - } -} - -impl std::ops::Deref for Dispatchers { - type Target = Vec<Box<dyn Dispatcher + 'static>>; - - fn deref(&self) -> &Self::Target { - &self.dispatcher - } -} - -impl From<Dispatchers> for Vec<Box<dyn Dispatcher + 'static>> { - fn from(val: Dispatchers) -> Self { - val.dispatcher - } -} diff --git a/mingling/src/asset/node.rs b/mingling/src/asset/node.rs deleted file mode 100644 index c8b7600..0000000 --- a/mingling/src/asset/node.rs +++ /dev/null @@ -1,54 +0,0 @@ -use just_fmt::kebab_case; - -#[derive(Debug, Default)] -pub struct Node { - node: Vec<String>, -} - -impl Node { - pub fn join(self, node: impl Into<String>) -> Node { - let mut new_node = self.node; - new_node.push(node.into()); - Node { node: new_node } - } -} - -impl From<&str> for Node { - fn from(s: &str) -> Self { - let node = s.split('.').map(|part| kebab_case!(part)).collect(); - Node { node } - } -} - -impl From<String> for Node { - fn from(s: String) -> Self { - let node = s.split('.').map(|part| kebab_case!(part)).collect(); - Node { node } - } -} - -impl PartialEq for Node { - fn eq(&self, other: &Self) -> bool { - self.node == other.node - } -} - -impl Eq for Node {} - -impl PartialOrd for Node { - fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { - Some(self.cmp(other)) - } -} - -impl Ord for Node { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - self.node.cmp(&other.node) - } -} - -impl std::fmt::Display for Node { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.node.join(".")) - } -} diff --git a/mingling/src/asset/renderer.rs b/mingling/src/asset/renderer.rs deleted file mode 100644 index 3852b55..0000000 --- a/mingling/src/asset/renderer.rs +++ /dev/null @@ -1,6 +0,0 @@ -use crate::RenderResult; - -pub trait Renderer { - type Previous; - fn render(p: Self::Previous, r: &mut RenderResult); -} diff --git a/mingling/src/lib.rs b/mingling/src/lib.rs deleted file mode 100644 index 4d9bcc5..0000000 --- a/mingling/src/lib.rs +++ /dev/null @@ -1,39 +0,0 @@ -mod any; -pub use crate::any::*; - -pub mod error { - pub use crate::asset::chain::error::*; - pub use crate::exec::error::*; -} - -mod program; -pub use crate::program::*; -pub mod setup { - pub use crate::program::setup::*; -} -pub mod hint { - pub use crate::program::hint::*; -} - -#[cfg(feature = "macros")] -#[allow(unused_imports)] -pub mod macros { - pub use mingling_macros::chain; - pub use mingling_macros::chain_struct; - pub use mingling_macros::dispatcher; - pub use mingling_macros::dispatcher_render; - pub use mingling_macros::node; - pub use mingling_macros::program; - pub use mingling_macros::r_print; - pub use mingling_macros::r_println; - pub use mingling_macros::renderer; -} - -mod renderer; - -mod asset; -pub use crate::asset::chain::*; -pub use crate::asset::dispatcher::*; -pub use crate::asset::node::*; -pub use crate::asset::renderer::*; -pub use crate::renderer::render_result::*; diff --git a/mingling/src/program.rs b/mingling/src/program.rs deleted file mode 100644 index 3d8bc14..0000000 --- a/mingling/src/program.rs +++ /dev/null @@ -1,132 +0,0 @@ -use crate::{ - AnyOutput, ChainProcess, RenderResult, asset::dispatcher::Dispatcher, - error::ProgramExecuteError, -}; -use std::{env, pin::Pin}; - -pub mod exec; -pub mod hint; -pub mod setup; - -mod config; -pub use config::*; - -mod flag; -pub use flag::*; -use tokio::io::AsyncWriteExt; - -#[derive(Default)] -pub struct Program<C: ProgramCollect> { - pub(crate) collect: std::marker::PhantomData<C>, - - pub(crate) args: Vec<String>, - pub(crate) dispatcher: Vec<Box<dyn Dispatcher>>, - - pub stdout_setting: ProgramStdoutSetting, - pub user_context: ProgramUserContext, -} - -impl<C> Program<C> -where - C: ProgramCollect, -{ - /// Creates a new Program instance, initializing args from environment. - pub fn new() -> Self { - Program { - collect: std::marker::PhantomData, - args: env::args().collect(), - dispatcher: Vec::new(), - stdout_setting: Default::default(), - user_context: Default::default(), - } - } - - /// Run the command line program - pub async fn exec_without_render(mut self) -> Result<RenderResult, ProgramExecuteError> { - self.args = self.args.iter().skip(1).cloned().collect(); - crate::exec::exec(self).await.map_err(|e| e.into()) - } - - /// Run the command line program - pub async fn exec(self) { - let stdout_setting = self.stdout_setting.clone(); - let result = match self.exec_without_render().await { - Ok(r) => r, - Err(e) => match e { - ProgramExecuteError::DispatcherNotFound => { - eprintln!("Dispatcher not found"); - return; - } - ProgramExecuteError::Other(e) => { - eprintln!("{}", e); - return; - } - }, - }; - - // Render result - if stdout_setting.render_output && !result.is_empty() { - print!("{}", result); - if let Err(e) = tokio::io::stdout().flush().await - && stdout_setting.error_output - { - eprintln!("{}", e); - } - } - } -} - -pub trait ProgramCollect { - fn render(any: AnyOutput, r: &mut RenderResult); - fn do_chain(any: AnyOutput) -> Pin<Box<dyn Future<Output = ChainProcess> + Send>>; - fn has_renderer(any: &AnyOutput) -> bool; - fn has_chain(any: &AnyOutput) -> bool; -} - -#[macro_export] -#[doc(hidden)] -macro_rules! __dispatch_program_renderers { - ( - $( $render_ty:ty => $prev_ty:ty, )* - ) => { - fn render(any: mingling::AnyOutput, r: &mut mingling::RenderResult) { - match any.type_id { - $( - id if id == std::any::TypeId::of::<$prev_ty>() => { - let value = any.downcast::<$prev_ty>().unwrap(); - <$render_ty as mingling::Renderer>::render(value, r); - } - )* - _ => (), - } - } - }; -} - -#[macro_export] -#[doc(hidden)] -macro_rules! __dispatch_program_chains { - ( - $( $chain_ty:ty => $chain_prev:ty, )* - ) => { - fn do_chain( - any: mingling::AnyOutput, - ) -> std::pin::Pin<Box<dyn Future<Output = mingling::ChainProcess> + Send>> { - match any.type_id { - $( - id if id == std::any::TypeId::of::<$chain_prev>() => { - let value = any.downcast::<$chain_prev>().unwrap(); - let fut = async { <$chain_ty as mingling::Chain>::proc(value).await }; - Box::pin(fut) - } - )* - _ => Box::pin(async move { - mingling::AnyOutput::new(mingling::hint::NoChainFound { - name: format!("{:?}", any.type_id).to_string(), - }) - .route_chain() - }), - } - } - }; -} diff --git a/mingling/src/program/config.rs b/mingling/src/program/config.rs deleted file mode 100644 index 386b112..0000000 --- a/mingling/src/program/config.rs +++ /dev/null @@ -1,26 +0,0 @@ -#[derive(Debug, Clone)] -pub struct ProgramStdoutSetting { - /// Output error messages - pub error_output: bool, - - /// Render results and output - pub render_output: bool, -} - -impl Default for ProgramStdoutSetting { - fn default() -> Self { - ProgramStdoutSetting { - error_output: true, - render_output: true, - } - } -} - -#[derive(Debug, Clone, Default)] -pub struct ProgramUserContext { - /// View help information instead of running the command - pub help: bool, - - /// Skip user confirmation step - pub confirm: bool, -} diff --git a/mingling/src/program/exec.rs b/mingling/src/program/exec.rs deleted file mode 100644 index 853bff1..0000000 --- a/mingling/src/program/exec.rs +++ /dev/null @@ -1,126 +0,0 @@ -#![allow(clippy::borrowed_box)] - -use crate::{ - AnyOutput, ChainProcess, Dispatcher, Next, Program, ProgramCollect, RenderResult, - error::ProgramInternalExecuteError, - hint::{DispatcherNotFound, RendererNotFound}, -}; - -pub mod error; - -pub async fn exec<C: ProgramCollect>( - program: Program<C>, -) -> Result<RenderResult, ProgramInternalExecuteError> { - // Match user input - let matched: (Box<dyn Dispatcher>, Vec<String>) = match match_user_input(&program) { - Ok(r) => (r.0.clone(), r.1), - Err(ProgramInternalExecuteError::DispatcherNotFound) => { - // If no Dispatcher is found, dispatch to the DispatcherNotFound Dispatcher - // to route it to the NoDispatcherFound struct - let disp: Box<dyn Dispatcher> = Box::new(DispatcherNotFound); - (disp, program.args) - } - Err(e) => return Err(e), - }; - - // Entry point - let (dispatcher, args) = matched; - let mut current = match dispatcher.begin(args) { - ChainProcess::Ok((any, Next::Renderer)) => return Ok(render::<C>(any)), - ChainProcess::Ok((any, Next::Chain)) => any, - ChainProcess::Err(e) => return Err(e.into()), - }; - - loop { - current = { - // If a chain exists, execute as a chain - if C::has_chain(¤t) { - match C::do_chain(current).await { - ChainProcess::Ok((any, Next::Renderer)) => return Ok(render::<C>(any)), - ChainProcess::Ok((any, Next::Chain)) => any, - ChainProcess::Err(e) => return Err(e.into()), - } - } - // If no chain exists, attempt to render - else if C::has_renderer(¤t) { - let mut render_result = RenderResult::default(); - C::render(current, &mut render_result); - return Ok(render_result); - } - // If no renderer exists, transfer to the RendererNotFound Dispatcher for execution - else { - let disp: Box<dyn Dispatcher> = Box::new(RendererNotFound); - - match disp.begin(vec![format!("{:?}", current.type_id)]) { - ChainProcess::Ok((any, Next::Renderer)) => return Ok(render::<C>(any)), - ChainProcess::Ok((any, Next::Chain)) => any, - ChainProcess::Err(e) => return Err(e.into()), - } - } - }; - } -} - -/// Match user input against registered dispatchers and return the matched dispatcher and remaining arguments. -fn match_user_input<C: ProgramCollect>( - program: &Program<C>, -) -> Result<(&Box<dyn Dispatcher>, Vec<String>), ProgramInternalExecuteError> { - let nodes = get_nodes(program); - let command = format!("{} ", program.args.join(" ")); - - // Find all nodes that match the command prefix - let matching_nodes: Vec<&(String, &Box<dyn Dispatcher>)> = nodes - .iter() - // Also add a space to the node string to ensure consistent matching logic - .filter(|(node_str, _)| command.starts_with(&format!("{} ", node_str))) - .collect(); - - match matching_nodes.len() { - 0 => { - // No matching node found - Err(ProgramInternalExecuteError::DispatcherNotFound) - } - 1 => { - let matched_prefix = matching_nodes[0]; - let prefix_len = matched_prefix.0.split_whitespace().count(); - let trimmed_args: Vec<String> = program.args.iter().skip(prefix_len).cloned().collect(); - Ok((matched_prefix.1, trimmed_args)) - } - _ => { - // Multiple matching nodes found - // Find the node with the longest length (most specific match) - let matched_prefix = matching_nodes - .iter() - .max_by_key(|node| node.0.len()) - .unwrap(); - - let prefix_len = matched_prefix.0.split_whitespace().count(); - let trimmed_args: Vec<String> = program.args.iter().skip(prefix_len).cloned().collect(); - Ok((matched_prefix.1, trimmed_args)) - } - } -} - -#[inline(always)] -fn render<C: ProgramCollect>(any: AnyOutput) -> RenderResult { - let mut render_result = RenderResult::default(); - C::render(any, &mut render_result); - render_result -} - -// Get all registered dispatcher names from the program -fn get_nodes<C: ProgramCollect>(program: &Program<C>) -> Vec<(String, &Box<dyn Dispatcher>)> { - program - .dispatcher - .iter() - .map(|disp| { - let node_str = disp - .node() - .to_string() - .split('.') - .collect::<Vec<_>>() - .join(" "); - (node_str, disp) - }) - .collect() -} diff --git a/mingling/src/program/exec/error.rs b/mingling/src/program/exec/error.rs deleted file mode 100644 index fe66e22..0000000 --- a/mingling/src/program/exec/error.rs +++ /dev/null @@ -1,46 +0,0 @@ -use crate::error::ChainProcessError; - -#[derive(thiserror::Error, Debug)] -pub enum ProgramExecuteError { - #[error("No Dispatcher Found")] - DispatcherNotFound, - - #[error("Other error: {0}")] - Other(String), -} - -#[derive(thiserror::Error, Debug)] -pub enum ProgramInternalExecuteError { - #[error("No Dispatcher Found")] - DispatcherNotFound, - - #[error("Other error: {0}")] - Other(String), - - #[error("IO error: {0}")] - IO(#[from] std::io::Error), -} - -impl From<ProgramInternalExecuteError> for ProgramExecuteError { - fn from(value: ProgramInternalExecuteError) -> Self { - match value { - ProgramInternalExecuteError::DispatcherNotFound => { - ProgramExecuteError::DispatcherNotFound - } - ProgramInternalExecuteError::Other(s) => ProgramExecuteError::Other(s), - ProgramInternalExecuteError::IO(e) => ProgramExecuteError::Other(format!("{}", e)), - } - } -} - -impl From<ChainProcessError> for ProgramInternalExecuteError { - fn from(value: ChainProcessError) -> Self { - match value { - ChainProcessError::Other(s) => ProgramInternalExecuteError::Other(s), - ChainProcessError::IO(error) => ProgramInternalExecuteError::IO(error), - ChainProcessError::Broken(_) => { - ProgramInternalExecuteError::Other("Broken".to_string()) - } - } - } -} diff --git a/mingling/src/program/flag.rs b/mingling/src/program/flag.rs deleted file mode 100644 index 3a678be..0000000 --- a/mingling/src/program/flag.rs +++ /dev/null @@ -1,148 +0,0 @@ -use crate::{Program, ProgramCollect}; - -pub struct Flag { - vec: Vec<&'static str>, -} - -impl From<&'static str> for Flag { - fn from(s: &'static str) -> Self { - Flag { vec: vec![s] } - } -} - -impl From<&'static [&'static str]> for Flag { - fn from(slice: &'static [&'static str]) -> Self { - Flag { - vec: slice.to_vec(), - } - } -} - -impl<const N: usize> From<[&'static str; N]> for Flag { - fn from(slice: [&'static str; N]) -> Self { - Flag { - vec: slice.to_vec(), - } - } -} - -impl<const N: usize> From<&'static [&'static str; N]> for Flag { - fn from(slice: &'static [&'static str; N]) -> Self { - Flag { - vec: slice.to_vec(), - } - } -} - -impl AsRef<[&'static str]> for Flag { - fn as_ref(&self) -> &[&'static str] { - &self.vec - } -} - -impl std::ops::Deref for Flag { - type Target = [&'static str]; - - fn deref(&self) -> &Self::Target { - &self.vec - } -} - -macro_rules! special_flag { - ($args:expr, $flag:expr) => {{ - let flag = $flag; - let found = $args.iter().any(|arg| arg == flag); - $args.retain(|arg| arg != flag); - found - }}; -} - -macro_rules! special_argument { - ($args:expr, $flag:expr) => {{ - let flag = $flag; - let mut value: Option<String> = None; - let mut i = 0; - while i < $args.len() { - if &$args[i] == flag { - if i + 1 < $args.len() { - value = Some($args[i + 1].clone()); - $args.remove(i + 1); - $args.remove(i); - } else { - value = None; - $args.remove(i); - } - break; - } - i += 1; - } - value - }}; -} - -impl<C> Program<C> -where - C: ProgramCollect, -{ - /// Registers a global argument (with value) and its handler. - pub fn global_argument<F, A>(&mut self, arguments: A, do_fn: F) - where - F: Fn(&mut Program<C>, String), - A: Into<Flag>, - { - let flag = arguments.into(); - for argument in flag.iter() { - let value = special_argument!(self.args, argument); - if let Some(value) = value { - do_fn(self, value); - return; - } - } - } - - /// Registers a global flag (boolean) and its handler. - pub fn global_flag<F, A>(&mut self, flag: A, do_fn: F) - where - F: Fn(&mut Program<C>), - A: Into<Flag>, - { - let flag = flag.into(); - for argument in flag.iter() { - let enabled = special_flag!(self.args, argument); - if enabled { - do_fn(self); - return; - } - } - } - - /// Extracts a global argument (with value) from arguments - pub fn pick_global_argument<F>(&mut self, flag: F) -> Option<String> - where - F: Into<Flag>, - { - let flag: Flag = flag.into(); - for argument in flag.iter() { - let value = special_argument!(self.args, argument); - if value.is_some() { - return value; - } - } - None - } - - /// Extracts global flags from arguments - pub fn pick_global_flag<F>(&mut self, flag: F) -> bool - where - F: Into<Flag>, - { - let flag: Flag = flag.into(); - for argument in flag.iter() { - let enabled = special_flag!(self.args, argument); - if enabled { - return enabled; - } - } - false - } -} diff --git a/mingling/src/program/hint.rs b/mingling/src/program/hint.rs deleted file mode 100644 index 6dbbac2..0000000 --- a/mingling/src/program/hint.rs +++ /dev/null @@ -1,62 +0,0 @@ -use crate::{AnyOutput, ChainProcess, Dispatcher, Node}; - -/// Marker: Dispatcher Not Found -/// -/// If a Dispatcher outputs NoDispatcherFound to the Chain, -/// the program will terminate directly. -/// -/// You can implement Renderer for NoDispatcherFound -/// to render relevant information when a Dispatcher cannot be found. -#[cfg_attr(feature = "general_renderer", derive(serde::Serialize))] -pub struct NoDispatcherFound { - pub args: Vec<String>, -} - -#[derive(Default)] -#[cfg_attr(feature = "general_renderer", derive(serde::Serialize))] -pub struct DispatcherNotFound; -impl Dispatcher for DispatcherNotFound { - fn node(&self) -> crate::Node { - Node::default().join("_not_found") - } - - fn begin(&self, args: Vec<String>) -> ChainProcess { - AnyOutput::new(NoDispatcherFound { args }).route_renderer() - } - - fn clone_dispatcher(&self) -> Box<dyn Dispatcher> { - Box::new(DispatcherNotFound) - } -} - -/// Marker: Renderer Not Found -/// -/// If a Chain outputs NoRendererFound to the Chain, -/// the program will terminate directly. -/// -/// You can implement Renderer for NoRendererFound -/// to render relevant information when a Renderer cannot be found. -#[cfg_attr(feature = "general_renderer", derive(serde::Serialize))] -pub struct NoRendererFound { - pub type_to_render: String, -} - -#[derive(Default)] -#[cfg_attr(feature = "general_renderer", derive(serde::Serialize))] -pub struct RendererNotFound; -impl Dispatcher for RendererNotFound { - fn node(&self) -> crate::Node { - Node::default().join("_not_found") - } - - fn begin(&self, args: Vec<String>) -> ChainProcess { - AnyOutput::new(NoRendererFound { - type_to_render: args.first().unwrap().clone(), - }) - .route_renderer() - } - - fn clone_dispatcher(&self) -> Box<dyn Dispatcher> { - Box::new(RendererNotFound) - } -} diff --git a/mingling/src/program/setup.rs b/mingling/src/program/setup.rs deleted file mode 100644 index e81247e..0000000 --- a/mingling/src/program/setup.rs +++ /dev/null @@ -1,19 +0,0 @@ -use crate::{ProgramCollect, program::Program}; - -mod basic; -pub use basic::*; - -pub trait ProgramSetup<C: ProgramCollect> { - fn setup(&mut self, program: &mut Program<C>); -} - -impl<C> Program<C> -where - C: ProgramCollect, -{ - /// Load and execute init logic - pub fn with_setup<S: ProgramSetup<C> + 'static>(&mut self, mut setup: S) -> S { - S::setup(&mut setup, self); - setup - } -} diff --git a/mingling/src/program/setup/basic.rs b/mingling/src/program/setup/basic.rs deleted file mode 100644 index 43c14b9..0000000 --- a/mingling/src/program/setup/basic.rs +++ /dev/null @@ -1,31 +0,0 @@ -use crate::{ - ProgramCollect, - program::{Program, setup::ProgramSetup}, -}; - -/// Performs basic program initialization: -/// -/// - Collects `--quiet` flag to control message rendering -/// - Collects `--help` flag to enable help mode -/// - Collects `--confirm` flag to skip user confirmation -pub struct BasicProgramSetup; - -impl<C> ProgramSetup<C> for BasicProgramSetup -where - C: ProgramCollect, -{ - fn setup(&mut self, program: &mut Program<C>) { - program.global_flag(["--quiet", "-q"], |p| { - p.stdout_setting.render_output = false; - p.stdout_setting.error_output = false; - }); - - program.global_flag(["--help", "-h"], |p| { - p.user_context.help = true; - }); - - program.global_flag(["--confirm", "-C"], |p| { - p.user_context.confirm = true; - }); - } -} diff --git a/mingling/src/renderer.rs b/mingling/src/renderer.rs deleted file mode 100644 index 631092b..0000000 --- a/mingling/src/renderer.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod render_result; diff --git a/mingling/src/renderer/render_result.rs b/mingling/src/renderer/render_result.rs deleted file mode 100644 index 73c38e7..0000000 --- a/mingling/src/renderer/render_result.rs +++ /dev/null @@ -1,38 +0,0 @@ -use std::{ - fmt::{Display, Formatter}, - ops::Deref, -}; - -#[derive(Default, Debug, PartialEq)] -pub struct RenderResult { - render_text: String, -} - -impl Display for RenderResult { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - writeln!(f, "{}", self.render_text.trim()) - } -} - -impl Deref for RenderResult { - type Target = str; - - fn deref(&self) -> &Self::Target { - &self.render_text - } -} - -impl RenderResult { - pub fn print(&mut self, text: &str) { - self.render_text.push_str(text); - } - - pub fn println(&mut self, text: &str) { - self.render_text.push_str(text); - self.render_text.push('\n'); - } - - pub fn clear(&mut self) { - self.render_text.clear(); - } -} |
