1use std::collections::HashMap;
2use std::fs;
3use std::io;
4use std::io::Write as _;
5use std::path::Path;
6use std::path::PathBuf;
7use std::process::ExitStatus;
8
9use bstr::ByteVec as _;
10use indexmap::IndexMap;
11use indoc::indoc;
12use itertools::FoldWhile;
13use itertools::Itertools as _;
14use jj_lib::backend::CommitId;
15use jj_lib::commit::Commit;
16use jj_lib::commit_builder::DetachedCommitBuilder;
17use jj_lib::config::ConfigGetError;
18use jj_lib::file_util::IoResultExt as _;
19use jj_lib::file_util::PathError;
20use jj_lib::settings::UserSettings;
21use jj_lib::trailer::parse_description_trailers;
22use jj_lib::trailer::parse_trailers;
23use thiserror::Error;
24
25use crate::cli_util::WorkspaceCommandTransaction;
26use crate::cli_util::short_commit_hash;
27use crate::command_error::CommandError;
28use crate::command_error::user_error;
29use crate::config::CommandNameAndArgs;
30use crate::formatter::PlainTextFormatter;
31use crate::templater::TemplateRenderer;
32use crate::text_util;
33use crate::ui::Ui;
34
35#[derive(Debug, Error)]
36pub enum TextEditError {
37 #[error("Failed to run editor '{name}'")]
38 FailedToRun { name: String, source: io::Error },
39 #[error("Editor '{command}' exited with {status}")]
40 ExitStatus { command: String, status: ExitStatus },
41}
42
43#[derive(Debug, Error)]
44#[error("Failed to edit {name}", name = name.as_deref().unwrap_or("file"))]
45pub struct TempTextEditError {
46 #[source]
47 pub error: Box<dyn std::error::Error + Send + Sync>,
48 pub name: Option<String>,
50 pub path: Option<PathBuf>,
52}
53
54impl TempTextEditError {
55 fn new(error: Box<dyn std::error::Error + Send + Sync>, path: Option<PathBuf>) -> Self {
56 Self {
57 error,
58 name: None,
59 path,
60 }
61 }
62
63 pub fn with_name(mut self, name: impl Into<String>) -> Self {
65 self.name = Some(name.into());
66 self
67 }
68}
69
70#[derive(Clone, Debug)]
72pub struct TextEditor {
73 editor: CommandNameAndArgs,
74 dir: Option<PathBuf>,
75}
76
77impl TextEditor {
78 pub fn from_settings(settings: &UserSettings) -> Result<Self, ConfigGetError> {
79 let editor = settings.get("ui.editor")?;
80 Ok(Self { editor, dir: None })
81 }
82
83 pub fn with_temp_dir(mut self, dir: impl Into<PathBuf>) -> Self {
84 self.dir = Some(dir.into());
85 self
86 }
87
88 pub fn edit_file(&self, path: impl AsRef<Path>) -> Result<(), TextEditError> {
90 let mut cmd = self.editor.to_command();
91 cmd.arg(path.as_ref());
92 tracing::info!(?cmd, "running editor");
93 let status = cmd.status().map_err(|source| TextEditError::FailedToRun {
94 name: self.editor.split_name().into_owned(),
95 source,
96 })?;
97 if status.success() {
98 Ok(())
99 } else {
100 let command = self.editor.to_string();
101 Err(TextEditError::ExitStatus { command, status })
102 }
103 }
104
105 pub fn edit_str(
107 &self,
108 content: impl AsRef<[u8]>,
109 suffix: Option<&str>,
110 ) -> Result<String, TempTextEditError> {
111 let path = self
112 .write_temp_file(content.as_ref(), suffix)
113 .map_err(|err| TempTextEditError::new(err.into(), None))?;
114 self.edit_file(&path)
115 .map_err(|err| TempTextEditError::new(err.into(), Some(path.clone())))?;
116 let edited = fs::read_to_string(&path)
117 .context(&path)
118 .map_err(|err| TempTextEditError::new(err.into(), Some(path.clone())))?;
119 fs::remove_file(path).ok();
121 Ok(edited)
122 }
123
124 fn write_temp_file(&self, content: &[u8], suffix: Option<&str>) -> Result<PathBuf, PathError> {
125 let dir = self.dir.clone().unwrap_or_else(tempfile::env::temp_dir);
126 let mut file = tempfile::Builder::new()
127 .prefix("editor-")
128 .suffix(suffix.unwrap_or(""))
129 .tempfile_in(&dir)
130 .context(&dir)?;
131 file.write_all(content).context(file.path())?;
132 let (_, path) = file
133 .keep()
134 .or_else(|err| Err(err.error).context(err.file.path()))?;
135 Ok(path)
136 }
137}
138
139fn append_blank_line(text: &mut String) {
140 if !text.is_empty() && !text.ends_with('\n') {
141 text.push('\n');
142 }
143 let last_line = text.lines().next_back();
144 if last_line.is_some_and(|line| line.starts_with("JJ:")) {
145 text.push_str("JJ:\n");
146 } else {
147 text.push('\n');
148 }
149}
150
151fn cleanup_description_lines<I>(lines: I) -> String
154where
155 I: IntoIterator,
156 I::Item: AsRef<str>,
157{
158 let description = lines
159 .into_iter()
160 .fold_while(String::new(), |acc, line| {
161 let line = line.as_ref();
162 if line.strip_prefix("JJ: ignore-rest").is_some() {
163 FoldWhile::Done(acc)
164 } else if line.starts_with("JJ:") {
165 FoldWhile::Continue(acc)
166 } else {
167 FoldWhile::Continue(acc + line + "\n")
168 }
169 })
170 .into_inner();
171 text_util::complete_newline(description.trim_matches('\n'))
172}
173
174pub fn edit_description(editor: &TextEditor, description: &str) -> Result<String, CommandError> {
175 let mut description = description.to_owned();
176 append_blank_line(&mut description);
177 description.push_str("JJ: Lines starting with \"JJ:\" (like this one) will be removed.\n");
178
179 let description = editor
180 .edit_str(description, Some(".jjdescription"))
181 .map_err(|err| err.with_name("description"))?;
182
183 Ok(cleanup_description_lines(description.lines()))
184}
185
186pub fn edit_multiple_descriptions(
188 ui: &Ui,
189 editor: &TextEditor,
190 tx: &WorkspaceCommandTransaction,
191 commits: &[(&CommitId, Commit)],
192) -> Result<ParsedBulkEditMessage<CommitId>, CommandError> {
193 let mut commits_map = IndexMap::new();
194 let mut bulk_message = String::new();
195
196 bulk_message.push_str(indoc! {r#"
197 JJ: Enter or edit commit descriptions after the `JJ: describe` lines.
198 JJ: Warning:
199 JJ: - The text you enter will be lost on a syntax error.
200 JJ: - The syntax of the separator lines may change in the future.
201 JJ:
202 "#});
203 for (commit_id, temp_commit) in commits {
204 let commit_hash = short_commit_hash(commit_id);
205 bulk_message.push_str("JJ: describe ");
206 bulk_message.push_str(&commit_hash);
207 bulk_message.push_str(" -------\n");
208 commits_map.insert(commit_hash, *commit_id);
209 let intro = "";
210 let template = description_template(ui, tx, intro, temp_commit)?;
211 bulk_message.push_str(&template);
212 append_blank_line(&mut bulk_message);
213 }
214 bulk_message.push_str("JJ: Lines starting with \"JJ:\" (like this one) will be removed.\n");
215
216 let bulk_message = editor
217 .edit_str(bulk_message, Some(".jjdescription"))
218 .map_err(|err| err.with_name("description"))?;
219
220 Ok(parse_bulk_edit_message(&bulk_message, &commits_map)?)
221}
222
223#[derive(Debug)]
224pub struct ParsedBulkEditMessage<T> {
225 pub descriptions: HashMap<T, String>,
227 pub missing: Vec<String>,
230 pub duplicates: Vec<String>,
233 pub unexpected: Vec<String>,
236}
237
238#[derive(Debug, Error, PartialEq)]
239pub enum ParseBulkEditMessageError {
240 #[error(r#"Found the following line without a commit header: "{0}""#)]
241 LineWithoutCommitHeader(String),
242}
243
244fn parse_bulk_edit_message<T>(
246 message: &str,
247 commit_ids_map: &IndexMap<String, &T>,
248) -> Result<ParsedBulkEditMessage<T>, ParseBulkEditMessageError>
249where
250 T: Eq + std::hash::Hash + Clone,
251{
252 let mut descriptions = HashMap::new();
253 let mut duplicates = Vec::new();
254 let mut unexpected = Vec::new();
255
256 let mut messages: Vec<(&str, Vec<&str>)> = vec![];
257 for line in message.lines() {
258 if let Some(commit_id_prefix) = line.strip_prefix("JJ: describe ") {
259 let commit_id_prefix =
260 commit_id_prefix.trim_end_matches(|c: char| c.is_ascii_whitespace() || c == '-');
261 messages.push((commit_id_prefix, vec![]));
262 } else if let Some((_, lines)) = messages.last_mut() {
263 lines.push(line);
264 }
265 else if !line.trim().is_empty() && !line.starts_with("JJ:") {
267 return Err(ParseBulkEditMessageError::LineWithoutCommitHeader(
268 line.to_owned(),
269 ));
270 };
271 }
272
273 for (commit_id_prefix, description_lines) in messages {
274 let Some(&commit_id) = commit_ids_map.get(commit_id_prefix) else {
275 unexpected.push(commit_id_prefix.to_string());
276 continue;
277 };
278 if descriptions.contains_key(commit_id) {
279 duplicates.push(commit_id_prefix.to_string());
280 continue;
281 }
282 descriptions.insert(
283 commit_id.clone(),
284 cleanup_description_lines(&description_lines),
285 );
286 }
287
288 let missing: Vec<_> = commit_ids_map
289 .iter()
290 .filter(|(_, commit_id)| !descriptions.contains_key(*commit_id))
291 .map(|(commit_id_prefix, _)| commit_id_prefix.clone())
292 .collect();
293
294 Ok(ParsedBulkEditMessage {
295 descriptions,
296 missing,
297 duplicates,
298 unexpected,
299 })
300}
301
302pub fn try_combine_messages(sources: &[Commit], destination: &Commit) -> Option<String> {
305 let non_empty = sources
306 .iter()
307 .chain(std::iter::once(destination))
308 .filter(|c| !c.description().is_empty())
309 .take(2)
310 .collect_vec();
311 match *non_empty.as_slice() {
312 [] => Some(String::new()),
313 [commit] => Some(commit.description().to_owned()),
314 [_, _, ..] => None,
315 }
316}
317
318pub fn combine_messages_for_editing(
323 ui: &Ui,
324 tx: &WorkspaceCommandTransaction,
325 sources: &[Commit],
326 destination: Option<&Commit>,
327 commit_builder: &DetachedCommitBuilder,
328) -> Result<String, CommandError> {
329 let mut combined = String::new();
330 if let Some(destination) = destination {
331 combined.push_str("JJ: Description from the destination commit:\n");
332 combined.push_str(destination.description());
333 }
334 for commit in sources {
335 combined.push_str("\nJJ: Description from source commit:\n");
336 combined.push_str(commit.description());
337 }
338
339 if let Some(template) = parse_trailers_template(ui, tx)? {
340 let old_trailers: Vec<_> = sources
342 .iter()
343 .chain(destination)
344 .flat_map(|commit| parse_description_trailers(commit.description()))
345 .collect();
346 let commit = commit_builder.write_hidden()?;
347 let trailer_lines = template
348 .format_plain_text(&commit)
349 .into_string()
350 .map_err(|_| user_error("Trailers should be valid utf-8"))?;
351 let new_trailers = parse_trailers(&trailer_lines)?;
352 let trailers: String = new_trailers
353 .iter()
354 .filter(|trailer| !old_trailers.contains(trailer))
355 .map(|trailer| format!("{}: {}\n", trailer.key, trailer.value))
356 .collect();
357 if !trailers.is_empty() {
358 combined.push_str("\nJJ: Trailers not found in the squashed commits:\n");
359 combined.push_str(&trailers);
360 }
361 }
362
363 Ok(combined)
364}
365
366pub fn join_message_paragraphs(paragraphs: &[String]) -> String {
371 paragraphs
374 .iter()
375 .map(|p| text_util::complete_newline(p.as_str()))
376 .join("\n")
377}
378
379pub fn parse_trailers_template<'a>(
383 ui: &Ui,
384 tx: &'a WorkspaceCommandTransaction,
385) -> Result<Option<TemplateRenderer<'a, Commit>>, CommandError> {
386 let trailer_template = tx.settings().get_string("templates.commit_trailers")?;
387 if trailer_template.is_empty() {
388 Ok(None)
389 } else {
390 tx.parse_commit_template(ui, &trailer_template).map(Some)
391 }
392}
393
394pub fn add_trailers_with_template(
399 template: &TemplateRenderer<'_, Commit>,
400 commit: &Commit,
401) -> Result<String, CommandError> {
402 let trailers = parse_description_trailers(commit.description());
403 let trailer_lines = template
404 .format_plain_text(commit)
405 .into_string()
406 .map_err(|_| user_error("Trailers should be valid utf-8"))?;
407 let new_trailers = parse_trailers(&trailer_lines)?;
408 let mut description = commit.description().to_owned();
409 if trailers.is_empty() && !new_trailers.is_empty() {
410 if description.is_empty() {
411 description.push('\n');
413 }
414 description.push('\n');
416 }
417 for new_trailer in new_trailers {
418 if !trailers.contains(&new_trailer) {
419 description.push_str(&format!("{}: {}\n", new_trailer.key, new_trailer.value));
420 }
421 }
422 Ok(description)
423}
424
425pub fn add_trailers(
430 ui: &Ui,
431 tx: &WorkspaceCommandTransaction,
432 commit_builder: &DetachedCommitBuilder,
433) -> Result<String, CommandError> {
434 if let Some(renderer) = parse_trailers_template(ui, tx)? {
435 let commit = commit_builder.write_hidden()?;
436 add_trailers_with_template(&renderer, &commit)
437 } else {
438 Ok(commit_builder.description().to_owned())
439 }
440}
441
442pub fn description_template(
444 ui: &Ui,
445 tx: &WorkspaceCommandTransaction,
446 intro: &str,
447 commit: &Commit,
448) -> Result<String, CommandError> {
449 let template_key = "templates.draft_commit_description";
451 let template_text = tx.settings().get_string(template_key)?;
452 let template = tx.parse_commit_template(ui, &template_text)?;
453
454 let mut output = Vec::new();
455 if !intro.is_empty() {
456 writeln!(output, "JJ: {intro}").unwrap();
457 }
458 template
459 .format(commit, &mut PlainTextFormatter::new(&mut output))
460 .expect("write() to vec backed formatter should never fail");
461 Ok(output.into_string_lossy())
463}
464
465#[cfg(test)]
466mod tests {
467 use indexmap::indexmap;
468 use indoc::indoc;
469 use maplit::hashmap;
470
471 use super::parse_bulk_edit_message;
472 use crate::description_util::ParseBulkEditMessageError;
473
474 #[test]
475 fn test_parse_complete_bulk_edit_message() {
476 let result = parse_bulk_edit_message(
477 indoc! {"
478 JJ: describe 1 -------
479 Description 1
480
481 JJ: describe 2
482 Description 2
483
484 JJ: describe 3 --
485 Description 3
486 "},
487 &indexmap! {
488 "1".to_string() => &1,
489 "2".to_string() => &2,
490 "3".to_string() => &3,
491 },
492 )
493 .unwrap();
494 assert_eq!(
495 result.descriptions,
496 hashmap! {
497 1 => "Description 1\n".to_string(),
498 2 => "Description 2\n".to_string(),
499 3 => "Description 3\n".to_string(),
500 }
501 );
502 assert!(result.missing.is_empty());
503 assert!(result.duplicates.is_empty());
504 assert!(result.unexpected.is_empty());
505 }
506
507 #[test]
508 fn test_parse_bulk_edit_message_with_missing_descriptions() {
509 let result = parse_bulk_edit_message(
510 indoc! {"
511 JJ: describe 1 -------
512 Description 1
513 "},
514 &indexmap! {
515 "1".to_string() => &1,
516 "2".to_string() => &2,
517 },
518 )
519 .unwrap();
520 assert_eq!(
521 result.descriptions,
522 hashmap! {
523 1 => "Description 1\n".to_string(),
524 }
525 );
526 assert_eq!(result.missing, vec!["2".to_string()]);
527 assert!(result.duplicates.is_empty());
528 assert!(result.unexpected.is_empty());
529 }
530
531 #[test]
532 fn test_parse_bulk_edit_message_with_duplicate_descriptions() {
533 let result = parse_bulk_edit_message(
534 indoc! {"
535 JJ: describe 1 -------
536 Description 1
537
538 JJ: describe 1 -------
539 Description 1 (repeated)
540 "},
541 &indexmap! {
542 "1".to_string() => &1,
543 },
544 )
545 .unwrap();
546 assert_eq!(
547 result.descriptions,
548 hashmap! {
549 1 => "Description 1\n".to_string(),
550 }
551 );
552 assert!(result.missing.is_empty());
553 assert_eq!(result.duplicates, vec!["1".to_string()]);
554 assert!(result.unexpected.is_empty());
555 }
556
557 #[test]
558 fn test_parse_bulk_edit_message_with_unexpected_descriptions() {
559 let result = parse_bulk_edit_message(
560 indoc! {"
561 JJ: describe 1 -------
562 Description 1
563
564 JJ: describe 3 -------
565 Description 3 (unexpected)
566 "},
567 &indexmap! {
568 "1".to_string() => &1,
569 },
570 )
571 .unwrap();
572 assert_eq!(
573 result.descriptions,
574 hashmap! {
575 1 => "Description 1\n".to_string(),
576 }
577 );
578 assert!(result.missing.is_empty());
579 assert!(result.duplicates.is_empty());
580 assert_eq!(result.unexpected, vec!["3".to_string()]);
581 }
582
583 #[test]
584 fn test_parse_bulk_edit_message_with_no_header() {
585 let result = parse_bulk_edit_message(
586 indoc! {"
587 Description 1
588 "},
589 &indexmap! {
590 "1".to_string() => &1,
591 },
592 );
593 assert_eq!(
594 result.unwrap_err(),
595 ParseBulkEditMessageError::LineWithoutCommitHeader("Description 1".to_string())
596 );
597 }
598
599 #[test]
600 fn test_parse_bulk_edit_message_with_comment_before_header() {
601 let result = parse_bulk_edit_message(
602 indoc! {"
603 JJ: Custom comment and empty lines below should be accepted
604
605
606 JJ: describe 1 -------
607 Description 1
608 "},
609 &indexmap! {
610 "1".to_string() => &1,
611 },
612 )
613 .unwrap();
614 assert_eq!(
615 result.descriptions,
616 hashmap! {
617 1 => "Description 1\n".to_string(),
618 }
619 );
620 assert!(result.missing.is_empty());
621 assert!(result.duplicates.is_empty());
622 assert!(result.unexpected.is_empty());
623 }
624}