Debian Codegraph @

cli/examples/custom-commit-templater/main.rs

raw
1 // Copyright 2024 The Jujutsu Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::sync::Arc;
16
17 use futures::TryStreamExt as _;
18 use jj_cli::cli_util::CliRunner;
19 use jj_cli::commit_templater::CommitTemplateBuildFnTable;
20 use jj_cli::commit_templater::CommitTemplateLanguageExtension;
21 use jj_cli::template_parser;
22 use jj_cli::template_parser::TemplateParseError;
23 use jj_cli::templater::TemplatePropertyExt as _;
24 use jj_lib::backend::CommitId;
25 use jj_lib::commit::Commit;
26 use jj_lib::extensions_map::ExtensionsMap;
27 use jj_lib::object_id::ObjectId as _;
28 use jj_lib::repo::Repo;
29 use jj_lib::revset::FunctionCallNode;
30 use jj_lib::revset::LoweringContext;
31 use jj_lib::revset::PartialSymbolResolver;
32 use jj_lib::revset::RevsetDiagnostics;
33 use jj_lib::revset::RevsetExpression;
34 use jj_lib::revset::RevsetFilterExtension;
35 use jj_lib::revset::RevsetFilterPredicate;
36 use jj_lib::revset::RevsetParseError;
37 use jj_lib::revset::RevsetResolutionError;
38 use jj_lib::revset::SymbolResolverExtension;
39 use jj_lib::revset::UserRevsetExpression;
40 use once_cell::sync::OnceCell;
41 use pollster::FutureExt as _;
42
43 struct HexCounter;
44
45 fn num_digits_in_id(id: &CommitId) -> i64 {
46 let mut count = 0;
47 for ch in id.hex().chars() {
48 if ch.is_ascii_digit() {
49 count += 1;
50 }
51 }
52 count
53 }
54
55 fn num_char_in_id(commit: Commit, ch_match: char) -> i64 {
56 let mut count = 0;
57 for ch in commit.id().hex().chars() {
58 if ch == ch_match {
59 count += 1;
60 }
61 }
62 count
63 }
64
65 #[derive(Default)]
66 struct MostDigitsInId {
67 count: OnceCell<i64>,
68 }
69
70 impl MostDigitsInId {
71 fn count(&self, repo: &dyn Repo) -> i64 {
72 *self.count.get_or_init(|| {
73 RevsetExpression::all()
74 .evaluate(repo)
75 .unwrap()
76 .stream()
77 .try_collect::<Vec<_>>()
78 .block_on()
79 .unwrap()
80 .iter()
81 .map(num_digits_in_id)
82 .max()
83 .unwrap_or(0)
84 })
85 }
86 }
87
88 #[derive(Default)]
89 struct TheDigitestResolver {
90 cache: MostDigitsInId,
91 }
92
93 impl PartialSymbolResolver for TheDigitestResolver {
94 fn resolve_symbol(
95 &self,
96 repo: &dyn Repo,
97 symbol: &str,
98 ) -> Result<Option<CommitId>, RevsetResolutionError> {
99 if symbol != "thedigitest" {
100 return Ok(None);
101 }
102
103 Ok(RevsetExpression::all()
104 .evaluate(repo)
105 .map_err(|err| RevsetResolutionError::Other(err.into()))?
106 .stream()
107 .try_collect::<Vec<_>>()
108 .block_on()
109 .unwrap()
110 .iter()
111 .find(|id| num_digits_in_id(id) == self.cache.count(repo))
112 .cloned())
113 }
114 }
115
116 struct TheDigitest;
117
118 impl SymbolResolverExtension for TheDigitest {
119 fn new_resolvers<'a>(&self, _repo: &'a dyn Repo) -> Vec<Box<dyn PartialSymbolResolver + 'a>> {
120 vec![Box::<TheDigitestResolver>::default()]
121 }
122 }
123
124 impl CommitTemplateLanguageExtension for HexCounter {
125 fn build_fn_table<'repo>(&self) -> CommitTemplateBuildFnTable<'repo> {
126 let mut table = CommitTemplateBuildFnTable::empty();
127 table.commit_methods.insert(
128 "has_most_digits",
129 |language, _diagnostics, _build_context, property, call| {
130 call.expect_no_arguments()?;
131 let most_digits = language
132 .cache_extension::<MostDigitsInId>()
133 .unwrap()
134 .count(language.repo());
135 let out_property =
136 property.map(move |commit| num_digits_in_id(commit.id()) == most_digits);
137 Ok(out_property.into_dyn_wrapped())
138 },
139 );
140 table.commit_methods.insert(
141 "num_digits_in_id",
142 |_language, _diagnostics, _build_context, property, call| {
143 call.expect_no_arguments()?;
144 let out_property = property.map(|commit| num_digits_in_id(commit.id()));
145 Ok(out_property.into_dyn_wrapped())
146 },
147 );
148 table.commit_methods.insert(
149 "num_char_in_id",
150 |_language, diagnostics, _build_context, property, call| {
151 let [string_arg] = call.expect_exact_arguments()?;
152 let char_arg = template_parser::catch_aliases(
153 diagnostics,
154 string_arg,
155 |_diagnostics, arg| {
156 let string = template_parser::expect_string_literal(arg)?;
157 let chars: Vec<_> = string.chars().collect();
158 match chars[..] {
159 [ch] => Ok(ch),
160 _ => Err(TemplateParseError::expression(
161 "Expected singular character argument",
162 arg.span,
163 )),
164 }
165 },
166 )?;
167
168 let out_property = property.map(move |commit| num_char_in_id(commit, char_arg));
169 Ok(out_property.into_dyn_wrapped())
170 },
171 );
172
173 table
174 }
175
176 fn build_cache_extensions(&self, extensions: &mut ExtensionsMap) {
177 extensions.insert(MostDigitsInId::default());
178 }
179 }
180
181 #[derive(Debug)]
182 struct EvenDigitsFilter;
183
184 impl RevsetFilterExtension for EvenDigitsFilter {
185 fn matches_commit(&self, commit: &Commit) -> bool {
186 num_digits_in_id(commit.id()) % 2 == 0
187 }
188 }
189
190 fn even_digits(
191 _diagnostics: &mut RevsetDiagnostics,
192 function: &FunctionCallNode,
193 _context: &LoweringContext,
194 ) -> Result<Arc<UserRevsetExpression>, RevsetParseError> {
195 function.expect_no_arguments()?;
196 Ok(RevsetExpression::filter(RevsetFilterPredicate::Extension(
197 Arc::new(EvenDigitsFilter),
198 )))
199 }
200
201 fn main() -> std::process::ExitCode {
202 CliRunner::init()
203 .add_symbol_resolver_extension(Box::new(TheDigitest))
204 .add_revset_function_extension("even_digits", even_digits)
205 .add_commit_template_extension(Box::new(HexCounter))
206 .run()
207 .into()
208 }