-
Notifications
You must be signed in to change notification settings - Fork 403
/
Copy pathdebug.rs
323 lines (298 loc) · 11.7 KB
/
debug.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
// Copyright 2023 The Jujutsu Authors
//
// 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
//
// https://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.
use std::any::Any;
use std::fmt::Debug;
use std::io::Write as _;
use clap::Subcommand;
use jj_lib::backend::ObjectId;
use jj_lib::default_index_store::{DefaultIndexStore, ReadonlyIndexWrapper};
use jj_lib::local_working_copy::{LocalWorkingCopy, LockedLocalWorkingCopy};
use jj_lib::revset;
use jj_lib::working_copy::WorkingCopy;
use crate::cli_util::{resolve_op_for_load, user_error, CommandError, CommandHelper, RevisionArg};
use crate::template_parser;
use crate::ui::Ui;
/// Low-level commands not intended for users
#[derive(Subcommand, Clone, Debug)]
#[command(hide = true)]
pub enum DebugCommands {
Revset(DebugRevsetArgs),
#[command(name = "workingcopy")]
WorkingCopy(DebugWorkingCopyArgs),
Template(DebugTemplateArgs),
Index(DebugIndexArgs),
#[command(name = "reindex")]
ReIndex(DebugReIndexArgs),
#[command(visible_alias = "view")]
Operation(DebugOperationArgs),
Tree(DebugTreeArgs),
#[command(subcommand)]
Watchman(DebugWatchmanSubcommand),
}
/// Evaluate revset to full commit IDs
#[derive(clap::Args, Clone, Debug)]
pub struct DebugRevsetArgs {
revision: String,
}
/// Show information about the working copy state
#[derive(clap::Args, Clone, Debug)]
pub struct DebugWorkingCopyArgs {}
/// Parse a template
#[derive(clap::Args, Clone, Debug)]
pub struct DebugTemplateArgs {
template: String,
}
/// Show commit index stats
#[derive(clap::Args, Clone, Debug)]
pub struct DebugIndexArgs {}
/// Rebuild commit index
#[derive(clap::Args, Clone, Debug)]
pub struct DebugReIndexArgs {}
/// Show information about an operation and its view
#[derive(clap::Args, Clone, Debug)]
pub struct DebugOperationArgs {
#[arg(default_value = "@")]
operation: String,
#[arg(long, value_enum, default_value = "all")]
display: DebugOperationDisplay,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, clap::ValueEnum)]
pub enum DebugOperationDisplay {
/// Show only the operation details.
Operation,
/// Show the operation id only
Id,
/// Show only the view details
View,
/// Show both the view and the operation
All,
}
/// List the recursive entries of a tree.
#[derive(clap::Args, Clone, Debug)]
pub struct DebugTreeArgs {
#[arg(long, short = 'r', default_value = "@")]
revision: RevisionArg,
paths: Vec<String>,
// TODO: Add an option to include trees that are ancestors of the matched paths
}
#[derive(Subcommand, Clone, Debug)]
pub enum DebugWatchmanSubcommand {
QueryClock,
QueryChangedFiles,
ResetClock,
}
pub fn cmd_debug(
ui: &mut Ui,
command: &CommandHelper,
subcommand: &DebugCommands,
) -> Result<(), CommandError> {
match subcommand {
DebugCommands::Revset(args) => cmd_debug_revset(ui, command, args)?,
DebugCommands::WorkingCopy(_wc_matches) => {
let workspace_command = command.workspace_helper(ui)?;
let wc = check_local_disk_wc(workspace_command.working_copy().as_any())?;
writeln!(ui.stdout(), "Current operation: {:?}", wc.operation_id())?;
writeln!(ui.stdout(), "Current tree: {:?}", wc.tree_id()?)?;
for (file, state) in wc.file_states()? {
writeln!(
ui.stdout(),
"{:?} {:13?} {:10?} {:?}",
state.file_type,
state.size,
state.mtime.0,
file
)?;
}
}
DebugCommands::Template(template_matches) => {
let node = template_parser::parse_template(&template_matches.template)?;
writeln!(ui.stdout(), "{node:#?}")?;
}
DebugCommands::Index(_index_matches) => {
let workspace_command = command.workspace_helper(ui)?;
let repo = workspace_command.repo();
let index_impl: Option<&ReadonlyIndexWrapper> =
repo.readonly_index().as_any().downcast_ref();
if let Some(index_impl) = index_impl {
let stats = index_impl.as_composite().stats();
writeln!(ui.stdout(), "Number of commits: {}", stats.num_commits)?;
writeln!(ui.stdout(), "Number of merges: {}", stats.num_merges)?;
writeln!(
ui.stdout(),
"Max generation number: {}",
stats.max_generation_number
)?;
writeln!(ui.stdout(), "Number of heads: {}", stats.num_heads)?;
writeln!(ui.stdout(), "Number of changes: {}", stats.num_changes)?;
writeln!(ui.stdout(), "Stats per level:")?;
for (i, level) in stats.levels.iter().enumerate() {
writeln!(ui.stdout(), " Level {i}:")?;
writeln!(ui.stdout(), " Number of commits: {}", level.num_commits)?;
writeln!(ui.stdout(), " Name: {}", level.name.as_ref().unwrap())?;
}
} else {
return Err(user_error(format!(
"Cannot get stats for indexes of type '{}'",
repo.index_store().name()
)));
}
}
DebugCommands::ReIndex(_reindex_matches) => {
let workspace_command = command.workspace_helper(ui)?;
let repo = workspace_command.repo();
let default_index_store: Option<&DefaultIndexStore> =
repo.index_store().as_any().downcast_ref();
if let Some(default_index_store) = default_index_store {
default_index_store.reinit();
let repo = repo.reload_at(repo.operation())?;
let index_impl: &ReadonlyIndexWrapper = repo
.readonly_index()
.as_any()
.downcast_ref()
.expect("Default index should be a ReadonlyIndexWrapper");
writeln!(
ui.stderr(),
"Finished indexing {:?} commits.",
index_impl.as_composite().stats().num_commits
)?;
} else {
return Err(user_error(format!(
"Cannot reindex indexes of type '{}'",
repo.index_store().name()
)));
}
}
DebugCommands::Operation(operation_args) => {
// Resolve the operation without loading the repo, so this command can be used
// even if e.g. the view object is broken.
let workspace = command.load_workspace()?;
let repo_loader = workspace.repo_loader();
let op = resolve_op_for_load(
repo_loader.op_store(),
repo_loader.op_heads_store(),
&operation_args.operation,
)?;
if operation_args.display == DebugOperationDisplay::Id {
writeln!(ui.stdout(), "{}", op.id().hex())?;
return Ok(());
}
if operation_args.display != DebugOperationDisplay::View {
writeln!(ui.stdout(), "{:#?}", op.store_operation())?;
}
if operation_args.display != DebugOperationDisplay::Operation {
writeln!(ui.stdout(), "{:#?}", op.view()?.store_view())?;
}
}
DebugCommands::Tree(sub_args) => cmd_debug_tree(ui, command, sub_args)?,
DebugCommands::Watchman(watchman_subcommand) => {
cmd_debug_watchman(ui, command, watchman_subcommand)?;
}
}
Ok(())
}
fn cmd_debug_revset(
ui: &mut Ui,
command: &CommandHelper,
args: &DebugRevsetArgs,
) -> Result<(), CommandError> {
let workspace_command = command.workspace_helper(ui)?;
let workspace_ctx = workspace_command.revset_parse_context();
let repo = workspace_command.repo().as_ref();
let expression = revset::parse(&args.revision, &workspace_ctx)?;
writeln!(ui.stdout(), "-- Parsed:")?;
writeln!(ui.stdout(), "{expression:#?}")?;
writeln!(ui.stdout())?;
let expression = revset::optimize(expression);
writeln!(ui.stdout(), "-- Optimized:")?;
writeln!(ui.stdout(), "{expression:#?}")?;
writeln!(ui.stdout())?;
let symbol_resolver = workspace_command.revset_symbol_resolver()?;
let expression = expression.resolve_user_expression(repo, &symbol_resolver)?;
writeln!(ui.stdout(), "-- Resolved:")?;
writeln!(ui.stdout(), "{expression:#?}")?;
writeln!(ui.stdout())?;
let revset = expression.evaluate(repo)?;
writeln!(ui.stdout(), "-- Evaluated:")?;
writeln!(ui.stdout(), "{revset:#?}")?;
writeln!(ui.stdout())?;
writeln!(ui.stdout(), "-- Commit IDs:")?;
for commit_id in revset.iter() {
writeln!(ui.stdout(), "{}", commit_id.hex())?;
}
Ok(())
}
fn cmd_debug_tree(
ui: &mut Ui,
command: &CommandHelper,
args: &DebugTreeArgs,
) -> Result<(), CommandError> {
let workspace_command = command.workspace_helper(ui)?;
let commit = workspace_command.resolve_single_rev(&args.revision, ui)?;
let tree = commit.tree()?;
let matcher = workspace_command.matcher_from_values(&args.paths)?;
for (path, value) in tree.entries_matching(matcher.as_ref()) {
let ui_path = workspace_command.format_file_path(&path);
writeln!(ui.stdout(), "{ui_path}: {value:?}")?;
}
Ok(())
}
#[cfg(feature = "watchman")]
fn cmd_debug_watchman(
ui: &mut Ui,
command: &CommandHelper,
subcommand: &DebugWatchmanSubcommand,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let repo = workspace_command.repo().clone();
match subcommand {
DebugWatchmanSubcommand::QueryClock => {
let wc = check_local_disk_wc(workspace_command.working_copy().as_any())?;
let (clock, _changed_files) = wc.query_watchman()?;
writeln!(ui.stdout(), "Clock: {clock:?}")?;
}
DebugWatchmanSubcommand::QueryChangedFiles => {
let wc = check_local_disk_wc(workspace_command.working_copy().as_any())?;
let (_clock, changed_files) = wc.query_watchman()?;
writeln!(ui.stdout(), "Changed files: {changed_files:?}")?;
}
DebugWatchmanSubcommand::ResetClock => {
let (mut locked_ws, _commit) = workspace_command.start_working_copy_mutation()?;
let Some(locked_local_wc): Option<&mut LockedLocalWorkingCopy> =
locked_ws.locked_wc().as_any_mut().downcast_mut()
else {
return Err(user_error(
"This command requires a standard local-disk working copy",
));
};
locked_local_wc.reset_watchman()?;
locked_ws.finish(repo.op_id().clone())?;
writeln!(ui.stderr(), "Reset Watchman clock")?;
}
}
Ok(())
}
#[cfg(not(feature = "watchman"))]
fn cmd_debug_watchman(
_ui: &mut Ui,
_command: &CommandHelper,
_subcommand: &DebugWatchmanSubcommand,
) -> Result<(), CommandError> {
Err(user_error(
"Cannot query Watchman because jj was not compiled with the `watchman` feature",
))
}
fn check_local_disk_wc(x: &dyn Any) -> Result<&LocalWorkingCopy, CommandError> {
x.downcast_ref()
.ok_or_else(|| user_error("This command requires a standard local-disk working copy"))
}