clap_serde_derive/lib.rs
1// Copyright (C) 2022 Davide Peressoni
2//
3// This program is free software: you can redistribute it and/or modify
4// it under the terms of the GNU Affero General Public License as published by
5// the Free Software Foundation, either version 3 of the License, or
6// any later version.
7//
8// This program is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11// GNU Affero General Public License for more details.
12//
13// You should have received a copy of the GNU Affero General Public License
14// along with this program. If not, see <http://www.gnu.org/licenses/>.
15
16#![doc(
17 html_favicon_url = "https://gitlab.com/DPDmancul/clap-serde-derive/-/raw/main/asstets/logo.svg"
18)]
19#![doc(html_logo_url = "https://gitlab.com/DPDmancul/clap-serde-derive/-/raw/main/assets/logo.svg")]
20#![doc = include_str!("../README.md")]
21
22use core::borrow::BorrowMut;
23use std::ffi::OsString;
24// Re-exports
25pub use clap;
26pub use clap_serde_proc::ClapSerde;
27pub use serde;
28
29/// Trait representing a struct which can be parsed from clap and serde.
30/// This trait is automatically implemented by [`ClapSerde`][clap_serde_proc::ClapSerde]
31/// derive macro.
32pub trait ClapSerde: Default + From<Self::Opt> + for<'a> From<&'a mut Self::Opt> {
33 /// The same struct of the parent but with optional fields.
34 type Opt: Default + clap::Parser + serde::de::DeserializeOwned + clap::Args;
35
36 /// Merge in place from Opt struct.
37 ///
38 /// Fields which are not None in `other` will be cleared and used to update `self`.
39 /// Fields which are None in `other` will not be modified in `self`.
40 fn update(&mut self, other: impl BorrowMut<Self::Opt>);
41
42 /// Merge from Opts struct.
43 fn merge(mut self, other: impl BorrowMut<Self::Opt>) -> Self {
44 self.update(other);
45 self
46 }
47
48 /// Merge from clap to the object.
49 fn merge_clap(self) -> Self {
50 self.merge(<Self::Opt as clap::Parser>::parse())
51 }
52
53 /// Merge from clap to the object with the given args
54 fn merge_clap_with_args<I, T>(self, itr: I) -> Self
55 where
56 I: IntoIterator<Item = T>,
57 T: Into<OsString> + Clone,
58 {
59 self.merge(<Self::Opt as clap::Parser>::parse_from(itr))
60 }
61
62 /// Create new object parsing from clap.
63 fn from_clap() -> Self {
64 Self::default().merge_clap()
65 }
66
67 /// Create new object parsing from clap with the given args
68 fn from_clap_with_args<I, T>(itr: I) -> Self
69 where
70 I: IntoIterator<Item = T>,
71 T: Into<OsString> + Clone,
72 {
73 Self::default().merge_clap_with_args(itr)
74 }
75}