Debian Codegraph @

cli/src/commands/file/show.rs

raw
1 // Copyright 2020 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::io::Write as _;
16
17 use clap_complete::ArgValueCandidates;
18 use clap_complete::ArgValueCompleter;
19 use itertools::Itertools as _;
20 use jj_lib::backend::BackendResult;
21 use jj_lib::backend::MergedTreeValueExt as _;
22 use jj_lib::conflicts::ConflictMaterializeOptions;
23 use jj_lib::conflicts::MaterializedTreeValue;
24 use jj_lib::conflicts::materialize_merge_result;
25 use jj_lib::conflicts::materialize_tree_value;
26 use jj_lib::file_util::copy_async_to_sync;
27 use jj_lib::fileset::FilePattern;
28 use jj_lib::fileset::FilesetExpression;
29 use jj_lib::merged_tree::MergedTree;
30 use jj_lib::repo::Repo as _;
31 use jj_lib::repo_path::RepoPath;
32 use tracing::instrument;
33
34 use crate::cli_util::CommandHelper;
35 use crate::cli_util::RevisionArg;
36 use crate::cli_util::WorkspaceCommandHelper;
37 use crate::cli_util::print_unmatched_explicit_paths;
38 use crate::command_error::CommandError;
39 use crate::command_error::user_error;
40 use crate::commit_templater::TreeEntry;
41 use crate::complete;
42 use crate::templater::TemplateRenderer;
43 use crate::ui::Ui;
44
45 /// Print contents of files in a revision
46 ///
47 /// If the given path is a directory, files in the directory will be visited
48 /// recursively.
49 #[derive(clap::Args, Clone, Debug)]
50 pub(crate) struct FileShowArgs {
51 /// The revision to get the file contents from
52 #[arg(long, short, default_value = "@", value_name = "REVSET")]
53 #[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
54 revision: RevisionArg,
55
56 /// Render each file metadata using the given template
57 ///
58 /// All 0-argument methods of the [`TreeEntry` type] are available as
59 /// keywords in the template expression. See [`jj help -k templates`] for
60 /// more information.
61 ///
62 /// If not specified, this defaults to the `templates.file_show` setting.
63 ///
64 /// [`TreeEntry` type]:
65 /// https://docs.jj-vcs.dev/latest/templates/#treeentry-type
66 ///
67 /// [`jj help -k templates`]:
68 /// https://docs.jj-vcs.dev/latest/templates/
69 #[arg(long, short = 'T')]
70 #[arg(add = ArgValueCandidates::new(complete::template_aliases))]
71 template: Option<String>,
72
73 /// Paths to print
74 #[arg(required = true, value_name = "FILESETS", value_hint = clap::ValueHint::FilePath)]
75 #[arg(add = ArgValueCompleter::new(complete::all_revision_files))]
76 paths: Vec<String>,
77 }
78
79 #[instrument(skip_all)]
80 pub(crate) async fn cmd_file_show(
81 ui: &mut Ui,
82 command: &CommandHelper,
83 args: &FileShowArgs,
84 ) -> Result<(), CommandError> {
85 let workspace_command = command.workspace_helper(ui).await?;
86 let commit = workspace_command
87 .resolve_single_rev(ui, &args.revision)
88 .await?;
89 let tree = commit.tree();
90 // TODO: No need to add special case for empty paths when switching to
91 // parse_union_filesets(). paths = [] should be "none()" if supported.
92 let fileset_expression = workspace_command.parse_file_patterns(ui, &args.paths)?;
93 let template = {
94 let language = workspace_command.commit_template_language();
95 let text = match &args.template {
96 Some(value) => value.to_owned(),
97 None => workspace_command.settings().get("templates.file_show")?,
98 };
99 workspace_command
100 .parse_template(ui, &language, &text)?
101 .labeled(["file_show"])
102 };
103
104 // Try fast path for single file entry
105 if let Some(path) = get_single_path(&fileset_expression) {
106 let value = tree.path_value(path).await?;
107 if value.is_absent() {
108 let ui_path = workspace_command.format_file_path(path);
109 return Err(user_error(format!("No such path: {ui_path}")));
110 }
111 if !value.is_tree() {
112 ui.request_pager();
113 let entry = TreeEntry {
114 path: path.to_owned(),
115 value,
116 };
117 write_tree_entries(ui, &workspace_command, &template, &tree, [Ok(entry)]).await?;
118 return Ok(());
119 }
120 }
121
122 let matcher = fileset_expression.to_matcher();
123 ui.request_pager();
124 write_tree_entries(
125 ui,
126 &workspace_command,
127 &template,
128 &tree,
129 tree.entries_matching(matcher.as_ref())
130 .map(|(path, value)| Ok((path, value?)))
131 .map_ok(|(path, value)| TreeEntry { path, value }),
132 )
133 .await?;
134 print_unmatched_explicit_paths(ui, &workspace_command, &fileset_expression, [&tree]).await?;
135 Ok(())
136 }
137
138 fn get_single_path(expression: &FilesetExpression) -> Option<&RepoPath> {
139 match &expression {
140 FilesetExpression::Pattern(pattern) => match pattern {
141 // Not using pattern.as_path() because files-in:<path> shouldn't
142 // select the literal <path> itself.
143 FilePattern::FilePath(path) | FilePattern::PrefixPath(path) => Some(path),
144 FilePattern::FileGlob { .. } | FilePattern::PrefixGlob { .. } => None,
145 },
146 _ => None,
147 }
148 }
149
150 async fn write_tree_entries(
151 ui: &Ui,
152 workspace_command: &WorkspaceCommandHelper,
153 template: &TemplateRenderer<'_, TreeEntry>,
154 tree: &MergedTree,
155 entries: impl IntoIterator<Item = BackendResult<TreeEntry>>,
156 ) -> Result<(), CommandError> {
157 let repo = workspace_command.repo();
158 for entry in entries {
159 let entry = entry?;
160 template.format(&entry, ui.stdout_formatter().as_mut())?;
161 let materialized =
162 materialize_tree_value(repo.store(), &entry.path, entry.value, tree.labels()).await?;
163 match materialized {
164 MaterializedTreeValue::Absent => panic!("absent values should be excluded"),
165 MaterializedTreeValue::AccessDenied(err) => {
166 let ui_path = workspace_command.format_file_path(&entry.path);
167 writeln!(
168 ui.warning_default(),
169 "Path '{ui_path}' exists but access is denied: {err}"
170 )?;
171 }
172 MaterializedTreeValue::File(file) => {
173 copy_async_to_sync(file.reader, ui.stdout_formatter().as_mut()).await?;
174 }
175 MaterializedTreeValue::FileConflict(file) => {
176 let options = ConflictMaterializeOptions {
177 marker_style: workspace_command.env().conflict_marker_style(),
178 marker_len: None,
179 merge: repo.store().merge_options().clone(),
180 };
181 materialize_merge_result(
182 &file.contents,
183 &file.labels,
184 &mut ui.stdout_formatter(),
185 &options,
186 )?;
187 }
188 MaterializedTreeValue::OtherConflict { id, labels } => {
189 ui.stdout_formatter()
190 .write_all(id.describe(&labels).as_bytes())?;
191 }
192 MaterializedTreeValue::Symlink { .. } | MaterializedTreeValue::GitSubmodule(_) => {
193 let ui_path = workspace_command.format_file_path(&entry.path);
194 writeln!(
195 ui.warning_default(),
196 "Path '{ui_path}' exists but is not a file."
197 )?;
198 }
199 MaterializedTreeValue::Tree(_) => panic!("entries should not contain trees"),
200 }
201 }
202 Ok(())
203 }