mirror of
https://github.com/cargo-bins/cargo-binstall.git
synced 2025-04-20 20:48:43 +00:00
Add new crate leon-macros
that provide template!
with identical syntax as runtime parsing (#946)
`leon_macros::template!` can parse template at compile-time. It accepts a utf-8 string literal and uses `leon` internally to parse it, then generate code that evaluates to `Template<'static>`. - Exclude fuzz from crate leon when publishing - Impl fn-like proc-macro `leon_macros::template!` - Add dep `leon-macros` to binstalk - Use `leon_macros::template!` in `binstalk::fetchers::gh_crate_meta::hosting` - Add doc for `leon-macros` in `leon` - Improve `std::fmt::Display` impl for `leon::ParseError` - Fixed broken infra link in leon Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
This commit is contained in:
parent
fa0455a417
commit
5683ca2476
18 changed files with 373 additions and 91 deletions
4
.github/dependabot.yml
vendored
4
.github/dependabot.yml
vendored
|
@ -52,3 +52,7 @@ updates:
|
|||
directory: "/crates/leon"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
- package-ecosystem: "cargo"
|
||||
directory: "/crates/leon-macros"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
|
|
1
.github/workflows/release-pr.yml
vendored
1
.github/workflows/release-pr.yml
vendored
|
@ -17,6 +17,7 @@ on:
|
|||
- fs-lock
|
||||
- normalize-path
|
||||
- leon
|
||||
- leon-macros
|
||||
version:
|
||||
description: Version to release
|
||||
required: true
|
||||
|
|
11
Cargo.lock
generated
11
Cargo.lock
generated
|
@ -231,6 +231,7 @@ dependencies = [
|
|||
"itertools",
|
||||
"jobslot",
|
||||
"leon",
|
||||
"leon-macros",
|
||||
"maybe-owned",
|
||||
"miette",
|
||||
"normalize-path",
|
||||
|
@ -1338,6 +1339,16 @@ dependencies = [
|
|||
"tinytemplate",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "leon-macros"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"leon",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.15",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.141"
|
||||
|
|
|
@ -10,6 +10,7 @@ members = [
|
|||
"crates/normalize-path",
|
||||
"crates/detect-targets",
|
||||
"crates/leon",
|
||||
"crates/leon-macros",
|
||||
]
|
||||
|
||||
[profile.release]
|
||||
|
|
|
@ -31,7 +31,7 @@ use strum_macros::EnumCount;
|
|||
pub struct Args {
|
||||
/// Packages to install.
|
||||
///
|
||||
/// Syntax: crate[@version]
|
||||
/// Syntax: `crate[@version]`
|
||||
///
|
||||
/// Each value is either a crate name alone, or a crate name followed by @ and the version to
|
||||
/// install. The version syntax is as with the --version option.
|
||||
|
|
|
@ -22,6 +22,7 @@ home = "0.5.4"
|
|||
itertools = "0.10.5"
|
||||
jobslot = { version = "0.2.11", features = ["tokio"] }
|
||||
leon = { version = "1.0.0", path = "../leon" }
|
||||
leon-macros = { version = "0.0.0", path = "../leon-macros" }
|
||||
maybe-owned = "0.3.4"
|
||||
miette = "5.7.0"
|
||||
normalize-path = { version = "0.2.0", path = "../normalize-path" }
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
use itertools::Itertools;
|
||||
use leon::{template, Item, Template};
|
||||
use leon::{Item, Template};
|
||||
use leon_macros::template;
|
||||
use url::Url;
|
||||
|
||||
use crate::errors::BinstallError;
|
||||
|
@ -16,62 +17,36 @@ pub enum RepositoryHost {
|
|||
/// Make sure to update possible_dirs in `bins::infer_bin_dir_template`
|
||||
/// if you modified FULL_FILENAMES or NOVERSION_FILENAMES.
|
||||
pub const FULL_FILENAMES: &[Template<'_>] = &[
|
||||
template!("/", { "name" }, "-", { "target" }, "-v", { "version" }, {
|
||||
"archive-suffix"
|
||||
}),
|
||||
template!("/", { "name" }, "-", { "target" }, "-", { "version" }, {
|
||||
"archive-suffix"
|
||||
}),
|
||||
template!("/", { "name" }, "-", { "version" }, "-", { "target" }, {
|
||||
"archive-suffix"
|
||||
}),
|
||||
template!("/", { "name" }, "-v", { "version" }, "-", { "target" }, {
|
||||
"archive-suffix"
|
||||
}),
|
||||
template!("/", { "name" }, "_", { "target" }, "_v", { "version" }, {
|
||||
"archive-suffix"
|
||||
}),
|
||||
template!("/", { "name" }, "_", { "target" }, "_", { "version" }, {
|
||||
"archive-suffix"
|
||||
}),
|
||||
template!("/", { "name" }, "_", { "version" }, "_", { "target" }, {
|
||||
"archive-suffix"
|
||||
}),
|
||||
template!("/", { "name" }, "_v", { "version" }, "_", { "target" }, {
|
||||
"archive-suffix"
|
||||
}),
|
||||
template!("/{ name }-{ target }-v{ version }{ archive-suffix }"),
|
||||
template!("/{ name }-{ target }-{ version }{ archive-suffix }"),
|
||||
template!("/{ name }-{ version }-{ target }{ archive-suffix }"),
|
||||
template!("/{ name }-v{ version }-{ target }{ archive-suffix }"),
|
||||
template!("/{ name }_{ target }_v{ version }{ archive-suffix }"),
|
||||
template!("/{ name }_{ target }_{ version }{ archive-suffix }"),
|
||||
template!("/{ name }_{ version }_{ target }{ archive-suffix }"),
|
||||
template!("/{ name }_v{ version }_{ target }{ archive-suffix }"),
|
||||
];
|
||||
|
||||
pub const NOVERSION_FILENAMES: &[Template<'_>] = &[
|
||||
template!("/", { "name" }, "-", { "target" }, { "archive-suffix" }),
|
||||
template!("/", { "name" }, "_", { "target" }, { "archive-suffix" }),
|
||||
template!("/{ name }-{ target }{ archive-suffix }"),
|
||||
template!("/{ name }_{ target }{ archive-suffix }"),
|
||||
];
|
||||
|
||||
const GITHUB_RELEASE_PATHS: &[Template<'_>] = &[
|
||||
template!({ "repo" }, "/releases/download/", { "version" }),
|
||||
template!({ "repo" }, "/releases/download/v", { "version" }),
|
||||
template!("{ repo }/releases/download/{ version }"),
|
||||
template!("{ repo }/releases/download/v{ version }"),
|
||||
];
|
||||
|
||||
const GITLAB_RELEASE_PATHS: &[Template<'_>] = &[
|
||||
template!(
|
||||
{ "repo" },
|
||||
"/-/releases/",
|
||||
{ "version" },
|
||||
"/downloads/binaries"
|
||||
),
|
||||
template!(
|
||||
{ "repo" },
|
||||
"/-/releases/v",
|
||||
{ "version" },
|
||||
"/downloads/binaries"
|
||||
),
|
||||
template!("{ repo }/-/releases/{ version }/downloads/binaries"),
|
||||
template!("{ repo }/-/releases/v{ version }/downloads/binaries"),
|
||||
];
|
||||
|
||||
const BITBUCKET_RELEASE_PATHS: &[Template<'_>] = &[template!({ "repo" }, "/downloads")];
|
||||
const BITBUCKET_RELEASE_PATHS: &[Template<'_>] = &[template!("{ repo }/downloads")];
|
||||
|
||||
const SOURCEFORGE_RELEASE_PATHS: &[Template<'_>] = &[
|
||||
template!({ "repo" }, "/files/binaries/", { "version" }),
|
||||
template!({ "repo" }, "/files/binaries/v", { "version" }),
|
||||
template!("{ repo }/files/binaries/{ version }"),
|
||||
template!("{ repo }/files/binaries/v{ version }"),
|
||||
];
|
||||
|
||||
impl RepositoryHost {
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
use std::{future::Future, pin::Pin};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
/// Given multiple futures with output = Result<Option<T>, E>,
|
||||
/// Given multiple futures with output = `Result<Option<T>, E>`,
|
||||
/// returns the the first one that returns either `Err(_)` or
|
||||
/// `Ok(Some(_))`.
|
||||
pub struct FuturesResolver<T, E> {
|
||||
|
|
19
crates/leon-macros/Cargo.toml
Normal file
19
crates/leon-macros/Cargo.toml
Normal file
|
@ -0,0 +1,19 @@
|
|||
[package]
|
||||
name = "leon-macros"
|
||||
version = "0.0.0"
|
||||
edition = "2021"
|
||||
description = "Proc macros for crate leon"
|
||||
repository = "https://github.com/cargo-bins/cargo-binstall"
|
||||
documentation = "https://docs.rs/leon-macros"
|
||||
rust-version = "1.61.0"
|
||||
authors = ["Félix Saparelli <felix@passcod.name>", "Jiahao XU Jiahao_XU@outlook"]
|
||||
license = "Apache-2.0 OR MIT"
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
leon = { version = "1.0.0", path = "../leon", default-features = false }
|
||||
proc-macro2 = "1.0.56"
|
||||
syn = { version = "2.0.15", default-features = false, features = ["proc-macro", "parsing"] }
|
||||
quote = "1.0.26"
|
176
crates/leon-macros/LICENSE-APACHE
Normal file
176
crates/leon-macros/LICENSE-APACHE
Normal file
|
@ -0,0 +1,176 @@
|
|||
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
|
23
crates/leon-macros/LICENSE-MIT
Normal file
23
crates/leon-macros/LICENSE-MIT
Normal file
|
@ -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.
|
36
crates/leon-macros/src/lib.rs
Normal file
36
crates/leon-macros/src/lib.rs
Normal file
|
@ -0,0 +1,36 @@
|
|||
use leon::{Item, Template};
|
||||
use quote::quote;
|
||||
use syn::{parse_macro_input, LitStr};
|
||||
|
||||
#[proc_macro]
|
||||
pub fn template(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
let input = parse_macro_input!(input as LitStr).value();
|
||||
|
||||
#[allow(clippy::unnecessary_to_owned)]
|
||||
let items = Template::parse(&input)
|
||||
.unwrap()
|
||||
.items
|
||||
.into_owned()
|
||||
.into_iter()
|
||||
.map(|item| match item {
|
||||
Item::Text(text) => quote! {
|
||||
::leon::Item::Text(#text)
|
||||
},
|
||||
Item::Key(key) => quote! {
|
||||
::leon::Item::Key(#key)
|
||||
},
|
||||
});
|
||||
|
||||
quote! {
|
||||
::leon::Template::new(
|
||||
{
|
||||
const ITEMS: &'static [::leon::Item<'static>] = &[
|
||||
#(#items),*
|
||||
];
|
||||
ITEMS
|
||||
},
|
||||
::core::option::Option::None,
|
||||
)
|
||||
}
|
||||
.into()
|
||||
}
|
21
crates/leon-macros/tests/parsing.rs
Normal file
21
crates/leon-macros/tests/parsing.rs
Normal file
|
@ -0,0 +1,21 @@
|
|||
use leon::{Item, Template};
|
||||
|
||||
#[test]
|
||||
fn test() {
|
||||
assert_eq!(leon_macros::template!(""), Template::new(&[], None),);
|
||||
|
||||
assert_eq!(
|
||||
leon_macros::template!("a"),
|
||||
Template::new(&[Item::Text("a")], None),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
leon_macros::template!("{1}"),
|
||||
Template::new(&[Item::Key("1")], None),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
leon_macros::template!("a{ 1 } c"),
|
||||
Template::new(&[Item::Text("a"), Item::Key("1"), Item::Text(" c")], None),
|
||||
);
|
||||
}
|
|
@ -8,6 +8,7 @@ rust-version = "1.61.0"
|
|||
authors = ["Félix Saparelli <felix@passcod.name>"]
|
||||
edition = "2021"
|
||||
license = "Apache-2.0 OR MIT"
|
||||
exclude = ["fuzz"]
|
||||
|
||||
[dependencies]
|
||||
clap = { version = "4.2.2", features = ["derive"], optional = true }
|
||||
|
|
|
@ -1,11 +1,13 @@
|
|||
#[derive(Debug, thiserror::Error)]
|
||||
use thiserror::Error as ThisError;
|
||||
|
||||
#[derive(Debug, ThisError)]
|
||||
#[cfg_attr(feature = "miette", derive(miette::Diagnostic))]
|
||||
pub enum RenderError {
|
||||
/// A key was missing from the provided values.
|
||||
#[error("missing key `{0}`")]
|
||||
MissingKey(String),
|
||||
|
||||
/// An I/O error passed through from [`Template::render_into`].
|
||||
/// An I/O error passed through from [`Template::render_into`](crate::Template::render_into).
|
||||
#[error("write failed: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
|
@ -15,71 +17,73 @@ pub enum RenderError {
|
|||
/// When the `miette` feature is enabled, this is a rich miette-powered error
|
||||
/// which will highlight the source of the error in the template when output
|
||||
/// (with miette's `fancy` feature). With `miette` disabled, this is opaque.
|
||||
#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
|
||||
#[derive(Clone, Debug, ThisError, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "miette", derive(miette::Diagnostic))]
|
||||
#[cfg_attr(feature = "miette", diagnostic(transparent))]
|
||||
#[error(transparent)]
|
||||
pub struct ParseError(Box<InnerParseError>);
|
||||
|
||||
/// The inner (unboxed) type of [`ParseError`].
|
||||
#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "miette", derive(miette::Diagnostic))]
|
||||
#[error("template parse failed")]
|
||||
#[derive(Clone, Debug, ThisError, PartialEq, Eq)]
|
||||
#[error("{kind} at span start = {offset}, len = {len}: {src}")]
|
||||
struct InnerParseError {
|
||||
#[cfg_attr(feature = "miette", source_code)]
|
||||
src: String,
|
||||
offset: usize,
|
||||
len: usize,
|
||||
kind: ErrorKind,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "miette", label("This bracket is not opening or closing anything. Try removing it, or escaping it with a backslash."))]
|
||||
unbalanced: Option<(usize, usize)>,
|
||||
#[cfg(feature = "miette")]
|
||||
impl miette::Diagnostic for InnerParseError {
|
||||
fn source_code(&self) -> Option<&dyn miette::SourceCode> {
|
||||
Some(&self.src)
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "miette", label("This escape is malformed."))]
|
||||
escape: Option<(usize, usize)>,
|
||||
fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> {
|
||||
Some(Box::new(std::iter::once_with(|| {
|
||||
miette::LabeledSpan::new(Some(self.kind.to_string()), self.offset, self.len)
|
||||
})))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "miette", label("A key cannot be empty."))]
|
||||
key_empty: Option<(usize, usize)>,
|
||||
#[derive(Clone, Debug, ThisError, PartialEq, Eq)]
|
||||
enum ErrorKind {
|
||||
#[error("This bracket is not opening or closing anything. Try removing it, or escaping it with a backslash.")]
|
||||
Unbalanced,
|
||||
|
||||
#[cfg_attr(feature = "miette", label("Escapes are not allowed in keys."))]
|
||||
key_escape: Option<(usize, usize)>,
|
||||
#[error("This escape is malformed.")]
|
||||
Escape,
|
||||
|
||||
#[error("A key cannot be empty.")]
|
||||
KeyEmpty,
|
||||
|
||||
#[error("Escapes are not allowed in keys.")]
|
||||
KeyEscape,
|
||||
}
|
||||
|
||||
impl ParseError {
|
||||
pub(crate) fn unbalanced(src: &str, start: usize, end: usize) -> Self {
|
||||
fn new(src: &str, start: usize, end: usize, kind: ErrorKind) -> Self {
|
||||
Self(Box::new(InnerParseError {
|
||||
src: String::from(src),
|
||||
unbalanced: Some((start, end.saturating_sub(start) + 1)),
|
||||
escape: None,
|
||||
key_empty: None,
|
||||
key_escape: None,
|
||||
offset: start,
|
||||
len: end.saturating_sub(start) + 1,
|
||||
kind,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn unbalanced(src: &str, start: usize, end: usize) -> Self {
|
||||
Self::new(src, start, end, ErrorKind::Unbalanced)
|
||||
}
|
||||
|
||||
pub(crate) fn escape(src: &str, start: usize, end: usize) -> Self {
|
||||
Self(Box::new(InnerParseError {
|
||||
src: String::from(src),
|
||||
unbalanced: None,
|
||||
escape: Some((start, end.saturating_sub(start) + 1)),
|
||||
key_empty: None,
|
||||
key_escape: None,
|
||||
}))
|
||||
Self::new(src, start, end, ErrorKind::Escape)
|
||||
}
|
||||
|
||||
pub(crate) fn key_empty(src: &str, start: usize, end: usize) -> Self {
|
||||
Self(Box::new(InnerParseError {
|
||||
src: String::from(src),
|
||||
unbalanced: None,
|
||||
escape: None,
|
||||
key_empty: Some((start, end.saturating_sub(start) + 1)),
|
||||
key_escape: None,
|
||||
}))
|
||||
Self::new(src, start, end, ErrorKind::KeyEmpty)
|
||||
}
|
||||
|
||||
pub(crate) fn key_escape(src: &str, start: usize, end: usize) -> Self {
|
||||
Self(Box::new(InnerParseError {
|
||||
src: String::from(src),
|
||||
unbalanced: None,
|
||||
escape: None,
|
||||
key_empty: None,
|
||||
key_escape: Some((start, end.saturating_sub(start) + 1)),
|
||||
}))
|
||||
Self::new(src, start, end, ErrorKind::KeyEscape)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -121,12 +121,21 @@
|
|||
//! assert_eq!(template.render(&values).unwrap().as_str(), "hello pontifex");
|
||||
//! ```
|
||||
//!
|
||||
//! # Compile-time parsing
|
||||
//!
|
||||
//! You can either use [`leon-macros`](https://docs.rs/leon-macros)'s
|
||||
//! [`template!`](https://docs.rs/leon-macros/latest/leon_macros/macro.template.html),
|
||||
//! a proc-macro, with the exact same syntax as the normal parser, or this
|
||||
//! crate's [`template!`] rules-macro, which requires a slightly different
|
||||
//! syntax but doesn't bring in additional dependencies. In either case,
|
||||
//! the leon library is required as a runtime dependency.
|
||||
//!
|
||||
//! # Errors
|
||||
//!
|
||||
//! Leon will return a [`LeonError::InvalidTemplate`] if the template fails to
|
||||
//! Leon will return a [`ParseError`] if the template fails to
|
||||
//! parse. This can happen if there are unbalanced braces, or if a key is empty.
|
||||
//!
|
||||
//! Leon will return a [`LeonError::MissingKey`] if a key is missing from keyed
|
||||
//! Leon will return a [`RenderError::MissingKey`] if a key is missing from keyed
|
||||
//! values passed to [`Template::render()`], unless a default value is provided
|
||||
//! with [`Template.default`].
|
||||
//!
|
||||
|
|
|
@ -29,7 +29,7 @@ macro_rules! __template_impl {
|
|||
}
|
||||
|
||||
/// Construct a template constant using syntax similar to the template to be
|
||||
/// passed to [`Template::parse`].
|
||||
/// passed to [`Template::parse`](crate::Template::parse).
|
||||
///
|
||||
/// This is essentially a shorthand for:
|
||||
///
|
||||
|
|
|
@ -47,7 +47,7 @@ impl<'s> Template<'s> {
|
|||
/// assert_eq!(TEMPLATE.render(&[("unrelated", "value")]).unwrap(), "Hello world");
|
||||
/// ```
|
||||
///
|
||||
/// For an even more ergonomic syntax, see the [`leon::template!`] macro.
|
||||
/// For an even more ergonomic syntax, see the [`leon::template!`](crate::template!) macro.
|
||||
pub const fn new(items: &'s [Item<'s>], default: Option<&'s str>) -> Template<'s> {
|
||||
Template {
|
||||
items: Cow::Borrowed(items),
|
||||
|
|
Loading…
Add table
Reference in a new issue