Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #include <curses.h>
25 #include <panel.h>
26 #include <locale.h>
27 #include <sha1.h>
28 #include <sha2.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #include <string.h>
35 #include <err.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <wchar.h>
39 #include <time.h>
40 #include <pthread.h>
41 #include <libgen.h>
42 #include <regex.h>
43 #include <sched.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_diff.h"
51 #include "got_opentemp.h"
52 #include "got_utf8.h"
53 #include "got_cancel.h"
54 #include "got_commit_graph.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_path.h"
58 #include "got_worktree.h"
59 #include "got_keyword.h"
61 #ifndef MIN
62 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
63 #endif
65 #ifndef MAX
66 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
67 #endif
69 #define CTRL(x) ((x) & 0x1f)
71 #ifndef nitems
72 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
73 #endif
75 struct tog_cmd {
76 const char *name;
77 const struct got_error *(*cmd_main)(int, char *[]);
78 void (*cmd_usage)(void);
79 };
81 __dead static void usage(int, int);
82 __dead static void usage_log(void);
83 __dead static void usage_diff(void);
84 __dead static void usage_blame(void);
85 __dead static void usage_tree(void);
86 __dead static void usage_ref(void);
88 static const struct got_error* cmd_log(int, char *[]);
89 static const struct got_error* cmd_diff(int, char *[]);
90 static const struct got_error* cmd_blame(int, char *[]);
91 static const struct got_error* cmd_tree(int, char *[]);
92 static const struct got_error* cmd_ref(int, char *[]);
94 static const struct tog_cmd tog_commands[] = {
95 { "log", cmd_log, usage_log },
96 { "diff", cmd_diff, usage_diff },
97 { "blame", cmd_blame, usage_blame },
98 { "tree", cmd_tree, usage_tree },
99 { "ref", cmd_ref, usage_ref },
100 };
102 enum tog_view_type {
103 TOG_VIEW_DIFF,
104 TOG_VIEW_LOG,
105 TOG_VIEW_BLAME,
106 TOG_VIEW_TREE,
107 TOG_VIEW_REF,
108 TOG_VIEW_HELP
109 };
111 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
112 enum tog_keymap_type {
113 TOG_KEYMAP_KEYS = -2,
114 TOG_KEYMAP_GLOBAL,
115 TOG_KEYMAP_DIFF,
116 TOG_KEYMAP_LOG,
117 TOG_KEYMAP_BLAME,
118 TOG_KEYMAP_TREE,
119 TOG_KEYMAP_REF,
120 TOG_KEYMAP_HELP
121 };
123 enum tog_view_mode {
124 TOG_VIEW_SPLIT_NONE,
125 TOG_VIEW_SPLIT_VERT,
126 TOG_VIEW_SPLIT_HRZN
127 };
129 #define HSPLIT_SCALE 0.3f /* default horizontal split scale */
131 #define TOG_EOF_STRING "(END)"
133 struct commit_queue_entry {
134 TAILQ_ENTRY(commit_queue_entry) entry;
135 struct got_object_id *id;
136 struct got_commit_object *commit;
137 int idx;
138 };
139 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
140 struct commit_queue {
141 int ncommits;
142 struct commit_queue_head head;
143 };
145 struct tog_color {
146 STAILQ_ENTRY(tog_color) entry;
147 regex_t regex;
148 short colorpair;
149 };
150 STAILQ_HEAD(tog_colors, tog_color);
152 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
153 static struct got_reflist_object_id_map *tog_refs_idmap;
154 static struct {
155 struct got_object_id *id;
156 int idx;
157 char marker;
158 } tog_base_commit;
159 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
161 static const struct got_error *
162 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
163 struct got_reference* re2)
165 const char *name1 = got_ref_get_name(re1);
166 const char *name2 = got_ref_get_name(re2);
167 int isbackup1, isbackup2;
169 /* Sort backup refs towards the bottom of the list. */
170 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
171 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
172 if (!isbackup1 && isbackup2) {
173 *cmp = -1;
174 return NULL;
175 } else if (isbackup1 && !isbackup2) {
176 *cmp = 1;
177 return NULL;
180 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
181 return NULL;
184 static const struct got_error *
185 tog_load_refs(struct got_repository *repo, int sort_by_date)
187 const struct got_error *err;
189 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
190 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
191 repo);
192 if (err)
193 return err;
195 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
196 repo);
199 static void
200 tog_free_refs(void)
202 if (tog_refs_idmap) {
203 got_reflist_object_id_map_free(tog_refs_idmap);
204 tog_refs_idmap = NULL;
206 got_ref_list_free(&tog_refs);
209 static const struct got_error *
210 add_color(struct tog_colors *colors, const char *pattern,
211 int idx, short color)
213 const struct got_error *err = NULL;
214 struct tog_color *tc;
215 int regerr = 0;
217 if (idx < 1 || idx > COLOR_PAIRS - 1)
218 return NULL;
220 init_pair(idx, color, -1);
222 tc = calloc(1, sizeof(*tc));
223 if (tc == NULL)
224 return got_error_from_errno("calloc");
225 regerr = regcomp(&tc->regex, pattern,
226 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
227 if (regerr) {
228 static char regerr_msg[512];
229 static char err_msg[512];
230 regerror(regerr, &tc->regex, regerr_msg,
231 sizeof(regerr_msg));
232 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
233 regerr_msg);
234 err = got_error_msg(GOT_ERR_REGEX, err_msg);
235 free(tc);
236 return err;
238 tc->colorpair = idx;
239 STAILQ_INSERT_HEAD(colors, tc, entry);
240 return NULL;
243 static void
244 free_colors(struct tog_colors *colors)
246 struct tog_color *tc;
248 while (!STAILQ_EMPTY(colors)) {
249 tc = STAILQ_FIRST(colors);
250 STAILQ_REMOVE_HEAD(colors, entry);
251 regfree(&tc->regex);
252 free(tc);
256 static struct tog_color *
257 get_color(struct tog_colors *colors, int colorpair)
259 struct tog_color *tc = NULL;
261 STAILQ_FOREACH(tc, colors, entry) {
262 if (tc->colorpair == colorpair)
263 return tc;
266 return NULL;
269 static int
270 default_color_value(const char *envvar)
272 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
273 return COLOR_MAGENTA;
274 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
275 return COLOR_CYAN;
276 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
277 return COLOR_YELLOW;
278 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
279 return COLOR_GREEN;
280 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
281 return COLOR_MAGENTA;
282 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
283 return COLOR_MAGENTA;
284 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
285 return COLOR_CYAN;
286 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
287 return COLOR_GREEN;
288 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
289 return COLOR_GREEN;
290 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
291 return COLOR_CYAN;
292 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
293 return COLOR_YELLOW;
294 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
295 return COLOR_GREEN;
296 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
297 return COLOR_MAGENTA;
298 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
299 return COLOR_YELLOW;
300 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
301 return COLOR_CYAN;
303 return -1;
306 static int
307 get_color_value(const char *envvar)
309 const char *val = getenv(envvar);
311 if (val == NULL)
312 return default_color_value(envvar);
314 if (strcasecmp(val, "black") == 0)
315 return COLOR_BLACK;
316 if (strcasecmp(val, "red") == 0)
317 return COLOR_RED;
318 if (strcasecmp(val, "green") == 0)
319 return COLOR_GREEN;
320 if (strcasecmp(val, "yellow") == 0)
321 return COLOR_YELLOW;
322 if (strcasecmp(val, "blue") == 0)
323 return COLOR_BLUE;
324 if (strcasecmp(val, "magenta") == 0)
325 return COLOR_MAGENTA;
326 if (strcasecmp(val, "cyan") == 0)
327 return COLOR_CYAN;
328 if (strcasecmp(val, "white") == 0)
329 return COLOR_WHITE;
330 if (strcasecmp(val, "default") == 0)
331 return -1;
333 return default_color_value(envvar);
336 struct tog_diff_view_state {
337 struct got_object_id *id1, *id2;
338 const char *label1, *label2;
339 FILE *f, *f1, *f2;
340 int fd1, fd2;
341 int lineno;
342 int first_displayed_line;
343 int last_displayed_line;
344 int eof;
345 int diff_context;
346 int ignore_whitespace;
347 int force_text_diff;
348 struct got_repository *repo;
349 struct got_diff_line *lines;
350 size_t nlines;
351 int matched_line;
352 int selected_line;
354 /* passed from log or blame view; may be NULL */
355 struct tog_view *parent_view;
356 };
358 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
359 static volatile sig_atomic_t tog_thread_error;
361 struct tog_log_thread_args {
362 pthread_cond_t need_commits;
363 pthread_cond_t commit_loaded;
364 int commits_needed;
365 int load_all;
366 struct got_commit_graph *graph;
367 struct commit_queue *real_commits;
368 const char *in_repo_path;
369 struct got_object_id *start_id;
370 struct got_repository *repo;
371 int *pack_fds;
372 int log_complete;
373 pthread_cond_t log_loaded;
374 sig_atomic_t *quit;
375 struct commit_queue_entry **first_displayed_entry;
376 struct commit_queue_entry **selected_entry;
377 int *searching;
378 int *search_next_done;
379 regex_t *regex;
380 int *limiting;
381 int limit_match;
382 regex_t *limit_regex;
383 struct commit_queue *limit_commits;
384 struct got_worktree *worktree;
385 int need_commit_marker;
386 };
388 struct tog_log_view_state {
389 struct commit_queue *commits;
390 struct commit_queue_entry *first_displayed_entry;
391 struct commit_queue_entry *last_displayed_entry;
392 struct commit_queue_entry *selected_entry;
393 struct commit_queue real_commits;
394 int selected;
395 char *in_repo_path;
396 char *head_ref_name;
397 int log_branches;
398 struct got_repository *repo;
399 struct got_object_id *start_id;
400 sig_atomic_t quit;
401 pthread_t thread;
402 struct tog_log_thread_args thread_args;
403 struct commit_queue_entry *matched_entry;
404 struct commit_queue_entry *search_entry;
405 struct tog_colors colors;
406 int use_committer;
407 int limit_view;
408 regex_t limit_regex;
409 struct commit_queue limit_commits;
410 };
412 #define TOG_COLOR_DIFF_MINUS 1
413 #define TOG_COLOR_DIFF_PLUS 2
414 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
415 #define TOG_COLOR_DIFF_META 4
416 #define TOG_COLOR_TREE_SUBMODULE 5
417 #define TOG_COLOR_TREE_SYMLINK 6
418 #define TOG_COLOR_TREE_DIRECTORY 7
419 #define TOG_COLOR_TREE_EXECUTABLE 8
420 #define TOG_COLOR_COMMIT 9
421 #define TOG_COLOR_AUTHOR 10
422 #define TOG_COLOR_DATE 11
423 #define TOG_COLOR_REFS_HEADS 12
424 #define TOG_COLOR_REFS_TAGS 13
425 #define TOG_COLOR_REFS_REMOTES 14
426 #define TOG_COLOR_REFS_BACKUP 15
428 struct tog_blame_cb_args {
429 struct tog_blame_line *lines; /* one per line */
430 int nlines;
432 struct tog_view *view;
433 struct got_object_id *commit_id;
434 int *quit;
435 };
437 struct tog_blame_thread_args {
438 const char *path;
439 struct got_repository *repo;
440 struct tog_blame_cb_args *cb_args;
441 int *complete;
442 got_cancel_cb cancel_cb;
443 void *cancel_arg;
444 pthread_cond_t blame_complete;
445 };
447 struct tog_blame {
448 FILE *f;
449 off_t filesize;
450 struct tog_blame_line *lines;
451 int nlines;
452 off_t *line_offsets;
453 pthread_t thread;
454 struct tog_blame_thread_args thread_args;
455 struct tog_blame_cb_args cb_args;
456 const char *path;
457 int *pack_fds;
458 };
460 struct tog_blame_view_state {
461 int first_displayed_line;
462 int last_displayed_line;
463 int selected_line;
464 int last_diffed_line;
465 int blame_complete;
466 int eof;
467 int done;
468 struct got_object_id_queue blamed_commits;
469 struct got_object_qid *blamed_commit;
470 char *path;
471 struct got_repository *repo;
472 struct got_object_id *commit_id;
473 struct got_object_id *id_to_log;
474 struct tog_blame blame;
475 int matched_line;
476 struct tog_colors colors;
477 };
479 struct tog_parent_tree {
480 TAILQ_ENTRY(tog_parent_tree) entry;
481 struct got_tree_object *tree;
482 struct got_tree_entry *first_displayed_entry;
483 struct got_tree_entry *selected_entry;
484 int selected;
485 };
487 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
489 struct tog_tree_view_state {
490 char *tree_label;
491 struct got_object_id *commit_id;/* commit which this tree belongs to */
492 struct got_tree_object *root; /* the commit's root tree entry */
493 struct got_tree_object *tree; /* currently displayed (sub-)tree */
494 struct got_tree_entry *first_displayed_entry;
495 struct got_tree_entry *last_displayed_entry;
496 struct got_tree_entry *selected_entry;
497 int ndisplayed, selected, show_ids;
498 struct tog_parent_trees parents; /* parent trees of current sub-tree */
499 char *head_ref_name;
500 struct got_repository *repo;
501 struct got_tree_entry *matched_entry;
502 struct tog_colors colors;
503 };
505 struct tog_reflist_entry {
506 TAILQ_ENTRY(tog_reflist_entry) entry;
507 struct got_reference *ref;
508 int idx;
509 };
511 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
513 struct tog_ref_view_state {
514 struct tog_reflist_head refs;
515 struct tog_reflist_entry *first_displayed_entry;
516 struct tog_reflist_entry *last_displayed_entry;
517 struct tog_reflist_entry *selected_entry;
518 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
519 struct got_repository *repo;
520 struct tog_reflist_entry *matched_entry;
521 struct tog_colors colors;
522 };
524 struct tog_help_view_state {
525 FILE *f;
526 off_t *line_offsets;
527 size_t nlines;
528 int lineno;
529 int first_displayed_line;
530 int last_displayed_line;
531 int eof;
532 int matched_line;
533 int selected_line;
534 int all;
535 enum tog_keymap_type type;
536 };
538 #define GENERATE_HELP \
539 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
540 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
541 KEY_("k C-p Up", "Move cursor or page up one line"), \
542 KEY_("j C-n Down", "Move cursor or page down one line"), \
543 KEY_("C-b b PgUp", "Scroll the view up one page"), \
544 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
545 KEY_("C-u u", "Scroll the view up one half page"), \
546 KEY_("C-d d", "Scroll the view down one half page"), \
547 KEY_("g", "Go to line N (default: first line)"), \
548 KEY_("Home =", "Go to the first line"), \
549 KEY_("G", "Go to line N (default: last line)"), \
550 KEY_("End *", "Go to the last line"), \
551 KEY_("l Right", "Scroll the view right"), \
552 KEY_("h Left", "Scroll the view left"), \
553 KEY_("$", "Scroll view to the rightmost position"), \
554 KEY_("0", "Scroll view to the leftmost position"), \
555 KEY_("-", "Decrease size of the focussed split"), \
556 KEY_("+", "Increase size of the focussed split"), \
557 KEY_("Tab", "Switch focus between views"), \
558 KEY_("F", "Toggle fullscreen mode"), \
559 KEY_("S", "Switch split-screen layout"), \
560 KEY_("/", "Open prompt to enter search term"), \
561 KEY_("n", "Find next line/token matching the current search term"), \
562 KEY_("N", "Find previous line/token matching the current search term"),\
563 KEY_("q", "Quit the focussed view; Quit help screen"), \
564 KEY_("Q", "Quit tog"), \
566 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
567 KEY_("< ,", "Move cursor up one commit"), \
568 KEY_("> .", "Move cursor down one commit"), \
569 KEY_("Enter", "Open diff view of the selected commit"), \
570 KEY_("B", "Reload the log view and toggle display of merged commits"), \
571 KEY_("R", "Open ref view of all repository references"), \
572 KEY_("T", "Display tree view of the repository from the selected" \
573 " commit"), \
574 KEY_("@", "Toggle between displaying author and committer name"), \
575 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
576 KEY_("C-g Backspace", "Cancel current search or log operation"), \
577 KEY_("C-l", "Reload the log view with new commits in the repository"), \
579 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
580 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
581 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
582 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
583 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
584 " data"), \
585 KEY_("(", "Go to the previous file in the diff"), \
586 KEY_(")", "Go to the next file in the diff"), \
587 KEY_("{", "Go to the previous hunk in the diff"), \
588 KEY_("}", "Go to the next hunk in the diff"), \
589 KEY_("[", "Decrease the number of context lines"), \
590 KEY_("]", "Increase the number of context lines"), \
591 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
593 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
594 KEY_("Enter", "Display diff view of the selected line's commit"), \
595 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
596 KEY_("L", "Open log view for the currently selected annotated line"), \
597 KEY_("C", "Reload view with the previously blamed commit"), \
598 KEY_("c", "Reload view with the version of the file found in the" \
599 " selected line's commit"), \
600 KEY_("p", "Reload view with the version of the file found in the" \
601 " selected line's parent commit"), \
603 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
604 KEY_("Enter", "Enter selected directory or open blame view of the" \
605 " selected file"), \
606 KEY_("L", "Open log view for the selected entry"), \
607 KEY_("R", "Open ref view of all repository references"), \
608 KEY_("i", "Show object IDs for all tree entries"), \
609 KEY_("Backspace", "Return to the parent directory"), \
611 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
612 KEY_("Enter", "Display log view of the selected reference"), \
613 KEY_("T", "Display tree view of the selected reference"), \
614 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
615 KEY_("m", "Toggle display of last modified date for each reference"), \
616 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
617 KEY_("C-l", "Reload view with all repository references")
619 struct tog_key_map {
620 const char *keys;
621 const char *info;
622 enum tog_keymap_type type;
623 };
625 /* curses io for tog regress */
626 struct tog_io {
627 FILE *cin;
628 FILE *cout;
629 FILE *f;
630 FILE *sdump;
631 char *input_str;
632 int wait_for_ui;
633 } tog_io;
634 static int using_mock_io;
636 #define TOG_KEY_SCRDUMP SHRT_MIN
638 /*
639 * We implement two types of views: parent views and child views.
641 * The 'Tab' key switches focus between a parent view and its child view.
642 * Child views are shown side-by-side to their parent view, provided
643 * there is enough screen estate.
645 * When a new view is opened from within a parent view, this new view
646 * becomes a child view of the parent view, replacing any existing child.
648 * When a new view is opened from within a child view, this new view
649 * becomes a parent view which will obscure the views below until the
650 * user quits the new parent view by typing 'q'.
652 * This list of views contains parent views only.
653 * Child views are only pointed to by their parent view.
654 */
655 TAILQ_HEAD(tog_view_list_head, tog_view);
657 struct tog_view {
658 TAILQ_ENTRY(tog_view) entry;
659 WINDOW *window;
660 PANEL *panel;
661 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
662 int resized_y, resized_x; /* begin_y/x based on user resizing */
663 int maxx, x; /* max column and current start column */
664 int lines, cols; /* copies of LINES and COLS */
665 int nscrolled, offset; /* lines scrolled and hsplit line offset */
666 int gline, hiline; /* navigate to and highlight this nG line */
667 int ch, count; /* current keymap and count prefix */
668 int resized; /* set when in a resize event */
669 int focussed; /* Only set on one parent or child view at a time. */
670 int dying;
671 struct tog_view *parent;
672 struct tog_view *child;
674 /*
675 * This flag is initially set on parent views when a new child view
676 * is created. It gets toggled when the 'Tab' key switches focus
677 * between parent and child.
678 * The flag indicates whether focus should be passed on to our child
679 * view if this parent view gets picked for focus after another parent
680 * view was closed. This prevents child views from losing focus in such
681 * situations.
682 */
683 int focus_child;
685 enum tog_view_mode mode;
686 /* type-specific state */
687 enum tog_view_type type;
688 union {
689 struct tog_diff_view_state diff;
690 struct tog_log_view_state log;
691 struct tog_blame_view_state blame;
692 struct tog_tree_view_state tree;
693 struct tog_ref_view_state ref;
694 struct tog_help_view_state help;
695 } state;
697 const struct got_error *(*show)(struct tog_view *);
698 const struct got_error *(*input)(struct tog_view **,
699 struct tog_view *, int);
700 const struct got_error *(*reset)(struct tog_view *);
701 const struct got_error *(*resize)(struct tog_view *, int);
702 const struct got_error *(*close)(struct tog_view *);
704 const struct got_error *(*search_start)(struct tog_view *);
705 const struct got_error *(*search_next)(struct tog_view *);
706 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
707 int **, int **, int **, int **);
708 int search_started;
709 int searching;
710 #define TOG_SEARCH_FORWARD 1
711 #define TOG_SEARCH_BACKWARD 2
712 int search_next_done;
713 #define TOG_SEARCH_HAVE_MORE 1
714 #define TOG_SEARCH_NO_MORE 2
715 #define TOG_SEARCH_HAVE_NONE 3
716 regex_t regex;
717 regmatch_t regmatch;
718 const char *action;
719 };
721 static const struct got_error *open_diff_view(struct tog_view *,
722 struct got_object_id *, struct got_object_id *,
723 const char *, const char *, int, int, int, struct tog_view *,
724 struct got_repository *);
725 static const struct got_error *show_diff_view(struct tog_view *);
726 static const struct got_error *input_diff_view(struct tog_view **,
727 struct tog_view *, int);
728 static const struct got_error *reset_diff_view(struct tog_view *);
729 static const struct got_error* close_diff_view(struct tog_view *);
730 static const struct got_error *search_start_diff_view(struct tog_view *);
731 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
732 size_t *, int **, int **, int **, int **);
733 static const struct got_error *search_next_view_match(struct tog_view *);
735 static const struct got_error *open_log_view(struct tog_view *,
736 struct got_object_id *, struct got_repository *,
737 const char *, const char *, int, struct got_worktree *);
738 static const struct got_error * show_log_view(struct tog_view *);
739 static const struct got_error *input_log_view(struct tog_view **,
740 struct tog_view *, int);
741 static const struct got_error *resize_log_view(struct tog_view *, int);
742 static const struct got_error *close_log_view(struct tog_view *);
743 static const struct got_error *search_start_log_view(struct tog_view *);
744 static const struct got_error *search_next_log_view(struct tog_view *);
746 static const struct got_error *open_blame_view(struct tog_view *, char *,
747 struct got_object_id *, struct got_repository *);
748 static const struct got_error *show_blame_view(struct tog_view *);
749 static const struct got_error *input_blame_view(struct tog_view **,
750 struct tog_view *, int);
751 static const struct got_error *reset_blame_view(struct tog_view *);
752 static const struct got_error *close_blame_view(struct tog_view *);
753 static const struct got_error *search_start_blame_view(struct tog_view *);
754 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
755 size_t *, int **, int **, int **, int **);
757 static const struct got_error *open_tree_view(struct tog_view *,
758 struct got_object_id *, const char *, struct got_repository *);
759 static const struct got_error *show_tree_view(struct tog_view *);
760 static const struct got_error *input_tree_view(struct tog_view **,
761 struct tog_view *, int);
762 static const struct got_error *close_tree_view(struct tog_view *);
763 static const struct got_error *search_start_tree_view(struct tog_view *);
764 static const struct got_error *search_next_tree_view(struct tog_view *);
766 static const struct got_error *open_ref_view(struct tog_view *,
767 struct got_repository *);
768 static const struct got_error *show_ref_view(struct tog_view *);
769 static const struct got_error *input_ref_view(struct tog_view **,
770 struct tog_view *, int);
771 static const struct got_error *close_ref_view(struct tog_view *);
772 static const struct got_error *search_start_ref_view(struct tog_view *);
773 static const struct got_error *search_next_ref_view(struct tog_view *);
775 static const struct got_error *open_help_view(struct tog_view *,
776 struct tog_view *);
777 static const struct got_error *show_help_view(struct tog_view *);
778 static const struct got_error *input_help_view(struct tog_view **,
779 struct tog_view *, int);
780 static const struct got_error *reset_help_view(struct tog_view *);
781 static const struct got_error* close_help_view(struct tog_view *);
782 static const struct got_error *search_start_help_view(struct tog_view *);
783 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
784 size_t *, int **, int **, int **, int **);
786 static volatile sig_atomic_t tog_sigwinch_received;
787 static volatile sig_atomic_t tog_sigpipe_received;
788 static volatile sig_atomic_t tog_sigcont_received;
789 static volatile sig_atomic_t tog_sigint_received;
790 static volatile sig_atomic_t tog_sigterm_received;
792 static void
793 tog_sigwinch(int signo)
795 tog_sigwinch_received = 1;
798 static void
799 tog_sigpipe(int signo)
801 tog_sigpipe_received = 1;
804 static void
805 tog_sigcont(int signo)
807 tog_sigcont_received = 1;
810 static void
811 tog_sigint(int signo)
813 tog_sigint_received = 1;
816 static void
817 tog_sigterm(int signo)
819 tog_sigterm_received = 1;
822 static int
823 tog_fatal_signal_received(void)
825 return (tog_sigpipe_received ||
826 tog_sigint_received || tog_sigterm_received);
829 static const struct got_error *
830 view_close(struct tog_view *view)
832 const struct got_error *err = NULL, *child_err = NULL;
834 if (view->child) {
835 child_err = view_close(view->child);
836 view->child = NULL;
838 if (view->close)
839 err = view->close(view);
840 if (view->panel)
841 del_panel(view->panel);
842 if (view->window)
843 delwin(view->window);
844 free(view);
845 return err ? err : child_err;
848 static struct tog_view *
849 view_open(int nlines, int ncols, int begin_y, int begin_x,
850 enum tog_view_type type)
852 struct tog_view *view = calloc(1, sizeof(*view));
854 if (view == NULL)
855 return NULL;
857 view->type = type;
858 view->lines = LINES;
859 view->cols = COLS;
860 view->nlines = nlines ? nlines : LINES - begin_y;
861 view->ncols = ncols ? ncols : COLS - begin_x;
862 view->begin_y = begin_y;
863 view->begin_x = begin_x;
864 view->window = newwin(nlines, ncols, begin_y, begin_x);
865 if (view->window == NULL) {
866 view_close(view);
867 return NULL;
869 view->panel = new_panel(view->window);
870 if (view->panel == NULL ||
871 set_panel_userptr(view->panel, view) != OK) {
872 view_close(view);
873 return NULL;
876 keypad(view->window, TRUE);
877 return view;
880 static int
881 view_split_begin_x(int begin_x)
883 if (begin_x > 0 || COLS < 120)
884 return 0;
885 return (COLS - MAX(COLS / 2, 80));
888 /* XXX Stub till we decide what to do. */
889 static int
890 view_split_begin_y(int lines)
892 return lines * HSPLIT_SCALE;
895 static const struct got_error *view_resize(struct tog_view *);
897 static const struct got_error *
898 view_splitscreen(struct tog_view *view)
900 const struct got_error *err = NULL;
902 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
903 if (view->resized_y && view->resized_y < view->lines)
904 view->begin_y = view->resized_y;
905 else
906 view->begin_y = view_split_begin_y(view->nlines);
907 view->begin_x = 0;
908 } else if (!view->resized) {
909 if (view->resized_x && view->resized_x < view->cols - 1 &&
910 view->cols > 119)
911 view->begin_x = view->resized_x;
912 else
913 view->begin_x = view_split_begin_x(0);
914 view->begin_y = 0;
916 view->nlines = LINES - view->begin_y;
917 view->ncols = COLS - view->begin_x;
918 view->lines = LINES;
919 view->cols = COLS;
920 err = view_resize(view);
921 if (err)
922 return err;
924 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
925 view->parent->nlines = view->begin_y;
927 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
928 return got_error_from_errno("mvwin");
930 return NULL;
933 static const struct got_error *
934 view_fullscreen(struct tog_view *view)
936 const struct got_error *err = NULL;
938 view->begin_x = 0;
939 view->begin_y = view->resized ? view->begin_y : 0;
940 view->nlines = view->resized ? view->nlines : LINES;
941 view->ncols = COLS;
942 view->lines = LINES;
943 view->cols = COLS;
944 err = view_resize(view);
945 if (err)
946 return err;
948 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
949 return got_error_from_errno("mvwin");
951 return NULL;
954 static int
955 view_is_parent_view(struct tog_view *view)
957 return view->parent == NULL;
960 static int
961 view_is_splitscreen(struct tog_view *view)
963 return view->begin_x > 0 || view->begin_y > 0;
966 static int
967 view_is_fullscreen(struct tog_view *view)
969 return view->nlines == LINES && view->ncols == COLS;
972 static int
973 view_is_hsplit_top(struct tog_view *view)
975 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
976 view_is_splitscreen(view->child);
979 static void
980 view_border(struct tog_view *view)
982 PANEL *panel;
983 const struct tog_view *view_above;
985 if (view->parent)
986 return view_border(view->parent);
988 panel = panel_above(view->panel);
989 if (panel == NULL)
990 return;
992 view_above = panel_userptr(panel);
993 if (view->mode == TOG_VIEW_SPLIT_HRZN)
994 mvwhline(view->window, view_above->begin_y - 1,
995 view->begin_x, ACS_HLINE, view->ncols);
996 else
997 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
998 ACS_VLINE, view->nlines);
1001 static const struct got_error *view_init_hsplit(struct tog_view *, int);
1002 static const struct got_error *request_log_commits(struct tog_view *);
1003 static const struct got_error *offset_selection_down(struct tog_view *);
1004 static void offset_selection_up(struct tog_view *);
1005 static void view_get_split(struct tog_view *, int *, int *);
1007 static const struct got_error *
1008 view_resize(struct tog_view *view)
1010 const struct got_error *err = NULL;
1011 int dif, nlines, ncols;
1013 dif = LINES - view->lines; /* line difference */
1015 if (view->lines > LINES)
1016 nlines = view->nlines - (view->lines - LINES);
1017 else
1018 nlines = view->nlines + (LINES - view->lines);
1019 if (view->cols > COLS)
1020 ncols = view->ncols - (view->cols - COLS);
1021 else
1022 ncols = view->ncols + (COLS - view->cols);
1024 if (view->child) {
1025 int hs = view->child->begin_y;
1027 if (!view_is_fullscreen(view))
1028 view->child->begin_x = view_split_begin_x(view->begin_x);
1029 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1030 view->child->begin_x == 0) {
1031 ncols = COLS;
1033 view_fullscreen(view->child);
1034 if (view->child->focussed)
1035 show_panel(view->child->panel);
1036 else
1037 show_panel(view->panel);
1038 } else {
1039 ncols = view->child->begin_x;
1041 view_splitscreen(view->child);
1042 show_panel(view->child->panel);
1045 * XXX This is ugly and needs to be moved into the above
1046 * logic but "works" for now and my attempts at moving it
1047 * break either 'tab' or 'F' key maps in horizontal splits.
1049 if (hs) {
1050 err = view_splitscreen(view->child);
1051 if (err)
1052 return err;
1053 if (dif < 0) { /* top split decreased */
1054 err = offset_selection_down(view);
1055 if (err)
1056 return err;
1058 view_border(view);
1059 update_panels();
1060 doupdate();
1061 show_panel(view->child->panel);
1062 nlines = view->nlines;
1064 } else if (view->parent == NULL)
1065 ncols = COLS;
1067 if (view->resize && dif > 0) {
1068 err = view->resize(view, dif);
1069 if (err)
1070 return err;
1073 if (wresize(view->window, nlines, ncols) == ERR)
1074 return got_error_from_errno("wresize");
1075 if (replace_panel(view->panel, view->window) == ERR)
1076 return got_error_from_errno("replace_panel");
1077 wclear(view->window);
1079 view->nlines = nlines;
1080 view->ncols = ncols;
1081 view->lines = LINES;
1082 view->cols = COLS;
1084 return NULL;
1087 static const struct got_error *
1088 resize_log_view(struct tog_view *view, int increase)
1090 struct tog_log_view_state *s = &view->state.log;
1091 const struct got_error *err = NULL;
1092 int n = 0;
1094 if (s->selected_entry)
1095 n = s->selected_entry->idx + view->lines - s->selected;
1098 * Request commits to account for the increased
1099 * height so we have enough to populate the view.
1101 if (s->commits->ncommits < n) {
1102 view->nscrolled = n - s->commits->ncommits + increase + 1;
1103 err = request_log_commits(view);
1106 return err;
1109 static void
1110 view_adjust_offset(struct tog_view *view, int n)
1112 if (n == 0)
1113 return;
1115 if (view->parent && view->parent->offset) {
1116 if (view->parent->offset + n >= 0)
1117 view->parent->offset += n;
1118 else
1119 view->parent->offset = 0;
1120 } else if (view->offset) {
1121 if (view->offset - n >= 0)
1122 view->offset -= n;
1123 else
1124 view->offset = 0;
1128 static const struct got_error *
1129 view_resize_split(struct tog_view *view, int resize)
1131 const struct got_error *err = NULL;
1132 struct tog_view *v = NULL;
1134 if (view->parent)
1135 v = view->parent;
1136 else
1137 v = view;
1139 if (!v->child || !view_is_splitscreen(v->child))
1140 return NULL;
1142 v->resized = v->child->resized = resize; /* lock for resize event */
1144 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1145 if (v->child->resized_y)
1146 v->child->begin_y = v->child->resized_y;
1147 if (view->parent)
1148 v->child->begin_y -= resize;
1149 else
1150 v->child->begin_y += resize;
1151 if (v->child->begin_y < 3) {
1152 view->count = 0;
1153 v->child->begin_y = 3;
1154 } else if (v->child->begin_y > LINES - 1) {
1155 view->count = 0;
1156 v->child->begin_y = LINES - 1;
1158 v->ncols = COLS;
1159 v->child->ncols = COLS;
1160 view_adjust_offset(view, resize);
1161 err = view_init_hsplit(v, v->child->begin_y);
1162 if (err)
1163 return err;
1164 v->child->resized_y = v->child->begin_y;
1165 } else {
1166 if (v->child->resized_x)
1167 v->child->begin_x = v->child->resized_x;
1168 if (view->parent)
1169 v->child->begin_x -= resize;
1170 else
1171 v->child->begin_x += resize;
1172 if (v->child->begin_x < 11) {
1173 view->count = 0;
1174 v->child->begin_x = 11;
1175 } else if (v->child->begin_x > COLS - 1) {
1176 view->count = 0;
1177 v->child->begin_x = COLS - 1;
1179 v->child->resized_x = v->child->begin_x;
1182 v->child->mode = v->mode;
1183 v->child->nlines = v->lines - v->child->begin_y;
1184 v->child->ncols = v->cols - v->child->begin_x;
1185 v->focus_child = 1;
1187 err = view_fullscreen(v);
1188 if (err)
1189 return err;
1190 err = view_splitscreen(v->child);
1191 if (err)
1192 return err;
1194 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1195 err = offset_selection_down(v->child);
1196 if (err)
1197 return err;
1200 if (v->resize)
1201 err = v->resize(v, 0);
1202 else if (v->child->resize)
1203 err = v->child->resize(v->child, 0);
1205 v->resized = v->child->resized = 0;
1207 return err;
1210 static void
1211 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1213 struct tog_view *v = src->child ? src->child : src;
1215 dst->resized_x = v->resized_x;
1216 dst->resized_y = v->resized_y;
1219 static const struct got_error *
1220 view_close_child(struct tog_view *view)
1222 const struct got_error *err = NULL;
1224 if (view->child == NULL)
1225 return NULL;
1227 err = view_close(view->child);
1228 view->child = NULL;
1229 return err;
1232 static const struct got_error *
1233 view_set_child(struct tog_view *view, struct tog_view *child)
1235 const struct got_error *err = NULL;
1237 view->child = child;
1238 child->parent = view;
1240 err = view_resize(view);
1241 if (err)
1242 return err;
1244 if (view->child->resized_x || view->child->resized_y)
1245 err = view_resize_split(view, 0);
1247 return err;
1250 static const struct got_error *view_dispatch_request(struct tog_view **,
1251 struct tog_view *, enum tog_view_type, int, int);
1253 static const struct got_error *
1254 view_request_new(struct tog_view **requested, struct tog_view *view,
1255 enum tog_view_type request)
1257 struct tog_view *new_view = NULL;
1258 const struct got_error *err;
1259 int y = 0, x = 0;
1261 *requested = NULL;
1263 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1264 view_get_split(view, &y, &x);
1266 err = view_dispatch_request(&new_view, view, request, y, x);
1267 if (err)
1268 return err;
1270 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1271 request != TOG_VIEW_HELP) {
1272 err = view_init_hsplit(view, y);
1273 if (err)
1274 return err;
1277 view->focussed = 0;
1278 new_view->focussed = 1;
1279 new_view->mode = view->mode;
1280 new_view->nlines = request == TOG_VIEW_HELP ?
1281 view->lines : view->lines - y;
1283 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1284 view_transfer_size(new_view, view);
1285 err = view_close_child(view);
1286 if (err)
1287 return err;
1288 err = view_set_child(view, new_view);
1289 if (err)
1290 return err;
1291 view->focus_child = 1;
1292 } else
1293 *requested = new_view;
1295 return NULL;
1298 static void
1299 tog_resizeterm(void)
1301 int cols, lines;
1302 struct winsize size;
1304 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1305 cols = 80; /* Default */
1306 lines = 24;
1307 } else {
1308 cols = size.ws_col;
1309 lines = size.ws_row;
1311 resize_term(lines, cols);
1314 static const struct got_error *
1315 view_search_start(struct tog_view *view, int fast_refresh)
1317 const struct got_error *err = NULL;
1318 struct tog_view *v = view;
1319 char pattern[1024];
1320 int ret;
1322 if (view->search_started) {
1323 regfree(&view->regex);
1324 view->searching = 0;
1325 memset(&view->regmatch, 0, sizeof(view->regmatch));
1327 view->search_started = 0;
1329 if (view->nlines < 1)
1330 return NULL;
1332 if (view_is_hsplit_top(view))
1333 v = view->child;
1334 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1335 v = view->parent;
1337 if (tog_io.input_str != NULL) {
1338 if (strlcpy(pattern, tog_io.input_str, sizeof(pattern)) >=
1339 sizeof(pattern))
1340 return got_error(GOT_ERR_NO_SPACE);
1341 } else {
1342 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1343 wclrtoeol(v->window);
1344 nodelay(v->window, FALSE); /* block for search term input */
1345 nocbreak();
1346 echo();
1347 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1348 wrefresh(v->window);
1349 cbreak();
1350 noecho();
1351 nodelay(v->window, TRUE);
1352 if (!fast_refresh && !using_mock_io)
1353 halfdelay(10);
1354 if (ret == ERR)
1355 return NULL;
1358 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1359 err = view->search_start(view);
1360 if (err) {
1361 regfree(&view->regex);
1362 return err;
1364 view->search_started = 1;
1365 view->searching = TOG_SEARCH_FORWARD;
1366 view->search_next_done = 0;
1367 view->search_next(view);
1370 return NULL;
1373 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1374 static const struct got_error *
1375 switch_split(struct tog_view *view)
1377 const struct got_error *err = NULL;
1378 struct tog_view *v = NULL;
1380 if (view->parent)
1381 v = view->parent;
1382 else
1383 v = view;
1385 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1386 v->mode = TOG_VIEW_SPLIT_VERT;
1387 else
1388 v->mode = TOG_VIEW_SPLIT_HRZN;
1390 if (!v->child)
1391 return NULL;
1392 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1393 v->mode = TOG_VIEW_SPLIT_NONE;
1395 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1396 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1397 v->child->begin_y = v->child->resized_y;
1398 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1399 v->child->begin_x = v->child->resized_x;
1402 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1403 v->ncols = COLS;
1404 v->child->ncols = COLS;
1405 v->child->nscrolled = LINES - v->child->nlines;
1407 err = view_init_hsplit(v, v->child->begin_y);
1408 if (err)
1409 return err;
1411 v->child->mode = v->mode;
1412 v->child->nlines = v->lines - v->child->begin_y;
1413 v->focus_child = 1;
1415 err = view_fullscreen(v);
1416 if (err)
1417 return err;
1418 err = view_splitscreen(v->child);
1419 if (err)
1420 return err;
1422 if (v->mode == TOG_VIEW_SPLIT_NONE)
1423 v->mode = TOG_VIEW_SPLIT_VERT;
1424 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1425 err = offset_selection_down(v);
1426 if (err)
1427 return err;
1428 err = offset_selection_down(v->child);
1429 if (err)
1430 return err;
1431 } else {
1432 offset_selection_up(v);
1433 offset_selection_up(v->child);
1435 if (v->resize)
1436 err = v->resize(v, 0);
1437 else if (v->child->resize)
1438 err = v->child->resize(v->child, 0);
1440 return err;
1444 * Strip trailing whitespace from str starting at byte *n;
1445 * if *n < 0, use strlen(str). Return new str length in *n.
1447 static void
1448 strip_trailing_ws(char *str, int *n)
1450 size_t x = *n;
1452 if (str == NULL || *str == '\0')
1453 return;
1455 if (x < 0)
1456 x = strlen(str);
1458 while (x-- > 0 && isspace((unsigned char)str[x]))
1459 str[x] = '\0';
1461 *n = x + 1;
1465 * Extract visible substring of line y from the curses screen
1466 * and strip trailing whitespace. If vline is set, overwrite
1467 * line[vline] with '|' because the ACS_VLINE character is
1468 * written out as 'x'. Write the line to file f.
1470 static const struct got_error *
1471 view_write_line(FILE *f, int y, int vline)
1473 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1474 int r, w;
1476 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1477 if (r == ERR)
1478 return got_error_fmt(GOT_ERR_RANGE,
1479 "failed to extract line %d", y);
1482 * In some views, lines are padded with blanks to COLS width.
1483 * Strip them so we can diff without the -b flag when testing.
1485 strip_trailing_ws(line, &r);
1487 if (vline > 0)
1488 line[vline] = '|';
1490 w = fprintf(f, "%s\n", line);
1491 if (w != r + 1) /* \n */
1492 return got_ferror(f, GOT_ERR_IO);
1494 return NULL;
1498 * Capture the visible curses screen by writing each line to the
1499 * file at the path set via the TOG_SCR_DUMP environment variable.
1501 static const struct got_error *
1502 screendump(struct tog_view *view)
1504 const struct got_error *err;
1505 int i;
1507 err = got_opentemp_truncate(tog_io.sdump);
1508 if (err)
1509 return err;
1511 if ((view->child && view->child->begin_x) ||
1512 (view->parent && view->begin_x)) {
1513 int ncols = view->child ? view->ncols : view->parent->ncols;
1515 /* vertical splitscreen */
1516 for (i = 0; i < view->nlines; ++i) {
1517 err = view_write_line(tog_io.sdump, i, ncols - 1);
1518 if (err)
1519 goto done;
1521 } else {
1522 int hline = 0;
1524 /* fullscreen or horizontal splitscreen */
1525 if ((view->child && view->child->begin_y) ||
1526 (view->parent && view->begin_y)) /* hsplit */
1527 hline = view->child ?
1528 view->child->begin_y : view->begin_y;
1530 for (i = 0; i < view->lines; i++) {
1531 if (hline && i == hline - 1) {
1532 int c;
1534 /* ACS_HLINE writes out as 'q', overwrite it */
1535 for (c = 0; c < view->cols; ++c)
1536 fputc('-', tog_io.sdump);
1537 fputc('\n', tog_io.sdump);
1538 continue;
1541 err = view_write_line(tog_io.sdump, i, 0);
1542 if (err)
1543 goto done;
1547 done:
1548 return err;
1552 * Compute view->count from numeric input. Assign total to view->count and
1553 * return first non-numeric key entered.
1555 static int
1556 get_compound_key(struct tog_view *view, int c)
1558 struct tog_view *v = view;
1559 int x, n = 0;
1561 if (view_is_hsplit_top(view))
1562 v = view->child;
1563 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1564 v = view->parent;
1566 view->count = 0;
1567 cbreak(); /* block for input */
1568 nodelay(view->window, FALSE);
1569 wmove(v->window, v->nlines - 1, 0);
1570 wclrtoeol(v->window);
1571 waddch(v->window, ':');
1573 do {
1574 x = getcurx(v->window);
1575 if (x != ERR && x < view->ncols) {
1576 waddch(v->window, c);
1577 wrefresh(v->window);
1581 * Don't overflow. Max valid request should be the greatest
1582 * between the longest and total lines; cap at 10 million.
1584 if (n >= 9999999)
1585 n = 9999999;
1586 else
1587 n = n * 10 + (c - '0');
1588 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1590 if (c == 'G' || c == 'g') { /* nG key map */
1591 view->gline = view->hiline = n;
1592 n = 0;
1593 c = 0;
1596 /* Massage excessive or inapplicable values at the input handler. */
1597 view->count = n;
1599 return c;
1602 static void
1603 action_report(struct tog_view *view)
1605 struct tog_view *v = view;
1607 if (view_is_hsplit_top(view))
1608 v = view->child;
1609 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1610 v = view->parent;
1612 wmove(v->window, v->nlines - 1, 0);
1613 wclrtoeol(v->window);
1614 wprintw(v->window, ":%s", view->action);
1615 wrefresh(v->window);
1618 * Clear action status report. Only clear in blame view
1619 * once annotating is complete, otherwise it's too fast.
1621 if (view->type == TOG_VIEW_BLAME) {
1622 if (view->state.blame.blame_complete)
1623 view->action = NULL;
1624 } else
1625 view->action = NULL;
1629 * Read the next line from the test script and assign
1630 * key instruction to *ch. If at EOF, set the *done flag.
1632 static const struct got_error *
1633 tog_read_script_key(FILE *script, struct tog_view *view, int *ch, int *done)
1635 const struct got_error *err = NULL;
1636 char *line = NULL;
1637 size_t linesz = 0;
1638 ssize_t n;
1641 if (view->count && --view->count) {
1642 *ch = view->ch;
1643 return NULL;
1644 } else
1645 *ch = -1;
1647 if ((n = getline(&line, &linesz, script)) == -1) {
1648 if (feof(script)) {
1649 *done = 1;
1650 goto done;
1651 } else {
1652 err = got_ferror(script, GOT_ERR_IO);
1653 goto done;
1657 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1658 tog_io.wait_for_ui = 1;
1659 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1660 *ch = KEY_ENTER;
1661 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1662 *ch = KEY_RIGHT;
1663 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1664 *ch = KEY_LEFT;
1665 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1666 *ch = KEY_DOWN;
1667 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1668 *ch = KEY_UP;
1669 else if (strncasecmp(line, "TAB", 3) == 0)
1670 *ch = '\t';
1671 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1672 *ch = TOG_KEY_SCRDUMP;
1673 else if (isdigit((unsigned char)*line)) {
1674 char *t = line;
1676 while (isdigit((unsigned char)*t))
1677 ++t;
1678 view->ch = *ch = *t;
1679 *t = '\0';
1680 /* ignore error, view->count is 0 if instruction is invalid */
1681 view->count = strtonum(line, 0, INT_MAX, NULL);
1682 } else {
1683 *ch = *line;
1684 if (n > 2 && (*ch == '/' || *ch == '&')) {
1685 /* skip leading keymap and trim trailing newline */
1686 tog_io.input_str = strndup(line + 1, n - 2);
1687 if (tog_io.input_str == NULL) {
1688 err = got_error_from_errno("strndup");
1689 goto done;
1694 done:
1695 free(line);
1696 return err;
1699 static const struct got_error *
1700 view_input(struct tog_view **new, int *done, struct tog_view *view,
1701 struct tog_view_list_head *views, int fast_refresh)
1703 const struct got_error *err = NULL;
1704 struct tog_view *v;
1705 int ch, errcode;
1707 *new = NULL;
1709 if (view->action)
1710 action_report(view);
1712 /* Clear "no matches" indicator. */
1713 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1714 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1715 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1716 view->count = 0;
1719 if (view->searching && !view->search_next_done) {
1720 errcode = pthread_mutex_unlock(&tog_mutex);
1721 if (errcode)
1722 return got_error_set_errno(errcode,
1723 "pthread_mutex_unlock");
1724 sched_yield();
1725 errcode = pthread_mutex_lock(&tog_mutex);
1726 if (errcode)
1727 return got_error_set_errno(errcode,
1728 "pthread_mutex_lock");
1729 view->search_next(view);
1730 return NULL;
1733 /* Allow threads to make progress while we are waiting for input. */
1734 errcode = pthread_mutex_unlock(&tog_mutex);
1735 if (errcode)
1736 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1738 if (using_mock_io) {
1739 err = tog_read_script_key(tog_io.f, view, &ch, done);
1740 if (err) {
1741 errcode = pthread_mutex_lock(&tog_mutex);
1742 return err;
1744 } else if (view->count && --view->count) {
1745 cbreak();
1746 nodelay(view->window, TRUE);
1747 ch = wgetch(view->window);
1748 /* let C-g or backspace abort unfinished count */
1749 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1750 view->count = 0;
1751 else
1752 ch = view->ch;
1753 } else {
1754 ch = wgetch(view->window);
1755 if (ch >= '1' && ch <= '9')
1756 view->ch = ch = get_compound_key(view, ch);
1758 if (view->hiline && ch != ERR && ch != 0)
1759 view->hiline = 0; /* key pressed, clear line highlight */
1760 nodelay(view->window, TRUE);
1761 errcode = pthread_mutex_lock(&tog_mutex);
1762 if (errcode)
1763 return got_error_set_errno(errcode, "pthread_mutex_lock");
1765 if (tog_sigwinch_received || tog_sigcont_received) {
1766 tog_resizeterm();
1767 tog_sigwinch_received = 0;
1768 tog_sigcont_received = 0;
1769 TAILQ_FOREACH(v, views, entry) {
1770 err = view_resize(v);
1771 if (err)
1772 return err;
1773 err = v->input(new, v, KEY_RESIZE);
1774 if (err)
1775 return err;
1776 if (v->child) {
1777 err = view_resize(v->child);
1778 if (err)
1779 return err;
1780 err = v->child->input(new, v->child,
1781 KEY_RESIZE);
1782 if (err)
1783 return err;
1784 if (v->child->resized_x || v->child->resized_y) {
1785 err = view_resize_split(v, 0);
1786 if (err)
1787 return err;
1793 switch (ch) {
1794 case '?':
1795 case 'H':
1796 case KEY_F(1):
1797 if (view->type == TOG_VIEW_HELP)
1798 err = view->reset(view);
1799 else
1800 err = view_request_new(new, view, TOG_VIEW_HELP);
1801 break;
1802 case '\t':
1803 view->count = 0;
1804 if (view->child) {
1805 view->focussed = 0;
1806 view->child->focussed = 1;
1807 view->focus_child = 1;
1808 } else if (view->parent) {
1809 view->focussed = 0;
1810 view->parent->focussed = 1;
1811 view->parent->focus_child = 0;
1812 if (!view_is_splitscreen(view)) {
1813 if (view->parent->resize) {
1814 err = view->parent->resize(view->parent,
1815 0);
1816 if (err)
1817 return err;
1819 offset_selection_up(view->parent);
1820 err = view_fullscreen(view->parent);
1821 if (err)
1822 return err;
1825 break;
1826 case 'q':
1827 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1828 if (view->parent->resize) {
1829 /* might need more commits to fill fullscreen */
1830 err = view->parent->resize(view->parent, 0);
1831 if (err)
1832 break;
1834 offset_selection_up(view->parent);
1836 err = view->input(new, view, ch);
1837 view->dying = 1;
1838 break;
1839 case 'Q':
1840 *done = 1;
1841 break;
1842 case 'F':
1843 view->count = 0;
1844 if (view_is_parent_view(view)) {
1845 if (view->child == NULL)
1846 break;
1847 if (view_is_splitscreen(view->child)) {
1848 view->focussed = 0;
1849 view->child->focussed = 1;
1850 err = view_fullscreen(view->child);
1851 } else {
1852 err = view_splitscreen(view->child);
1853 if (!err)
1854 err = view_resize_split(view, 0);
1856 if (err)
1857 break;
1858 err = view->child->input(new, view->child,
1859 KEY_RESIZE);
1860 } else {
1861 if (view_is_splitscreen(view)) {
1862 view->parent->focussed = 0;
1863 view->focussed = 1;
1864 err = view_fullscreen(view);
1865 } else {
1866 err = view_splitscreen(view);
1867 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1868 err = view_resize(view->parent);
1869 if (!err)
1870 err = view_resize_split(view, 0);
1872 if (err)
1873 break;
1874 err = view->input(new, view, KEY_RESIZE);
1876 if (err)
1877 break;
1878 if (view->resize) {
1879 err = view->resize(view, 0);
1880 if (err)
1881 break;
1883 if (view->parent) {
1884 if (view->parent->resize) {
1885 err = view->parent->resize(view->parent, 0);
1886 if (err != NULL)
1887 break;
1889 err = offset_selection_down(view->parent);
1890 if (err != NULL)
1891 break;
1893 err = offset_selection_down(view);
1894 break;
1895 case 'S':
1896 view->count = 0;
1897 err = switch_split(view);
1898 break;
1899 case '-':
1900 err = view_resize_split(view, -1);
1901 break;
1902 case '+':
1903 err = view_resize_split(view, 1);
1904 break;
1905 case KEY_RESIZE:
1906 break;
1907 case '/':
1908 view->count = 0;
1909 if (view->search_start)
1910 view_search_start(view, fast_refresh);
1911 else
1912 err = view->input(new, view, ch);
1913 break;
1914 case 'N':
1915 case 'n':
1916 if (view->search_started && view->search_next) {
1917 view->searching = (ch == 'n' ?
1918 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1919 view->search_next_done = 0;
1920 view->search_next(view);
1921 } else
1922 err = view->input(new, view, ch);
1923 break;
1924 case 'A':
1925 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1926 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1927 view->action = "Patience diff algorithm";
1928 } else {
1929 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1930 view->action = "Myers diff algorithm";
1932 TAILQ_FOREACH(v, views, entry) {
1933 if (v->reset) {
1934 err = v->reset(v);
1935 if (err)
1936 return err;
1938 if (v->child && v->child->reset) {
1939 err = v->child->reset(v->child);
1940 if (err)
1941 return err;
1944 break;
1945 case TOG_KEY_SCRDUMP:
1946 err = screendump(view);
1947 break;
1948 default:
1949 err = view->input(new, view, ch);
1950 break;
1953 return err;
1956 static int
1957 view_needs_focus_indication(struct tog_view *view)
1959 if (view_is_parent_view(view)) {
1960 if (view->child == NULL || view->child->focussed)
1961 return 0;
1962 if (!view_is_splitscreen(view->child))
1963 return 0;
1964 } else if (!view_is_splitscreen(view))
1965 return 0;
1967 return view->focussed;
1970 static const struct got_error *
1971 tog_io_close(void)
1973 const struct got_error *err = NULL;
1975 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1976 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1977 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1978 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1979 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1980 err = got_ferror(tog_io.f, GOT_ERR_IO);
1981 if (tog_io.sdump && fclose(tog_io.sdump) == EOF && err == NULL)
1982 err = got_ferror(tog_io.sdump, GOT_ERR_IO);
1983 if (tog_io.input_str != NULL)
1984 free(tog_io.input_str);
1986 return err;
1989 static const struct got_error *
1990 view_loop(struct tog_view *view)
1992 const struct got_error *err = NULL;
1993 struct tog_view_list_head views;
1994 struct tog_view *new_view;
1995 char *mode;
1996 int fast_refresh = 10;
1997 int done = 0, errcode;
1999 mode = getenv("TOG_VIEW_SPLIT_MODE");
2000 if (!mode || !(*mode == 'h' || *mode == 'H'))
2001 view->mode = TOG_VIEW_SPLIT_VERT;
2002 else
2003 view->mode = TOG_VIEW_SPLIT_HRZN;
2005 errcode = pthread_mutex_lock(&tog_mutex);
2006 if (errcode)
2007 return got_error_set_errno(errcode, "pthread_mutex_lock");
2009 TAILQ_INIT(&views);
2010 TAILQ_INSERT_HEAD(&views, view, entry);
2012 view->focussed = 1;
2013 err = view->show(view);
2014 if (err)
2015 return err;
2016 update_panels();
2017 doupdate();
2018 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
2019 !tog_fatal_signal_received()) {
2020 /* Refresh fast during initialization, then become slower. */
2021 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
2022 halfdelay(10); /* switch to once per second */
2024 err = view_input(&new_view, &done, view, &views, fast_refresh);
2025 if (err)
2026 break;
2028 if (view->dying && view == TAILQ_FIRST(&views) &&
2029 TAILQ_NEXT(view, entry) == NULL)
2030 done = 1;
2031 if (done) {
2032 struct tog_view *v;
2035 * When we quit, scroll the screen up a single line
2036 * so we don't lose any information.
2038 TAILQ_FOREACH(v, &views, entry) {
2039 wmove(v->window, 0, 0);
2040 wdeleteln(v->window);
2041 wnoutrefresh(v->window);
2042 if (v->child && !view_is_fullscreen(v)) {
2043 wmove(v->child->window, 0, 0);
2044 wdeleteln(v->child->window);
2045 wnoutrefresh(v->child->window);
2048 doupdate();
2051 if (view->dying) {
2052 struct tog_view *v, *prev = NULL;
2054 if (view_is_parent_view(view))
2055 prev = TAILQ_PREV(view, tog_view_list_head,
2056 entry);
2057 else if (view->parent)
2058 prev = view->parent;
2060 if (view->parent) {
2061 view->parent->child = NULL;
2062 view->parent->focus_child = 0;
2063 /* Restore fullscreen line height. */
2064 view->parent->nlines = view->parent->lines;
2065 err = view_resize(view->parent);
2066 if (err)
2067 break;
2068 /* Make resized splits persist. */
2069 view_transfer_size(view->parent, view);
2070 } else
2071 TAILQ_REMOVE(&views, view, entry);
2073 err = view_close(view);
2074 if (err)
2075 goto done;
2077 view = NULL;
2078 TAILQ_FOREACH(v, &views, entry) {
2079 if (v->focussed)
2080 break;
2082 if (view == NULL && new_view == NULL) {
2083 /* No view has focus. Try to pick one. */
2084 if (prev)
2085 view = prev;
2086 else if (!TAILQ_EMPTY(&views)) {
2087 view = TAILQ_LAST(&views,
2088 tog_view_list_head);
2090 if (view) {
2091 if (view->focus_child) {
2092 view->child->focussed = 1;
2093 view = view->child;
2094 } else
2095 view->focussed = 1;
2099 if (new_view) {
2100 struct tog_view *v, *t;
2101 /* Only allow one parent view per type. */
2102 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2103 if (v->type != new_view->type)
2104 continue;
2105 TAILQ_REMOVE(&views, v, entry);
2106 err = view_close(v);
2107 if (err)
2108 goto done;
2109 break;
2111 TAILQ_INSERT_TAIL(&views, new_view, entry);
2112 view = new_view;
2114 if (view && !done) {
2115 if (view_is_parent_view(view)) {
2116 if (view->child && view->child->focussed)
2117 view = view->child;
2118 } else {
2119 if (view->parent && view->parent->focussed)
2120 view = view->parent;
2122 show_panel(view->panel);
2123 if (view->child && view_is_splitscreen(view->child))
2124 show_panel(view->child->panel);
2125 if (view->parent && view_is_splitscreen(view)) {
2126 err = view->parent->show(view->parent);
2127 if (err)
2128 goto done;
2130 err = view->show(view);
2131 if (err)
2132 goto done;
2133 if (view->child) {
2134 err = view->child->show(view->child);
2135 if (err)
2136 goto done;
2138 update_panels();
2139 doupdate();
2142 done:
2143 while (!TAILQ_EMPTY(&views)) {
2144 const struct got_error *close_err;
2145 view = TAILQ_FIRST(&views);
2146 TAILQ_REMOVE(&views, view, entry);
2147 close_err = view_close(view);
2148 if (close_err && err == NULL)
2149 err = close_err;
2152 errcode = pthread_mutex_unlock(&tog_mutex);
2153 if (errcode && err == NULL)
2154 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2156 return err;
2159 __dead static void
2160 usage_log(void)
2162 endwin();
2163 fprintf(stderr,
2164 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2165 getprogname());
2166 exit(1);
2169 /* Create newly allocated wide-character string equivalent to a byte string. */
2170 static const struct got_error *
2171 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2173 char *vis = NULL;
2174 const struct got_error *err = NULL;
2176 *ws = NULL;
2177 *wlen = mbstowcs(NULL, s, 0);
2178 if (*wlen == (size_t)-1) {
2179 int vislen;
2180 if (errno != EILSEQ)
2181 return got_error_from_errno("mbstowcs");
2183 /* byte string invalid in current encoding; try to "fix" it */
2184 err = got_mbsavis(&vis, &vislen, s);
2185 if (err)
2186 return err;
2187 *wlen = mbstowcs(NULL, vis, 0);
2188 if (*wlen == (size_t)-1) {
2189 err = got_error_from_errno("mbstowcs"); /* give up */
2190 goto done;
2194 *ws = calloc(*wlen + 1, sizeof(**ws));
2195 if (*ws == NULL) {
2196 err = got_error_from_errno("calloc");
2197 goto done;
2200 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2201 err = got_error_from_errno("mbstowcs");
2202 done:
2203 free(vis);
2204 if (err) {
2205 free(*ws);
2206 *ws = NULL;
2207 *wlen = 0;
2209 return err;
2212 static const struct got_error *
2213 expand_tab(char **ptr, const char *src)
2215 char *dst;
2216 size_t len, n, idx = 0, sz = 0;
2218 *ptr = NULL;
2219 n = len = strlen(src);
2220 dst = malloc(n + 1);
2221 if (dst == NULL)
2222 return got_error_from_errno("malloc");
2224 while (idx < len && src[idx]) {
2225 const char c = src[idx];
2227 if (c == '\t') {
2228 size_t nb = TABSIZE - sz % TABSIZE;
2229 char *p;
2231 p = realloc(dst, n + nb);
2232 if (p == NULL) {
2233 free(dst);
2234 return got_error_from_errno("realloc");
2237 dst = p;
2238 n += nb;
2239 memset(dst + sz, ' ', nb);
2240 sz += nb;
2241 } else
2242 dst[sz++] = src[idx];
2243 ++idx;
2246 dst[sz] = '\0';
2247 *ptr = dst;
2248 return NULL;
2252 * Advance at most n columns from wline starting at offset off.
2253 * Return the index to the first character after the span operation.
2254 * Return the combined column width of all spanned wide characters in
2255 * *rcol.
2257 static int
2258 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2260 int width, i, cols = 0;
2262 if (n == 0) {
2263 *rcol = cols;
2264 return off;
2267 for (i = off; wline[i] != L'\0'; ++i) {
2268 if (wline[i] == L'\t')
2269 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2270 else
2271 width = wcwidth(wline[i]);
2273 if (width == -1) {
2274 width = 1;
2275 wline[i] = L'.';
2278 if (cols + width > n)
2279 break;
2280 cols += width;
2283 *rcol = cols;
2284 return i;
2288 * Format a line for display, ensuring that it won't overflow a width limit.
2289 * With scrolling, the width returned refers to the scrolled version of the
2290 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2292 static const struct got_error *
2293 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2294 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2296 const struct got_error *err = NULL;
2297 int cols;
2298 wchar_t *wline = NULL;
2299 char *exstr = NULL;
2300 size_t wlen;
2301 int i, scrollx;
2303 *wlinep = NULL;
2304 *widthp = 0;
2306 if (expand) {
2307 err = expand_tab(&exstr, line);
2308 if (err)
2309 return err;
2312 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2313 free(exstr);
2314 if (err)
2315 return err;
2317 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2319 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2320 wline[wlen - 1] = L'\0';
2321 wlen--;
2323 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2324 wline[wlen - 1] = L'\0';
2325 wlen--;
2328 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2329 wline[i] = L'\0';
2331 if (widthp)
2332 *widthp = cols;
2333 if (scrollxp)
2334 *scrollxp = scrollx;
2335 if (err)
2336 free(wline);
2337 else
2338 *wlinep = wline;
2339 return err;
2342 static const struct got_error*
2343 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2344 struct got_object_id *id, struct got_repository *repo)
2346 static const struct got_error *err = NULL;
2347 struct got_reflist_entry *re;
2348 char *s;
2349 const char *name;
2351 *refs_str = NULL;
2353 if (refs == NULL)
2354 return NULL;
2356 TAILQ_FOREACH(re, refs, entry) {
2357 struct got_tag_object *tag = NULL;
2358 struct got_object_id *ref_id;
2359 int cmp;
2361 name = got_ref_get_name(re->ref);
2362 if (strcmp(name, GOT_REF_HEAD) == 0)
2363 continue;
2364 if (strncmp(name, "refs/", 5) == 0)
2365 name += 5;
2366 if (strncmp(name, "got/", 4) == 0)
2367 continue;
2368 if (strncmp(name, "heads/", 6) == 0)
2369 name += 6;
2370 if (strncmp(name, "remotes/", 8) == 0) {
2371 name += 8;
2372 s = strstr(name, "/" GOT_REF_HEAD);
2373 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
2374 continue;
2376 err = got_ref_resolve(&ref_id, repo, re->ref);
2377 if (err)
2378 break;
2379 if (strncmp(name, "tags/", 5) == 0) {
2380 err = got_object_open_as_tag(&tag, repo, ref_id);
2381 if (err) {
2382 if (err->code != GOT_ERR_OBJ_TYPE) {
2383 free(ref_id);
2384 break;
2386 /* Ref points at something other than a tag. */
2387 err = NULL;
2388 tag = NULL;
2391 cmp = got_object_id_cmp(tag ?
2392 got_object_tag_get_object_id(tag) : ref_id, id);
2393 free(ref_id);
2394 if (tag)
2395 got_object_tag_close(tag);
2396 if (cmp != 0)
2397 continue;
2398 s = *refs_str;
2399 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2400 s ? ", " : "", name) == -1) {
2401 err = got_error_from_errno("asprintf");
2402 free(s);
2403 *refs_str = NULL;
2404 break;
2406 free(s);
2409 return err;
2412 static const struct got_error *
2413 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2414 int col_tab_align)
2416 char *smallerthan;
2418 smallerthan = strchr(author, '<');
2419 if (smallerthan && smallerthan[1] != '\0')
2420 author = smallerthan + 1;
2421 author[strcspn(author, "@>")] = '\0';
2422 return format_line(wauthor, author_width, NULL, author, 0, limit,
2423 col_tab_align, 0);
2426 static const struct got_error *
2427 draw_commit(struct tog_view *view, struct commit_queue_entry *entry,
2428 const size_t date_display_cols, int author_display_cols)
2430 struct tog_log_view_state *s = &view->state.log;
2431 const struct got_error *err = NULL;
2432 struct got_commit_object *commit = entry->commit;
2433 struct got_object_id *id = entry->id;
2434 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2435 char *refs_str = NULL;
2436 char *logmsg0 = NULL, *logmsg = NULL;
2437 char *author = NULL;
2438 wchar_t *wrefstr = NULL, *wlogmsg = NULL, *wauthor = NULL;
2439 int author_width, refstr_width, logmsg_width;
2440 char *newline, *line = NULL;
2441 int col, limit, scrollx, logmsg_x;
2442 const int avail = view->ncols, marker_column = author_display_cols + 1;
2443 struct tm tm;
2444 time_t committer_time;
2445 struct tog_color *tc;
2446 struct got_reflist_head *refs;
2448 if (tog_base_commit.id != NULL && tog_base_commit.idx == -1 &&
2449 got_object_id_cmp(id, tog_base_commit.id) == 0)
2450 tog_base_commit.idx = entry->idx;
2451 if (tog_io.wait_for_ui && s->thread_args.need_commit_marker) {
2452 int rc;
2454 rc = pthread_cond_wait(&s->thread_args.log_loaded, &tog_mutex);
2455 if (rc)
2456 return got_error_set_errno(rc, "pthread_cond_wait");
2459 committer_time = got_object_commit_get_committer_time(commit);
2460 if (gmtime_r(&committer_time, &tm) == NULL)
2461 return got_error_from_errno("gmtime_r");
2462 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2463 return got_error(GOT_ERR_NO_SPACE);
2465 if (avail <= date_display_cols)
2466 limit = MIN(sizeof(datebuf) - 1, avail);
2467 else
2468 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2469 tc = get_color(&s->colors, TOG_COLOR_DATE);
2470 if (tc)
2471 wattr_on(view->window,
2472 COLOR_PAIR(tc->colorpair), NULL);
2473 waddnstr(view->window, datebuf, limit);
2474 if (tc)
2475 wattr_off(view->window,
2476 COLOR_PAIR(tc->colorpair), NULL);
2477 col = limit;
2478 if (col > avail)
2479 goto done;
2481 if (avail >= 120) {
2482 char *id_str;
2483 err = got_object_id_str(&id_str, id);
2484 if (err)
2485 goto done;
2486 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2487 if (tc)
2488 wattr_on(view->window,
2489 COLOR_PAIR(tc->colorpair), NULL);
2490 wprintw(view->window, "%.8s ", id_str);
2491 if (tc)
2492 wattr_off(view->window,
2493 COLOR_PAIR(tc->colorpair), NULL);
2494 free(id_str);
2495 col += 9;
2496 if (col > avail)
2497 goto done;
2500 if (s->use_committer)
2501 author = strdup(got_object_commit_get_committer(commit));
2502 else
2503 author = strdup(got_object_commit_get_author(commit));
2504 if (author == NULL) {
2505 err = got_error_from_errno("strdup");
2506 goto done;
2508 err = format_author(&wauthor, &author_width, author, avail - col, col);
2509 if (err)
2510 goto done;
2511 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2512 if (tc)
2513 wattr_on(view->window,
2514 COLOR_PAIR(tc->colorpair), NULL);
2515 waddwstr(view->window, wauthor);
2516 col += author_width;
2517 while (col < avail && author_width < author_display_cols + 2) {
2518 if (tog_base_commit.marker != GOT_WORKTREE_STATE_UNKNOWN &&
2519 author_width == marker_column &&
2520 entry->idx == tog_base_commit.idx && !s->limit_view) {
2521 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2522 if (tc)
2523 wattr_on(view->window,
2524 COLOR_PAIR(tc->colorpair), NULL);
2525 waddch(view->window, tog_base_commit.marker);
2526 if (tc)
2527 wattr_off(view->window,
2528 COLOR_PAIR(tc->colorpair), NULL);
2529 } else
2530 waddch(view->window, ' ');
2531 col++;
2532 author_width++;
2534 if (tc)
2535 wattr_off(view->window,
2536 COLOR_PAIR(tc->colorpair), NULL);
2537 if (col > avail)
2538 goto done;
2540 err = got_object_commit_get_logmsg(&logmsg0, commit);
2541 if (err)
2542 goto done;
2543 logmsg = logmsg0;
2544 while (*logmsg == '\n')
2545 logmsg++;
2546 newline = strchr(logmsg, '\n');
2547 if (newline)
2548 *newline = '\0';
2550 limit = avail - col;
2551 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2552 limit--; /* for the border */
2554 /* Prepend reference labels to log message if possible .*/
2555 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, id);
2556 err = build_refs_str(&refs_str, refs, id, s->repo);
2557 if (err)
2558 goto done;
2559 if (refs_str) {
2560 char *rs;
2562 if (asprintf(&rs, "[%s]", refs_str) == -1) {
2563 err = got_error_from_errno("asprintf");
2564 goto done;
2566 err = format_line(&wrefstr, &refstr_width,
2567 &scrollx, rs, view->x, limit, col, 1);
2568 free(rs);
2569 if (err)
2570 goto done;
2571 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2572 if (tc)
2573 wattr_on(view->window,
2574 COLOR_PAIR(tc->colorpair), NULL);
2575 waddwstr(view->window, &wrefstr[scrollx]);
2576 if (tc)
2577 wattr_off(view->window,
2578 COLOR_PAIR(tc->colorpair), NULL);
2579 col += MAX(refstr_width, 0);
2580 if (col > avail)
2581 goto done;
2583 if (col < avail) {
2584 waddch(view->window, ' ');
2585 col++;
2588 if (refstr_width > 0)
2589 logmsg_x = 0;
2590 else {
2591 int unscrolled_refstr_width;
2592 size_t len = wcslen(wrefstr);
2595 * No need to check for -1 return value here since
2596 * unprintables have been replaced by span_wline().
2598 unscrolled_refstr_width = wcswidth(wrefstr, len);
2599 unscrolled_refstr_width += 1; /* trailing space */
2600 logmsg_x = view->x - unscrolled_refstr_width;
2603 limit = avail - col;
2604 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2605 limit--; /* for the border */
2606 } else
2607 logmsg_x = view->x;
2609 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, logmsg_x,
2610 limit, col, 1);
2611 if (err)
2612 goto done;
2613 waddwstr(view->window, &wlogmsg[scrollx]);
2614 col += MAX(logmsg_width, 0);
2615 while (col < avail) {
2616 waddch(view->window, ' ');
2617 col++;
2619 done:
2620 free(logmsg0);
2621 free(wlogmsg);
2622 free(wrefstr);
2623 free(refs_str);
2624 free(author);
2625 free(wauthor);
2626 free(line);
2627 return err;
2630 static struct commit_queue_entry *
2631 alloc_commit_queue_entry(struct got_commit_object *commit,
2632 struct got_object_id *id)
2634 struct commit_queue_entry *entry;
2635 struct got_object_id *dup;
2637 entry = calloc(1, sizeof(*entry));
2638 if (entry == NULL)
2639 return NULL;
2641 dup = got_object_id_dup(id);
2642 if (dup == NULL) {
2643 free(entry);
2644 return NULL;
2647 entry->id = dup;
2648 entry->commit = commit;
2649 return entry;
2652 static void
2653 pop_commit(struct commit_queue *commits)
2655 struct commit_queue_entry *entry;
2657 entry = TAILQ_FIRST(&commits->head);
2658 TAILQ_REMOVE(&commits->head, entry, entry);
2659 got_object_commit_close(entry->commit);
2660 commits->ncommits--;
2661 free(entry->id);
2662 free(entry);
2665 static void
2666 free_commits(struct commit_queue *commits)
2668 while (!TAILQ_EMPTY(&commits->head))
2669 pop_commit(commits);
2672 static const struct got_error *
2673 match_commit(int *have_match, struct got_object_id *id,
2674 struct got_commit_object *commit, regex_t *regex)
2676 const struct got_error *err = NULL;
2677 regmatch_t regmatch;
2678 char *id_str = NULL, *logmsg = NULL;
2680 *have_match = 0;
2682 err = got_object_id_str(&id_str, id);
2683 if (err)
2684 return err;
2686 err = got_object_commit_get_logmsg(&logmsg, commit);
2687 if (err)
2688 goto done;
2690 if (regexec(regex, got_object_commit_get_author(commit), 1,
2691 &regmatch, 0) == 0 ||
2692 regexec(regex, got_object_commit_get_committer(commit), 1,
2693 &regmatch, 0) == 0 ||
2694 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2695 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2696 *have_match = 1;
2697 done:
2698 free(id_str);
2699 free(logmsg);
2700 return err;
2703 static const struct got_error *
2704 queue_commits(struct tog_log_thread_args *a)
2706 const struct got_error *err = NULL;
2709 * We keep all commits open throughout the lifetime of the log
2710 * view in order to avoid having to re-fetch commits from disk
2711 * while updating the display.
2713 do {
2714 struct got_object_id id;
2715 struct got_commit_object *commit;
2716 struct commit_queue_entry *entry;
2717 int limit_match = 0;
2718 int errcode;
2720 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2721 NULL, NULL);
2722 if (err)
2723 break;
2725 err = got_object_open_as_commit(&commit, a->repo, &id);
2726 if (err)
2727 break;
2728 entry = alloc_commit_queue_entry(commit, &id);
2729 if (entry == NULL) {
2730 err = got_error_from_errno("alloc_commit_queue_entry");
2731 break;
2734 errcode = pthread_mutex_lock(&tog_mutex);
2735 if (errcode) {
2736 err = got_error_set_errno(errcode,
2737 "pthread_mutex_lock");
2738 break;
2741 entry->idx = a->real_commits->ncommits;
2742 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2743 a->real_commits->ncommits++;
2745 if (*a->limiting) {
2746 err = match_commit(&limit_match, &id, commit,
2747 a->limit_regex);
2748 if (err)
2749 break;
2751 if (limit_match) {
2752 struct commit_queue_entry *matched;
2754 matched = alloc_commit_queue_entry(
2755 entry->commit, entry->id);
2756 if (matched == NULL) {
2757 err = got_error_from_errno(
2758 "alloc_commit_queue_entry");
2759 break;
2761 matched->commit = entry->commit;
2762 got_object_commit_retain(entry->commit);
2764 matched->idx = a->limit_commits->ncommits;
2765 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2766 matched, entry);
2767 a->limit_commits->ncommits++;
2771 * This is how we signal log_thread() that we
2772 * have found a match, and that it should be
2773 * counted as a new entry for the view.
2775 a->limit_match = limit_match;
2778 if (*a->searching == TOG_SEARCH_FORWARD &&
2779 !*a->search_next_done) {
2780 int have_match;
2781 err = match_commit(&have_match, &id, commit, a->regex);
2782 if (err)
2783 break;
2785 if (*a->limiting) {
2786 if (limit_match && have_match)
2787 *a->search_next_done =
2788 TOG_SEARCH_HAVE_MORE;
2789 } else if (have_match)
2790 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2793 errcode = pthread_mutex_unlock(&tog_mutex);
2794 if (errcode && err == NULL)
2795 err = got_error_set_errno(errcode,
2796 "pthread_mutex_unlock");
2797 if (err)
2798 break;
2799 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2801 return err;
2804 static void
2805 select_commit(struct tog_log_view_state *s)
2807 struct commit_queue_entry *entry;
2808 int ncommits = 0;
2810 entry = s->first_displayed_entry;
2811 while (entry) {
2812 if (ncommits == s->selected) {
2813 s->selected_entry = entry;
2814 break;
2816 entry = TAILQ_NEXT(entry, entry);
2817 ncommits++;
2821 static const struct got_error *
2822 draw_commits(struct tog_view *view)
2824 const struct got_error *err = NULL;
2825 struct tog_log_view_state *s = &view->state.log;
2826 struct commit_queue_entry *entry = s->selected_entry;
2827 int limit = view->nlines;
2828 int width;
2829 int ncommits, author_cols = 4, refstr_cols;
2830 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2831 char *refs_str = NULL;
2832 wchar_t *wline;
2833 struct tog_color *tc;
2834 static const size_t date_display_cols = 12;
2835 struct got_reflist_head *refs;
2837 if (view_is_hsplit_top(view))
2838 --limit; /* account for border */
2840 if (s->selected_entry &&
2841 !(view->searching && view->search_next_done == 0)) {
2842 err = got_object_id_str(&id_str, s->selected_entry->id);
2843 if (err)
2844 return err;
2845 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2846 s->selected_entry->id);
2847 err = build_refs_str(&refs_str, refs, s->selected_entry->id,
2848 s->repo);
2849 if (err)
2850 goto done;
2853 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2854 halfdelay(10); /* disable fast refresh */
2856 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2857 if (asprintf(&ncommits_str, " [%d/%d] %s",
2858 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2859 (view->searching && !view->search_next_done) ?
2860 "searching..." : "loading...") == -1) {
2861 err = got_error_from_errno("asprintf");
2862 goto done;
2864 } else {
2865 const char *search_str = NULL;
2866 const char *limit_str = NULL;
2868 if (view->searching) {
2869 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2870 search_str = "no more matches";
2871 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2872 search_str = "no matches found";
2873 else if (!view->search_next_done)
2874 search_str = "searching...";
2877 if (s->limit_view && s->commits->ncommits == 0)
2878 limit_str = "no matches found";
2880 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2881 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2882 search_str ? search_str : (refs_str ? refs_str : ""),
2883 limit_str ? limit_str : "") == -1) {
2884 err = got_error_from_errno("asprintf");
2885 goto done;
2889 free(refs_str);
2890 refs_str = NULL;
2892 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2893 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2894 "........................................",
2895 s->in_repo_path, ncommits_str) == -1) {
2896 err = got_error_from_errno("asprintf");
2897 header = NULL;
2898 goto done;
2900 } else if (asprintf(&header, "commit %s%s",
2901 id_str ? id_str : "........................................",
2902 ncommits_str) == -1) {
2903 err = got_error_from_errno("asprintf");
2904 header = NULL;
2905 goto done;
2907 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2908 if (err)
2909 goto done;
2911 werase(view->window);
2913 if (view_needs_focus_indication(view))
2914 wstandout(view->window);
2915 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2916 if (tc)
2917 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2918 waddwstr(view->window, wline);
2919 while (width < view->ncols) {
2920 waddch(view->window, ' ');
2921 width++;
2923 if (tc)
2924 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2925 if (view_needs_focus_indication(view))
2926 wstandend(view->window);
2927 free(wline);
2928 if (limit <= 1)
2929 goto done;
2931 /* Grow author column size if necessary, and set view->maxx. */
2932 entry = s->first_displayed_entry;
2933 ncommits = 0;
2934 view->maxx = 0;
2935 while (entry) {
2936 struct got_commit_object *c = entry->commit;
2937 char *author, *eol, *msg, *msg0;
2938 wchar_t *wauthor, *wmsg;
2939 int width;
2940 if (ncommits >= limit - 1)
2941 break;
2942 if (s->use_committer)
2943 author = strdup(got_object_commit_get_committer(c));
2944 else
2945 author = strdup(got_object_commit_get_author(c));
2946 if (author == NULL) {
2947 err = got_error_from_errno("strdup");
2948 goto done;
2950 err = format_author(&wauthor, &width, author, COLS,
2951 date_display_cols);
2952 if (author_cols < width)
2953 author_cols = width;
2954 free(wauthor);
2955 free(author);
2956 if (err)
2957 goto done;
2958 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2959 entry->id);
2960 err = build_refs_str(&refs_str, refs, entry->id, s->repo);
2961 if (err)
2962 goto done;
2963 if (refs_str) {
2964 wchar_t *ws;
2965 err = format_line(&ws, &width, NULL, refs_str,
2966 0, INT_MAX, date_display_cols + author_cols, 0);
2967 free(ws);
2968 free(refs_str);
2969 refs_str = NULL;
2970 if (err)
2971 goto done;
2972 refstr_cols = width + 3; /* account for [ ] + space */
2973 } else
2974 refstr_cols = 0;
2975 err = got_object_commit_get_logmsg(&msg0, c);
2976 if (err)
2977 goto done;
2978 msg = msg0;
2979 while (*msg == '\n')
2980 ++msg;
2981 if ((eol = strchr(msg, '\n')))
2982 *eol = '\0';
2983 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2984 date_display_cols + author_cols + refstr_cols, 0);
2985 if (err)
2986 goto done;
2987 view->maxx = MAX(view->maxx, width + refstr_cols);
2988 free(msg0);
2989 free(wmsg);
2990 ncommits++;
2991 entry = TAILQ_NEXT(entry, entry);
2994 entry = s->first_displayed_entry;
2995 s->last_displayed_entry = s->first_displayed_entry;
2996 ncommits = 0;
2997 while (entry) {
2998 if (ncommits >= limit - 1)
2999 break;
3000 if (ncommits == s->selected)
3001 wstandout(view->window);
3002 err = draw_commit(view, entry, date_display_cols, author_cols);
3003 if (ncommits == s->selected)
3004 wstandend(view->window);
3005 if (err)
3006 goto done;
3007 ncommits++;
3008 s->last_displayed_entry = entry;
3009 entry = TAILQ_NEXT(entry, entry);
3012 view_border(view);
3013 done:
3014 free(id_str);
3015 free(refs_str);
3016 free(ncommits_str);
3017 free(header);
3018 return err;
3021 static void
3022 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
3024 struct commit_queue_entry *entry;
3025 int nscrolled = 0;
3027 entry = TAILQ_FIRST(&s->commits->head);
3028 if (s->first_displayed_entry == entry)
3029 return;
3031 entry = s->first_displayed_entry;
3032 while (entry && nscrolled < maxscroll) {
3033 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3034 if (entry) {
3035 s->first_displayed_entry = entry;
3036 nscrolled++;
3041 static const struct got_error *
3042 trigger_log_thread(struct tog_view *view, int wait)
3044 struct tog_log_thread_args *ta = &view->state.log.thread_args;
3045 int errcode;
3047 if (!using_mock_io)
3048 halfdelay(1); /* fast refresh while loading commits */
3050 while (!ta->log_complete && !tog_thread_error &&
3051 (ta->commits_needed > 0 || ta->load_all)) {
3052 /* Wake the log thread. */
3053 errcode = pthread_cond_signal(&ta->need_commits);
3054 if (errcode)
3055 return got_error_set_errno(errcode,
3056 "pthread_cond_signal");
3059 * The mutex will be released while the view loop waits
3060 * in wgetch(), at which time the log thread will run.
3062 if (!wait)
3063 break;
3065 /* Display progress update in log view. */
3066 show_log_view(view);
3067 update_panels();
3068 doupdate();
3070 /* Wait right here while next commit is being loaded. */
3071 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
3072 if (errcode)
3073 return got_error_set_errno(errcode,
3074 "pthread_cond_wait");
3076 /* Display progress update in log view. */
3077 show_log_view(view);
3078 update_panels();
3079 doupdate();
3082 return NULL;
3085 static const struct got_error *
3086 request_log_commits(struct tog_view *view)
3088 struct tog_log_view_state *state = &view->state.log;
3089 const struct got_error *err = NULL;
3091 if (state->thread_args.log_complete)
3092 return NULL;
3094 state->thread_args.commits_needed += view->nscrolled;
3095 err = trigger_log_thread(view, 1);
3096 view->nscrolled = 0;
3098 return err;
3101 static const struct got_error *
3102 log_scroll_down(struct tog_view *view, int maxscroll)
3104 struct tog_log_view_state *s = &view->state.log;
3105 const struct got_error *err = NULL;
3106 struct commit_queue_entry *pentry;
3107 int nscrolled = 0, ncommits_needed;
3109 if (s->last_displayed_entry == NULL)
3110 return NULL;
3112 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
3113 if (s->commits->ncommits < ncommits_needed &&
3114 !s->thread_args.log_complete) {
3116 * Ask the log thread for required amount of commits.
3118 s->thread_args.commits_needed +=
3119 ncommits_needed - s->commits->ncommits;
3120 err = trigger_log_thread(view, 1);
3121 if (err)
3122 return err;
3125 do {
3126 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
3127 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3128 break;
3130 s->last_displayed_entry = pentry ?
3131 pentry : s->last_displayed_entry;
3133 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3134 if (pentry == NULL)
3135 break;
3136 s->first_displayed_entry = pentry;
3137 } while (++nscrolled < maxscroll);
3139 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3140 view->nscrolled += nscrolled;
3141 else
3142 view->nscrolled = 0;
3144 return err;
3147 static const struct got_error *
3148 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3149 struct got_commit_object *commit, struct got_object_id *commit_id,
3150 struct tog_view *log_view, struct got_repository *repo)
3152 const struct got_error *err;
3153 struct got_object_qid *parent_id;
3154 struct tog_view *diff_view;
3156 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3157 if (diff_view == NULL)
3158 return got_error_from_errno("view_open");
3160 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3161 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3162 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3163 if (err == NULL)
3164 *new_view = diff_view;
3165 return err;
3168 static const struct got_error *
3169 tree_view_visit_subtree(struct tog_tree_view_state *s,
3170 struct got_tree_object *subtree)
3172 struct tog_parent_tree *parent;
3174 parent = calloc(1, sizeof(*parent));
3175 if (parent == NULL)
3176 return got_error_from_errno("calloc");
3178 parent->tree = s->tree;
3179 parent->first_displayed_entry = s->first_displayed_entry;
3180 parent->selected_entry = s->selected_entry;
3181 parent->selected = s->selected;
3182 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3183 s->tree = subtree;
3184 s->selected = 0;
3185 s->first_displayed_entry = NULL;
3186 return NULL;
3189 static const struct got_error *
3190 tree_view_walk_path(struct tog_tree_view_state *s,
3191 struct got_commit_object *commit, const char *path)
3193 const struct got_error *err = NULL;
3194 struct got_tree_object *tree = NULL;
3195 const char *p;
3196 char *slash, *subpath = NULL;
3198 /* Walk the path and open corresponding tree objects. */
3199 p = path;
3200 while (*p) {
3201 struct got_tree_entry *te;
3202 struct got_object_id *tree_id;
3203 char *te_name;
3205 while (p[0] == '/')
3206 p++;
3208 /* Ensure the correct subtree entry is selected. */
3209 slash = strchr(p, '/');
3210 if (slash == NULL)
3211 te_name = strdup(p);
3212 else
3213 te_name = strndup(p, slash - p);
3214 if (te_name == NULL) {
3215 err = got_error_from_errno("strndup");
3216 break;
3218 te = got_object_tree_find_entry(s->tree, te_name);
3219 if (te == NULL) {
3220 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3221 free(te_name);
3222 break;
3224 free(te_name);
3225 s->first_displayed_entry = s->selected_entry = te;
3227 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3228 break; /* jump to this file's entry */
3230 slash = strchr(p, '/');
3231 if (slash)
3232 subpath = strndup(path, slash - path);
3233 else
3234 subpath = strdup(path);
3235 if (subpath == NULL) {
3236 err = got_error_from_errno("strdup");
3237 break;
3240 err = got_object_id_by_path(&tree_id, s->repo, commit,
3241 subpath);
3242 if (err)
3243 break;
3245 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3246 free(tree_id);
3247 if (err)
3248 break;
3250 err = tree_view_visit_subtree(s, tree);
3251 if (err) {
3252 got_object_tree_close(tree);
3253 break;
3255 if (slash == NULL)
3256 break;
3257 free(subpath);
3258 subpath = NULL;
3259 p = slash;
3262 free(subpath);
3263 return err;
3266 static const struct got_error *
3267 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3268 struct commit_queue_entry *entry, const char *path,
3269 const char *head_ref_name, struct got_repository *repo)
3271 const struct got_error *err = NULL;
3272 struct tog_tree_view_state *s;
3273 struct tog_view *tree_view;
3275 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3276 if (tree_view == NULL)
3277 return got_error_from_errno("view_open");
3279 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3280 if (err)
3281 return err;
3282 s = &tree_view->state.tree;
3284 *new_view = tree_view;
3286 if (got_path_is_root_dir(path))
3287 return NULL;
3289 return tree_view_walk_path(s, entry->commit, path);
3292 static const struct got_error *
3293 block_signals_used_by_main_thread(void)
3295 sigset_t sigset;
3296 int errcode;
3298 if (sigemptyset(&sigset) == -1)
3299 return got_error_from_errno("sigemptyset");
3301 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3302 if (sigaddset(&sigset, SIGWINCH) == -1)
3303 return got_error_from_errno("sigaddset");
3304 if (sigaddset(&sigset, SIGCONT) == -1)
3305 return got_error_from_errno("sigaddset");
3306 if (sigaddset(&sigset, SIGINT) == -1)
3307 return got_error_from_errno("sigaddset");
3308 if (sigaddset(&sigset, SIGTERM) == -1)
3309 return got_error_from_errno("sigaddset");
3311 /* ncurses handles SIGTSTP */
3312 if (sigaddset(&sigset, SIGTSTP) == -1)
3313 return got_error_from_errno("sigaddset");
3315 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3316 if (errcode)
3317 return got_error_set_errno(errcode, "pthread_sigmask");
3319 return NULL;
3322 static void *
3323 log_thread(void *arg)
3325 const struct got_error *err = NULL;
3326 int errcode = 0;
3327 struct tog_log_thread_args *a = arg;
3328 int done = 0;
3331 * Sync startup with main thread such that we begin our
3332 * work once view_input() has released the mutex.
3334 errcode = pthread_mutex_lock(&tog_mutex);
3335 if (errcode) {
3336 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3337 return (void *)err;
3340 err = block_signals_used_by_main_thread();
3341 if (err) {
3342 pthread_mutex_unlock(&tog_mutex);
3343 goto done;
3346 while (!done && !err && !tog_fatal_signal_received()) {
3347 errcode = pthread_mutex_unlock(&tog_mutex);
3348 if (errcode) {
3349 err = got_error_set_errno(errcode,
3350 "pthread_mutex_unlock");
3351 goto done;
3353 err = queue_commits(a);
3354 if (err) {
3355 if (err->code != GOT_ERR_ITER_COMPLETED)
3356 goto done;
3357 err = NULL;
3358 done = 1;
3359 a->commits_needed = 0;
3360 } else if (a->commits_needed > 0 && !a->load_all) {
3361 if (*a->limiting) {
3362 if (a->limit_match)
3363 a->commits_needed--;
3364 } else
3365 a->commits_needed--;
3368 errcode = pthread_mutex_lock(&tog_mutex);
3369 if (errcode) {
3370 err = got_error_set_errno(errcode,
3371 "pthread_mutex_lock");
3372 goto done;
3373 } else if (*a->quit)
3374 done = 1;
3375 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3376 *a->first_displayed_entry =
3377 TAILQ_FIRST(&a->limit_commits->head);
3378 *a->selected_entry = *a->first_displayed_entry;
3379 } else if (*a->first_displayed_entry == NULL) {
3380 *a->first_displayed_entry =
3381 TAILQ_FIRST(&a->real_commits->head);
3382 *a->selected_entry = *a->first_displayed_entry;
3385 errcode = pthread_cond_signal(&a->commit_loaded);
3386 if (errcode) {
3387 err = got_error_set_errno(errcode,
3388 "pthread_cond_signal");
3389 pthread_mutex_unlock(&tog_mutex);
3390 goto done;
3393 if (a->commits_needed == 0 &&
3394 a->need_commit_marker && a->worktree) {
3395 errcode = pthread_mutex_unlock(&tog_mutex);
3396 if (errcode) {
3397 err = got_error_set_errno(errcode,
3398 "pthread_mutex_unlock");
3399 goto done;
3401 err = got_worktree_get_state(&tog_base_commit.marker,
3402 a->repo, a->worktree, NULL, NULL);
3403 if (err)
3404 goto done;
3405 errcode = pthread_mutex_lock(&tog_mutex);
3406 if (errcode) {
3407 err = got_error_set_errno(errcode,
3408 "pthread_mutex_lock");
3409 goto done;
3411 a->need_commit_marker = 0;
3413 * The main thread did not close this
3414 * work tree yet. Close it now.
3416 got_worktree_close(a->worktree);
3417 a->worktree = NULL;
3419 if (*a->quit)
3420 done = 1;
3423 if (done)
3424 a->commits_needed = 0;
3425 else {
3426 if (a->commits_needed == 0 && !a->load_all) {
3427 if (tog_io.wait_for_ui) {
3428 errcode = pthread_cond_signal(
3429 &a->log_loaded);
3430 if (errcode && err == NULL)
3431 err = got_error_set_errno(
3432 errcode,
3433 "pthread_cond_signal");
3436 errcode = pthread_cond_wait(&a->need_commits,
3437 &tog_mutex);
3438 if (errcode) {
3439 err = got_error_set_errno(errcode,
3440 "pthread_cond_wait");
3441 pthread_mutex_unlock(&tog_mutex);
3442 goto done;
3444 if (*a->quit)
3445 done = 1;
3449 a->log_complete = 1;
3450 if (tog_io.wait_for_ui) {
3451 errcode = pthread_cond_signal(&a->log_loaded);
3452 if (errcode && err == NULL)
3453 err = got_error_set_errno(errcode,
3454 "pthread_cond_signal");
3457 errcode = pthread_mutex_unlock(&tog_mutex);
3458 if (errcode)
3459 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3460 done:
3461 if (err) {
3462 tog_thread_error = 1;
3463 pthread_cond_signal(&a->commit_loaded);
3464 if (a->worktree) {
3465 got_worktree_close(a->worktree);
3466 a->worktree = NULL;
3469 return (void *)err;
3472 static const struct got_error *
3473 stop_log_thread(struct tog_log_view_state *s)
3475 const struct got_error *err = NULL, *thread_err = NULL;
3476 int errcode;
3478 if (s->thread) {
3479 s->quit = 1;
3480 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3481 if (errcode)
3482 return got_error_set_errno(errcode,
3483 "pthread_cond_signal");
3484 errcode = pthread_mutex_unlock(&tog_mutex);
3485 if (errcode)
3486 return got_error_set_errno(errcode,
3487 "pthread_mutex_unlock");
3488 errcode = pthread_join(s->thread, (void **)&thread_err);
3489 if (errcode)
3490 return got_error_set_errno(errcode, "pthread_join");
3491 errcode = pthread_mutex_lock(&tog_mutex);
3492 if (errcode)
3493 return got_error_set_errno(errcode,
3494 "pthread_mutex_lock");
3495 s->thread = NULL;
3498 if (s->thread_args.repo) {
3499 err = got_repo_close(s->thread_args.repo);
3500 s->thread_args.repo = NULL;
3503 if (s->thread_args.pack_fds) {
3504 const struct got_error *pack_err =
3505 got_repo_pack_fds_close(s->thread_args.pack_fds);
3506 if (err == NULL)
3507 err = pack_err;
3508 s->thread_args.pack_fds = NULL;
3511 if (s->thread_args.graph) {
3512 got_commit_graph_close(s->thread_args.graph);
3513 s->thread_args.graph = NULL;
3516 return err ? err : thread_err;
3519 static const struct got_error *
3520 close_log_view(struct tog_view *view)
3522 const struct got_error *err = NULL;
3523 struct tog_log_view_state *s = &view->state.log;
3524 int errcode;
3526 err = stop_log_thread(s);
3528 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3529 if (errcode && err == NULL)
3530 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3532 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3533 if (errcode && err == NULL)
3534 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3536 free_commits(&s->limit_commits);
3537 free_commits(&s->real_commits);
3538 free_colors(&s->colors);
3539 free(s->in_repo_path);
3540 s->in_repo_path = NULL;
3541 free(s->start_id);
3542 s->start_id = NULL;
3543 free(s->head_ref_name);
3544 s->head_ref_name = NULL;
3545 return err;
3549 * We use two queues to implement the limit feature: first consists of
3550 * commits matching the current limit_regex; second is the real queue
3551 * of all known commits (real_commits). When the user starts limiting,
3552 * we swap queues such that all movement and displaying functionality
3553 * works with very slight change.
3555 static const struct got_error *
3556 limit_log_view(struct tog_view *view)
3558 struct tog_log_view_state *s = &view->state.log;
3559 struct commit_queue_entry *entry;
3560 struct tog_view *v = view;
3561 const struct got_error *err = NULL;
3562 char pattern[1024];
3563 int ret;
3565 if (view_is_hsplit_top(view))
3566 v = view->child;
3567 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3568 v = view->parent;
3570 if (tog_io.input_str != NULL) {
3571 if (strlcpy(pattern, tog_io.input_str, sizeof(pattern)) >=
3572 sizeof(pattern))
3573 return got_error(GOT_ERR_NO_SPACE);
3574 } else {
3575 wmove(v->window, v->nlines - 1, 0);
3576 wclrtoeol(v->window);
3577 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3578 nodelay(v->window, FALSE);
3579 nocbreak();
3580 echo();
3581 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3582 cbreak();
3583 noecho();
3584 nodelay(v->window, TRUE);
3585 if (ret == ERR)
3586 return NULL;
3589 if (*pattern == '\0') {
3591 * Safety measure for the situation where the user
3592 * resets limit without previously limiting anything.
3594 if (!s->limit_view)
3595 return NULL;
3598 * User could have pressed Ctrl+L, which refreshed the
3599 * commit queues, it means we can't save previously
3600 * (before limit took place) displayed entries,
3601 * because they would point to already free'ed memory,
3602 * so we are forced to always select first entry of
3603 * the queue.
3605 s->commits = &s->real_commits;
3606 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3607 s->selected_entry = s->first_displayed_entry;
3608 s->selected = 0;
3609 s->limit_view = 0;
3611 return NULL;
3614 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3615 return NULL;
3617 s->limit_view = 1;
3619 /* Clear the screen while loading limit view */
3620 s->first_displayed_entry = NULL;
3621 s->last_displayed_entry = NULL;
3622 s->selected_entry = NULL;
3623 s->commits = &s->limit_commits;
3625 /* Prepare limit queue for new search */
3626 free_commits(&s->limit_commits);
3627 s->limit_commits.ncommits = 0;
3629 /* First process commits, which are in queue already */
3630 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3631 int have_match = 0;
3633 err = match_commit(&have_match, entry->id,
3634 entry->commit, &s->limit_regex);
3635 if (err)
3636 return err;
3638 if (have_match) {
3639 struct commit_queue_entry *matched;
3641 matched = alloc_commit_queue_entry(entry->commit,
3642 entry->id);
3643 if (matched == NULL) {
3644 err = got_error_from_errno(
3645 "alloc_commit_queue_entry");
3646 break;
3648 matched->commit = entry->commit;
3649 got_object_commit_retain(entry->commit);
3651 matched->idx = s->limit_commits.ncommits;
3652 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3653 matched, entry);
3654 s->limit_commits.ncommits++;
3658 /* Second process all the commits, until we fill the screen */
3659 if (s->limit_commits.ncommits < view->nlines - 1 &&
3660 !s->thread_args.log_complete) {
3661 s->thread_args.commits_needed +=
3662 view->nlines - s->limit_commits.ncommits - 1;
3663 err = trigger_log_thread(view, 1);
3664 if (err)
3665 return err;
3668 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3669 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3670 s->selected = 0;
3672 return NULL;
3675 static const struct got_error *
3676 search_start_log_view(struct tog_view *view)
3678 struct tog_log_view_state *s = &view->state.log;
3680 s->matched_entry = NULL;
3681 s->search_entry = NULL;
3682 return NULL;
3685 static const struct got_error *
3686 search_next_log_view(struct tog_view *view)
3688 const struct got_error *err = NULL;
3689 struct tog_log_view_state *s = &view->state.log;
3690 struct commit_queue_entry *entry;
3692 /* Display progress update in log view. */
3693 show_log_view(view);
3694 update_panels();
3695 doupdate();
3697 if (s->search_entry) {
3698 if (!using_mock_io) {
3699 int errcode, ch;
3701 errcode = pthread_mutex_unlock(&tog_mutex);
3702 if (errcode)
3703 return got_error_set_errno(errcode,
3704 "pthread_mutex_unlock");
3705 ch = wgetch(view->window);
3706 errcode = pthread_mutex_lock(&tog_mutex);
3707 if (errcode)
3708 return got_error_set_errno(errcode,
3709 "pthread_mutex_lock");
3710 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3711 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3712 return NULL;
3715 if (view->searching == TOG_SEARCH_FORWARD)
3716 entry = TAILQ_NEXT(s->search_entry, entry);
3717 else
3718 entry = TAILQ_PREV(s->search_entry,
3719 commit_queue_head, entry);
3720 } else if (s->matched_entry) {
3722 * If the user has moved the cursor after we hit a match,
3723 * the position from where we should continue searching
3724 * might have changed.
3726 if (view->searching == TOG_SEARCH_FORWARD)
3727 entry = TAILQ_NEXT(s->selected_entry, entry);
3728 else
3729 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3730 entry);
3731 } else {
3732 entry = s->selected_entry;
3735 while (1) {
3736 int have_match = 0;
3738 if (entry == NULL) {
3739 if (s->thread_args.log_complete ||
3740 view->searching == TOG_SEARCH_BACKWARD) {
3741 view->search_next_done =
3742 (s->matched_entry == NULL ?
3743 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3744 s->search_entry = NULL;
3745 return NULL;
3748 * Poke the log thread for more commits and return,
3749 * allowing the main loop to make progress. Search
3750 * will resume at s->search_entry once we come back.
3752 s->search_entry = s->selected_entry;
3753 s->thread_args.commits_needed++;
3754 return trigger_log_thread(view, 0);
3757 err = match_commit(&have_match, entry->id, entry->commit,
3758 &view->regex);
3759 if (err)
3760 break;
3761 if (have_match) {
3762 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3763 s->matched_entry = entry;
3764 break;
3767 s->search_entry = entry;
3768 if (view->searching == TOG_SEARCH_FORWARD)
3769 entry = TAILQ_NEXT(entry, entry);
3770 else
3771 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3774 if (s->matched_entry) {
3775 int cur = s->selected_entry->idx;
3776 while (cur < s->matched_entry->idx) {
3777 err = input_log_view(NULL, view, KEY_DOWN);
3778 if (err)
3779 return err;
3780 cur++;
3782 while (cur > s->matched_entry->idx) {
3783 err = input_log_view(NULL, view, KEY_UP);
3784 if (err)
3785 return err;
3786 cur--;
3790 s->search_entry = NULL;
3792 return NULL;
3795 static const struct got_error *
3796 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3797 struct got_repository *repo, const char *head_ref_name,
3798 const char *in_repo_path, int log_branches,
3799 struct got_worktree *worktree)
3801 const struct got_error *err = NULL;
3802 struct tog_log_view_state *s = &view->state.log;
3803 struct got_repository *thread_repo = NULL;
3804 struct got_commit_graph *thread_graph = NULL;
3805 int errcode;
3807 if (in_repo_path != s->in_repo_path) {
3808 free(s->in_repo_path);
3809 s->in_repo_path = strdup(in_repo_path);
3810 if (s->in_repo_path == NULL) {
3811 err = got_error_from_errno("strdup");
3812 goto done;
3816 /* The commit queue only contains commits being displayed. */
3817 TAILQ_INIT(&s->real_commits.head);
3818 s->real_commits.ncommits = 0;
3819 s->commits = &s->real_commits;
3821 TAILQ_INIT(&s->limit_commits.head);
3822 s->limit_view = 0;
3823 s->limit_commits.ncommits = 0;
3825 s->repo = repo;
3826 if (head_ref_name) {
3827 s->head_ref_name = strdup(head_ref_name);
3828 if (s->head_ref_name == NULL) {
3829 err = got_error_from_errno("strdup");
3830 goto done;
3833 s->start_id = got_object_id_dup(start_id);
3834 if (s->start_id == NULL) {
3835 err = got_error_from_errno("got_object_id_dup");
3836 goto done;
3838 s->log_branches = log_branches;
3839 s->use_committer = 1;
3841 STAILQ_INIT(&s->colors);
3842 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3843 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3844 get_color_value("TOG_COLOR_COMMIT"));
3845 if (err)
3846 goto done;
3847 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3848 get_color_value("TOG_COLOR_AUTHOR"));
3849 if (err)
3850 goto done;
3851 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3852 get_color_value("TOG_COLOR_DATE"));
3853 if (err)
3854 goto done;
3857 view->show = show_log_view;
3858 view->input = input_log_view;
3859 view->resize = resize_log_view;
3860 view->close = close_log_view;
3861 view->search_start = search_start_log_view;
3862 view->search_next = search_next_log_view;
3864 if (s->thread_args.pack_fds == NULL) {
3865 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3866 if (err)
3867 goto done;
3869 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3870 s->thread_args.pack_fds);
3871 if (err)
3872 goto done;
3873 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3874 !s->log_branches);
3875 if (err)
3876 goto done;
3877 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3878 s->repo, NULL, NULL);
3879 if (err)
3880 goto done;
3882 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3883 if (errcode) {
3884 err = got_error_set_errno(errcode, "pthread_cond_init");
3885 goto done;
3887 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3888 if (errcode) {
3889 err = got_error_set_errno(errcode, "pthread_cond_init");
3890 goto done;
3893 if (using_mock_io) {
3894 int rc;
3896 rc = pthread_cond_init(&s->thread_args.log_loaded, NULL);
3897 if (rc)
3898 return got_error_set_errno(rc, "pthread_cond_init");
3901 s->thread_args.commits_needed = view->nlines;
3902 s->thread_args.graph = thread_graph;
3903 s->thread_args.real_commits = &s->real_commits;
3904 s->thread_args.limit_commits = &s->limit_commits;
3905 s->thread_args.in_repo_path = s->in_repo_path;
3906 s->thread_args.start_id = s->start_id;
3907 s->thread_args.repo = thread_repo;
3908 s->thread_args.log_complete = 0;
3909 s->thread_args.quit = &s->quit;
3910 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3911 s->thread_args.selected_entry = &s->selected_entry;
3912 s->thread_args.searching = &view->searching;
3913 s->thread_args.search_next_done = &view->search_next_done;
3914 s->thread_args.regex = &view->regex;
3915 s->thread_args.limiting = &s->limit_view;
3916 s->thread_args.limit_regex = &s->limit_regex;
3917 s->thread_args.limit_commits = &s->limit_commits;
3918 s->thread_args.worktree = worktree;
3919 if (worktree)
3920 s->thread_args.need_commit_marker = 1;
3921 done:
3922 if (err) {
3923 if (view->close == NULL)
3924 close_log_view(view);
3925 view_close(view);
3927 return err;
3930 static const struct got_error *
3931 show_log_view(struct tog_view *view)
3933 const struct got_error *err;
3934 struct tog_log_view_state *s = &view->state.log;
3936 if (s->thread == NULL) {
3937 int errcode = pthread_create(&s->thread, NULL, log_thread,
3938 &s->thread_args);
3939 if (errcode)
3940 return got_error_set_errno(errcode, "pthread_create");
3941 if (s->thread_args.commits_needed > 0) {
3942 err = trigger_log_thread(view, 1);
3943 if (err)
3944 return err;
3948 return draw_commits(view);
3951 static void
3952 log_move_cursor_up(struct tog_view *view, int page, int home)
3954 struct tog_log_view_state *s = &view->state.log;
3956 if (s->first_displayed_entry == NULL)
3957 return;
3958 if (s->selected_entry->idx == 0)
3959 view->count = 0;
3961 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3962 || home)
3963 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3965 if (!page && !home && s->selected > 0)
3966 --s->selected;
3967 else
3968 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3970 select_commit(s);
3971 return;
3974 static const struct got_error *
3975 log_move_cursor_down(struct tog_view *view, int page)
3977 struct tog_log_view_state *s = &view->state.log;
3978 const struct got_error *err = NULL;
3979 int eos = view->nlines - 2;
3981 if (s->first_displayed_entry == NULL)
3982 return NULL;
3984 if (s->thread_args.log_complete &&
3985 s->selected_entry->idx >= s->commits->ncommits - 1)
3986 return NULL;
3988 if (view_is_hsplit_top(view))
3989 --eos; /* border consumes the last line */
3991 if (!page) {
3992 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3993 ++s->selected;
3994 else
3995 err = log_scroll_down(view, 1);
3996 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3997 struct commit_queue_entry *entry;
3998 int n;
4000 s->selected = 0;
4001 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
4002 s->last_displayed_entry = entry;
4003 for (n = 0; n <= eos; n++) {
4004 if (entry == NULL)
4005 break;
4006 s->first_displayed_entry = entry;
4007 entry = TAILQ_PREV(entry, commit_queue_head, entry);
4009 if (n > 0)
4010 s->selected = n - 1;
4011 } else {
4012 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
4013 s->thread_args.log_complete)
4014 s->selected += MIN(page,
4015 s->commits->ncommits - s->selected_entry->idx - 1);
4016 else
4017 err = log_scroll_down(view, page);
4019 if (err)
4020 return err;
4023 * We might necessarily overshoot in horizontal
4024 * splits; if so, select the last displayed commit.
4026 if (s->first_displayed_entry && s->last_displayed_entry) {
4027 s->selected = MIN(s->selected,
4028 s->last_displayed_entry->idx -
4029 s->first_displayed_entry->idx);
4032 select_commit(s);
4034 if (s->thread_args.log_complete &&
4035 s->selected_entry->idx == s->commits->ncommits - 1)
4036 view->count = 0;
4038 return NULL;
4041 static void
4042 view_get_split(struct tog_view *view, int *y, int *x)
4044 *x = 0;
4045 *y = 0;
4047 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
4048 if (view->child && view->child->resized_y)
4049 *y = view->child->resized_y;
4050 else if (view->resized_y)
4051 *y = view->resized_y;
4052 else
4053 *y = view_split_begin_y(view->lines);
4054 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
4055 if (view->child && view->child->resized_x)
4056 *x = view->child->resized_x;
4057 else if (view->resized_x)
4058 *x = view->resized_x;
4059 else
4060 *x = view_split_begin_x(view->begin_x);
4064 /* Split view horizontally at y and offset view->state->selected line. */
4065 static const struct got_error *
4066 view_init_hsplit(struct tog_view *view, int y)
4068 const struct got_error *err = NULL;
4070 view->nlines = y;
4071 view->ncols = COLS;
4072 err = view_resize(view);
4073 if (err)
4074 return err;
4076 err = offset_selection_down(view);
4078 return err;
4081 static const struct got_error *
4082 log_goto_line(struct tog_view *view, int nlines)
4084 const struct got_error *err = NULL;
4085 struct tog_log_view_state *s = &view->state.log;
4086 int g, idx = s->selected_entry->idx;
4088 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
4089 return NULL;
4091 g = view->gline;
4092 view->gline = 0;
4094 if (g >= s->first_displayed_entry->idx + 1 &&
4095 g <= s->last_displayed_entry->idx + 1 &&
4096 g - s->first_displayed_entry->idx - 1 < nlines) {
4097 s->selected = g - s->first_displayed_entry->idx - 1;
4098 select_commit(s);
4099 return NULL;
4102 if (idx + 1 < g) {
4103 err = log_move_cursor_down(view, g - idx - 1);
4104 if (!err && g > s->selected_entry->idx + 1)
4105 err = log_move_cursor_down(view,
4106 g - s->first_displayed_entry->idx - 1);
4107 if (err)
4108 return err;
4109 } else if (idx + 1 > g)
4110 log_move_cursor_up(view, idx - g + 1, 0);
4112 if (g < nlines && s->first_displayed_entry->idx == 0)
4113 s->selected = g - 1;
4115 select_commit(s);
4116 return NULL;
4120 static void
4121 horizontal_scroll_input(struct tog_view *view, int ch)
4124 switch (ch) {
4125 case KEY_LEFT:
4126 case 'h':
4127 view->x -= MIN(view->x, 2);
4128 if (view->x <= 0)
4129 view->count = 0;
4130 break;
4131 case KEY_RIGHT:
4132 case 'l':
4133 if (view->x + view->ncols / 2 < view->maxx)
4134 view->x += 2;
4135 else
4136 view->count = 0;
4137 break;
4138 case '0':
4139 view->x = 0;
4140 break;
4141 case '$':
4142 view->x = MAX(view->maxx - view->ncols / 2, 0);
4143 view->count = 0;
4144 break;
4145 default:
4146 break;
4150 static const struct got_error *
4151 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4153 const struct got_error *err = NULL;
4154 struct tog_log_view_state *s = &view->state.log;
4155 int eos, nscroll;
4157 if (s->thread_args.load_all) {
4158 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4159 s->thread_args.load_all = 0;
4160 else if (s->thread_args.log_complete) {
4161 err = log_move_cursor_down(view, s->commits->ncommits);
4162 s->thread_args.load_all = 0;
4164 if (err)
4165 return err;
4168 eos = nscroll = view->nlines - 1;
4169 if (view_is_hsplit_top(view))
4170 --eos; /* border */
4172 if (view->gline)
4173 return log_goto_line(view, eos);
4175 switch (ch) {
4176 case '&':
4177 err = limit_log_view(view);
4178 break;
4179 case 'q':
4180 s->quit = 1;
4181 break;
4182 case '0':
4183 case '$':
4184 case KEY_RIGHT:
4185 case 'l':
4186 case KEY_LEFT:
4187 case 'h':
4188 horizontal_scroll_input(view, ch);
4189 break;
4190 case 'k':
4191 case KEY_UP:
4192 case '<':
4193 case ',':
4194 case CTRL('p'):
4195 log_move_cursor_up(view, 0, 0);
4196 break;
4197 case 'g':
4198 case '=':
4199 case KEY_HOME:
4200 log_move_cursor_up(view, 0, 1);
4201 view->count = 0;
4202 break;
4203 case CTRL('u'):
4204 case 'u':
4205 nscroll /= 2;
4206 /* FALL THROUGH */
4207 case KEY_PPAGE:
4208 case CTRL('b'):
4209 case 'b':
4210 log_move_cursor_up(view, nscroll, 0);
4211 break;
4212 case 'j':
4213 case KEY_DOWN:
4214 case '>':
4215 case '.':
4216 case CTRL('n'):
4217 err = log_move_cursor_down(view, 0);
4218 break;
4219 case '@':
4220 s->use_committer = !s->use_committer;
4221 view->action = s->use_committer ?
4222 "show committer" : "show commit author";
4223 break;
4224 case 'G':
4225 case '*':
4226 case KEY_END: {
4227 /* We don't know yet how many commits, so we're forced to
4228 * traverse them all. */
4229 view->count = 0;
4230 s->thread_args.load_all = 1;
4231 if (!s->thread_args.log_complete)
4232 return trigger_log_thread(view, 0);
4233 err = log_move_cursor_down(view, s->commits->ncommits);
4234 s->thread_args.load_all = 0;
4235 break;
4237 case CTRL('d'):
4238 case 'd':
4239 nscroll /= 2;
4240 /* FALL THROUGH */
4241 case KEY_NPAGE:
4242 case CTRL('f'):
4243 case 'f':
4244 case ' ':
4245 err = log_move_cursor_down(view, nscroll);
4246 break;
4247 case KEY_RESIZE:
4248 if (s->selected > view->nlines - 2)
4249 s->selected = view->nlines - 2;
4250 if (s->selected > s->commits->ncommits - 1)
4251 s->selected = s->commits->ncommits - 1;
4252 select_commit(s);
4253 if (s->commits->ncommits < view->nlines - 1 &&
4254 !s->thread_args.log_complete) {
4255 s->thread_args.commits_needed += (view->nlines - 1) -
4256 s->commits->ncommits;
4257 err = trigger_log_thread(view, 1);
4259 break;
4260 case KEY_ENTER:
4261 case '\r':
4262 view->count = 0;
4263 if (s->selected_entry == NULL)
4264 break;
4265 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4266 break;
4267 case 'T':
4268 view->count = 0;
4269 if (s->selected_entry == NULL)
4270 break;
4271 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4272 break;
4273 case KEY_BACKSPACE:
4274 case CTRL('l'):
4275 case 'B':
4276 view->count = 0;
4277 if (ch == KEY_BACKSPACE &&
4278 got_path_is_root_dir(s->in_repo_path))
4279 break;
4280 err = stop_log_thread(s);
4281 if (err)
4282 return err;
4283 if (ch == KEY_BACKSPACE) {
4284 char *parent_path;
4285 err = got_path_dirname(&parent_path, s->in_repo_path);
4286 if (err)
4287 return err;
4288 free(s->in_repo_path);
4289 s->in_repo_path = parent_path;
4290 s->thread_args.in_repo_path = s->in_repo_path;
4291 } else if (ch == CTRL('l')) {
4292 struct got_object_id *start_id;
4293 err = got_repo_match_object_id(&start_id, NULL,
4294 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4295 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4296 if (err) {
4297 if (s->head_ref_name == NULL ||
4298 err->code != GOT_ERR_NOT_REF)
4299 return err;
4300 /* Try to cope with deleted references. */
4301 free(s->head_ref_name);
4302 s->head_ref_name = NULL;
4303 err = got_repo_match_object_id(&start_id,
4304 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4305 &tog_refs, s->repo);
4306 if (err)
4307 return err;
4309 free(s->start_id);
4310 s->start_id = start_id;
4311 s->thread_args.start_id = s->start_id;
4312 } else /* 'B' */
4313 s->log_branches = !s->log_branches;
4315 if (s->thread_args.pack_fds == NULL) {
4316 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4317 if (err)
4318 return err;
4320 err = got_repo_open(&s->thread_args.repo,
4321 got_repo_get_path(s->repo), NULL,
4322 s->thread_args.pack_fds);
4323 if (err)
4324 return err;
4325 tog_free_refs();
4326 err = tog_load_refs(s->repo, 0);
4327 if (err)
4328 return err;
4329 err = got_commit_graph_open(&s->thread_args.graph,
4330 s->in_repo_path, !s->log_branches);
4331 if (err)
4332 return err;
4333 err = got_commit_graph_iter_start(s->thread_args.graph,
4334 s->start_id, s->repo, NULL, NULL);
4335 if (err)
4336 return err;
4337 free_commits(&s->real_commits);
4338 free_commits(&s->limit_commits);
4339 s->first_displayed_entry = NULL;
4340 s->last_displayed_entry = NULL;
4341 s->selected_entry = NULL;
4342 s->selected = 0;
4343 s->thread_args.log_complete = 0;
4344 s->quit = 0;
4345 s->thread_args.commits_needed = view->lines;
4346 s->matched_entry = NULL;
4347 s->search_entry = NULL;
4348 view->offset = 0;
4349 break;
4350 case 'R':
4351 view->count = 0;
4352 err = view_request_new(new_view, view, TOG_VIEW_REF);
4353 break;
4354 default:
4355 view->count = 0;
4356 break;
4359 return err;
4362 static const struct got_error *
4363 apply_unveil(const char *repo_path, const char *worktree_path)
4365 const struct got_error *error;
4367 #ifdef PROFILE
4368 if (unveil("gmon.out", "rwc") != 0)
4369 return got_error_from_errno2("unveil", "gmon.out");
4370 #endif
4371 if (repo_path && unveil(repo_path, "r") != 0)
4372 return got_error_from_errno2("unveil", repo_path);
4374 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4375 return got_error_from_errno2("unveil", worktree_path);
4377 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4378 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4380 error = got_privsep_unveil_exec_helpers();
4381 if (error != NULL)
4382 return error;
4384 if (unveil(NULL, NULL) != 0)
4385 return got_error_from_errno("unveil");
4387 return NULL;
4390 static const struct got_error *
4391 init_mock_term(const char *test_script_path)
4393 const struct got_error *err = NULL;
4394 const char *screen_dump_path;
4395 int in;
4397 if (test_script_path == NULL || *test_script_path == '\0')
4398 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4400 tog_io.f = fopen(test_script_path, "re");
4401 if (tog_io.f == NULL) {
4402 err = got_error_from_errno_fmt("fopen: %s",
4403 test_script_path);
4404 goto done;
4407 /* test mode, we don't want any output */
4408 tog_io.cout = fopen("/dev/null", "w+");
4409 if (tog_io.cout == NULL) {
4410 err = got_error_from_errno2("fopen", "/dev/null");
4411 goto done;
4414 in = dup(fileno(tog_io.cout));
4415 if (in == -1) {
4416 err = got_error_from_errno("dup");
4417 goto done;
4419 tog_io.cin = fdopen(in, "r");
4420 if (tog_io.cin == NULL) {
4421 err = got_error_from_errno("fdopen");
4422 close(in);
4423 goto done;
4426 screen_dump_path = getenv("TOG_SCR_DUMP");
4427 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4428 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4429 tog_io.sdump = fopen(screen_dump_path, "we");
4430 if (tog_io.sdump == NULL) {
4431 err = got_error_from_errno2("fopen", screen_dump_path);
4432 goto done;
4435 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4436 err = got_error_from_errno("fseeko");
4437 goto done;
4440 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4441 err = got_error_msg(GOT_ERR_IO,
4442 "newterm: failed to initialise curses");
4444 using_mock_io = 1;
4446 done:
4447 if (err)
4448 tog_io_close();
4449 return err;
4452 static void
4453 init_curses(void)
4455 if (using_mock_io) /* In test mode we use a fake terminal */
4456 return;
4458 initscr();
4460 cbreak();
4461 halfdelay(1); /* Fast refresh while initial view is loading. */
4462 noecho();
4463 nonl();
4464 intrflush(stdscr, FALSE);
4465 keypad(stdscr, TRUE);
4466 curs_set(0);
4467 if (getenv("TOG_COLORS") != NULL) {
4468 start_color();
4469 use_default_colors();
4472 return;
4475 static const struct got_error *
4476 set_tog_base_commit(struct got_repository *repo, struct got_worktree *worktree)
4478 tog_base_commit.id = got_object_id_dup(
4479 got_worktree_get_base_commit_id(worktree));
4480 if (tog_base_commit.id == NULL)
4481 return got_error_from_errno( "got_object_id_dup");
4483 return NULL;
4486 static const struct got_error *
4487 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4488 struct got_repository *repo, struct got_worktree *worktree)
4490 const struct got_error *err = NULL;
4492 if (argc == 0) {
4493 *in_repo_path = strdup("/");
4494 if (*in_repo_path == NULL)
4495 return got_error_from_errno("strdup");
4496 return NULL;
4499 if (worktree) {
4500 const char *prefix = got_worktree_get_path_prefix(worktree);
4501 char *p;
4503 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4504 if (err)
4505 return err;
4506 if (asprintf(in_repo_path, "%s%s%s", prefix,
4507 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4508 p) == -1) {
4509 err = got_error_from_errno("asprintf");
4510 *in_repo_path = NULL;
4512 free(p);
4513 } else
4514 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4516 return err;
4519 static const struct got_error *
4520 cmd_log(int argc, char *argv[])
4522 const struct got_error *error;
4523 struct got_repository *repo = NULL;
4524 struct got_worktree *worktree = NULL;
4525 struct got_object_id *start_id = NULL;
4526 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4527 char *keyword_idstr = NULL, *start_commit = NULL, *label = NULL;
4528 struct got_reference *ref = NULL;
4529 const char *head_ref_name = NULL;
4530 int ch, log_branches = 0;
4531 struct tog_view *view;
4532 int *pack_fds = NULL;
4534 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4535 switch (ch) {
4536 case 'b':
4537 log_branches = 1;
4538 break;
4539 case 'c':
4540 start_commit = optarg;
4541 break;
4542 case 'r':
4543 repo_path = realpath(optarg, NULL);
4544 if (repo_path == NULL)
4545 return got_error_from_errno2("realpath",
4546 optarg);
4547 break;
4548 default:
4549 usage_log();
4550 /* NOTREACHED */
4554 argc -= optind;
4555 argv += optind;
4557 if (argc > 1)
4558 usage_log();
4560 error = got_repo_pack_fds_open(&pack_fds);
4561 if (error != NULL)
4562 goto done;
4564 if (repo_path == NULL) {
4565 cwd = getcwd(NULL, 0);
4566 if (cwd == NULL) {
4567 error = got_error_from_errno("getcwd");
4568 goto done;
4570 error = got_worktree_open(&worktree, cwd, NULL);
4571 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4572 goto done;
4573 if (worktree)
4574 repo_path =
4575 strdup(got_worktree_get_repo_path(worktree));
4576 else
4577 repo_path = strdup(cwd);
4578 if (repo_path == NULL) {
4579 error = got_error_from_errno("strdup");
4580 goto done;
4584 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4585 if (error != NULL)
4586 goto done;
4588 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4589 repo, worktree);
4590 if (error)
4591 goto done;
4593 init_curses();
4595 error = apply_unveil(got_repo_get_path(repo),
4596 worktree ? got_worktree_get_root_path(worktree) : NULL);
4597 if (error)
4598 goto done;
4600 /* already loaded by tog_log_with_path()? */
4601 if (TAILQ_EMPTY(&tog_refs)) {
4602 error = tog_load_refs(repo, 0);
4603 if (error)
4604 goto done;
4607 if (start_commit == NULL) {
4608 error = got_repo_match_object_id(&start_id, &label,
4609 worktree ? got_worktree_get_head_ref_name(worktree) :
4610 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4611 if (error)
4612 goto done;
4613 head_ref_name = label;
4614 } else {
4615 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4616 repo, worktree);
4617 if (error != NULL)
4618 goto done;
4619 if (keyword_idstr != NULL)
4620 start_commit = keyword_idstr;
4622 error = got_ref_open(&ref, repo, start_commit, 0);
4623 if (error == NULL)
4624 head_ref_name = got_ref_get_name(ref);
4625 else if (error->code != GOT_ERR_NOT_REF)
4626 goto done;
4627 error = got_repo_match_object_id(&start_id, NULL,
4628 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4629 if (error)
4630 goto done;
4633 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4634 if (view == NULL) {
4635 error = got_error_from_errno("view_open");
4636 goto done;
4639 if (worktree) {
4640 error = set_tog_base_commit(repo, worktree);
4641 if (error != NULL)
4642 goto done;
4645 error = open_log_view(view, start_id, repo, head_ref_name,
4646 in_repo_path, log_branches, worktree);
4647 if (error)
4648 goto done;
4650 if (worktree) {
4651 /* The work tree will be closed by the log thread. */
4652 worktree = NULL;
4655 error = view_loop(view);
4657 done:
4658 free(tog_base_commit.id);
4659 free(keyword_idstr);
4660 free(in_repo_path);
4661 free(repo_path);
4662 free(cwd);
4663 free(start_id);
4664 free(label);
4665 if (ref)
4666 got_ref_close(ref);
4667 if (repo) {
4668 const struct got_error *close_err = got_repo_close(repo);
4669 if (error == NULL)
4670 error = close_err;
4672 if (worktree)
4673 got_worktree_close(worktree);
4674 if (pack_fds) {
4675 const struct got_error *pack_err =
4676 got_repo_pack_fds_close(pack_fds);
4677 if (error == NULL)
4678 error = pack_err;
4680 tog_free_refs();
4681 return error;
4684 __dead static void
4685 usage_diff(void)
4687 endwin();
4688 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4689 "object1 object2\n", getprogname());
4690 exit(1);
4693 static int
4694 match_line(const char *line, regex_t *regex, size_t nmatch,
4695 regmatch_t *regmatch)
4697 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4700 static struct tog_color *
4701 match_color(struct tog_colors *colors, const char *line)
4703 struct tog_color *tc = NULL;
4705 STAILQ_FOREACH(tc, colors, entry) {
4706 if (match_line(line, &tc->regex, 0, NULL))
4707 return tc;
4710 return NULL;
4713 static const struct got_error *
4714 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4715 WINDOW *window, int skipcol, regmatch_t *regmatch)
4717 const struct got_error *err = NULL;
4718 char *exstr = NULL;
4719 wchar_t *wline = NULL;
4720 int rme, rms, n, width, scrollx;
4721 int width0 = 0, width1 = 0, width2 = 0;
4722 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4724 *wtotal = 0;
4726 rms = regmatch->rm_so;
4727 rme = regmatch->rm_eo;
4729 err = expand_tab(&exstr, line);
4730 if (err)
4731 return err;
4733 /* Split the line into 3 segments, according to match offsets. */
4734 seg0 = strndup(exstr, rms);
4735 if (seg0 == NULL) {
4736 err = got_error_from_errno("strndup");
4737 goto done;
4739 seg1 = strndup(exstr + rms, rme - rms);
4740 if (seg1 == NULL) {
4741 err = got_error_from_errno("strndup");
4742 goto done;
4744 seg2 = strdup(exstr + rme);
4745 if (seg2 == NULL) {
4746 err = got_error_from_errno("strndup");
4747 goto done;
4750 /* draw up to matched token if we haven't scrolled past it */
4751 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4752 col_tab_align, 1);
4753 if (err)
4754 goto done;
4755 n = MAX(width0 - skipcol, 0);
4756 if (n) {
4757 free(wline);
4758 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4759 wlimit, col_tab_align, 1);
4760 if (err)
4761 goto done;
4762 waddwstr(window, &wline[scrollx]);
4763 wlimit -= width;
4764 *wtotal += width;
4767 if (wlimit > 0) {
4768 int i = 0, w = 0;
4769 size_t wlen;
4771 free(wline);
4772 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4773 col_tab_align, 1);
4774 if (err)
4775 goto done;
4776 wlen = wcslen(wline);
4777 while (i < wlen) {
4778 width = wcwidth(wline[i]);
4779 if (width == -1) {
4780 /* should not happen, tabs are expanded */
4781 err = got_error(GOT_ERR_RANGE);
4782 goto done;
4784 if (width0 + w + width > skipcol)
4785 break;
4786 w += width;
4787 i++;
4789 /* draw (visible part of) matched token (if scrolled into it) */
4790 if (width1 - w > 0) {
4791 wattron(window, A_STANDOUT);
4792 waddwstr(window, &wline[i]);
4793 wattroff(window, A_STANDOUT);
4794 wlimit -= (width1 - w);
4795 *wtotal += (width1 - w);
4799 if (wlimit > 0) { /* draw rest of line */
4800 free(wline);
4801 if (skipcol > width0 + width1) {
4802 err = format_line(&wline, &width2, &scrollx, seg2,
4803 skipcol - (width0 + width1), wlimit,
4804 col_tab_align, 1);
4805 if (err)
4806 goto done;
4807 waddwstr(window, &wline[scrollx]);
4808 } else {
4809 err = format_line(&wline, &width2, NULL, seg2, 0,
4810 wlimit, col_tab_align, 1);
4811 if (err)
4812 goto done;
4813 waddwstr(window, wline);
4815 *wtotal += width2;
4817 done:
4818 free(wline);
4819 free(exstr);
4820 free(seg0);
4821 free(seg1);
4822 free(seg2);
4823 return err;
4826 static int
4827 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4829 FILE *f = NULL;
4830 int *eof, *first, *selected;
4832 if (view->type == TOG_VIEW_DIFF) {
4833 struct tog_diff_view_state *s = &view->state.diff;
4835 first = &s->first_displayed_line;
4836 selected = first;
4837 eof = &s->eof;
4838 f = s->f;
4839 } else if (view->type == TOG_VIEW_HELP) {
4840 struct tog_help_view_state *s = &view->state.help;
4842 first = &s->first_displayed_line;
4843 selected = first;
4844 eof = &s->eof;
4845 f = s->f;
4846 } else if (view->type == TOG_VIEW_BLAME) {
4847 struct tog_blame_view_state *s = &view->state.blame;
4849 first = &s->first_displayed_line;
4850 selected = &s->selected_line;
4851 eof = &s->eof;
4852 f = s->blame.f;
4853 } else
4854 return 0;
4856 /* Center gline in the middle of the page like vi(1). */
4857 if (*lineno < view->gline - (view->nlines - 3) / 2)
4858 return 0;
4859 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4860 rewind(f);
4861 *eof = 0;
4862 *first = 1;
4863 *lineno = 0;
4864 *nprinted = 0;
4865 return 0;
4868 *selected = view->gline <= (view->nlines - 3) / 2 ?
4869 view->gline : (view->nlines - 3) / 2 + 1;
4870 view->gline = 0;
4872 return 1;
4875 static const struct got_error *
4876 draw_file(struct tog_view *view, const char *header)
4878 struct tog_diff_view_state *s = &view->state.diff;
4879 regmatch_t *regmatch = &view->regmatch;
4880 const struct got_error *err;
4881 int nprinted = 0;
4882 char *line;
4883 size_t linesize = 0;
4884 ssize_t linelen;
4885 wchar_t *wline;
4886 int width;
4887 int max_lines = view->nlines;
4888 int nlines = s->nlines;
4889 off_t line_offset;
4891 s->lineno = s->first_displayed_line - 1;
4892 line_offset = s->lines[s->first_displayed_line - 1].offset;
4893 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4894 return got_error_from_errno("fseek");
4896 werase(view->window);
4898 if (view->gline > s->nlines - 1)
4899 view->gline = s->nlines - 1;
4901 if (header) {
4902 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4903 1 : view->gline - (view->nlines - 3) / 2 :
4904 s->lineno + s->selected_line;
4906 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4907 return got_error_from_errno("asprintf");
4908 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4909 0, 0);
4910 free(line);
4911 if (err)
4912 return err;
4914 if (view_needs_focus_indication(view))
4915 wstandout(view->window);
4916 waddwstr(view->window, wline);
4917 free(wline);
4918 wline = NULL;
4919 while (width++ < view->ncols)
4920 waddch(view->window, ' ');
4921 if (view_needs_focus_indication(view))
4922 wstandend(view->window);
4924 if (max_lines <= 1)
4925 return NULL;
4926 max_lines--;
4929 s->eof = 0;
4930 view->maxx = 0;
4931 line = NULL;
4932 while (max_lines > 0 && nprinted < max_lines) {
4933 enum got_diff_line_type linetype;
4934 attr_t attr = 0;
4936 linelen = getline(&line, &linesize, s->f);
4937 if (linelen == -1) {
4938 if (feof(s->f)) {
4939 s->eof = 1;
4940 break;
4942 free(line);
4943 return got_ferror(s->f, GOT_ERR_IO);
4946 if (++s->lineno < s->first_displayed_line)
4947 continue;
4948 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4949 continue;
4950 if (s->lineno == view->hiline)
4951 attr = A_STANDOUT;
4953 /* Set view->maxx based on full line length. */
4954 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4955 view->x ? 1 : 0);
4956 if (err) {
4957 free(line);
4958 return err;
4960 view->maxx = MAX(view->maxx, width);
4961 free(wline);
4962 wline = NULL;
4964 linetype = s->lines[s->lineno].type;
4965 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4966 linetype < GOT_DIFF_LINE_CONTEXT)
4967 attr |= COLOR_PAIR(linetype);
4968 if (attr)
4969 wattron(view->window, attr);
4970 if (s->first_displayed_line + nprinted == s->matched_line &&
4971 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4972 err = add_matched_line(&width, line, view->ncols, 0,
4973 view->window, view->x, regmatch);
4974 if (err) {
4975 free(line);
4976 return err;
4978 } else {
4979 int skip;
4980 err = format_line(&wline, &width, &skip, line,
4981 view->x, view->ncols, 0, view->x ? 1 : 0);
4982 if (err) {
4983 free(line);
4984 return err;
4986 waddwstr(view->window, &wline[skip]);
4987 free(wline);
4988 wline = NULL;
4990 if (s->lineno == view->hiline) {
4991 /* highlight full gline length */
4992 while (width++ < view->ncols)
4993 waddch(view->window, ' ');
4994 } else {
4995 if (width <= view->ncols - 1)
4996 waddch(view->window, '\n');
4998 if (attr)
4999 wattroff(view->window, attr);
5000 if (++nprinted == 1)
5001 s->first_displayed_line = s->lineno;
5003 free(line);
5004 if (nprinted >= 1)
5005 s->last_displayed_line = s->first_displayed_line +
5006 (nprinted - 1);
5007 else
5008 s->last_displayed_line = s->first_displayed_line;
5010 view_border(view);
5012 if (s->eof) {
5013 while (nprinted < view->nlines) {
5014 waddch(view->window, '\n');
5015 nprinted++;
5018 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
5019 view->ncols, 0, 0);
5020 if (err) {
5021 return err;
5024 wstandout(view->window);
5025 waddwstr(view->window, wline);
5026 free(wline);
5027 wline = NULL;
5028 wstandend(view->window);
5031 return NULL;
5034 static char *
5035 get_datestr(time_t *time, char *datebuf)
5037 struct tm mytm, *tm;
5038 char *p, *s;
5040 tm = gmtime_r(time, &mytm);
5041 if (tm == NULL)
5042 return NULL;
5043 s = asctime_r(tm, datebuf);
5044 if (s == NULL)
5045 return NULL;
5046 p = strchr(s, '\n');
5047 if (p)
5048 *p = '\0';
5049 return s;
5052 static const struct got_error *
5053 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
5054 off_t off, uint8_t type)
5056 struct got_diff_line *p;
5058 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
5059 if (p == NULL)
5060 return got_error_from_errno("reallocarray");
5061 *lines = p;
5062 (*lines)[*nlines].offset = off;
5063 (*lines)[*nlines].type = type;
5064 (*nlines)++;
5066 return NULL;
5069 static const struct got_error *
5070 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
5071 struct got_diff_line *s_lines, size_t s_nlines)
5073 struct got_diff_line *p;
5074 char buf[BUFSIZ];
5075 size_t i, r;
5077 if (fseeko(src, 0L, SEEK_SET) == -1)
5078 return got_error_from_errno("fseeko");
5080 for (;;) {
5081 r = fread(buf, 1, sizeof(buf), src);
5082 if (r == 0) {
5083 if (ferror(src))
5084 return got_error_from_errno("fread");
5085 if (feof(src))
5086 break;
5088 if (fwrite(buf, 1, r, dst) != r)
5089 return got_ferror(dst, GOT_ERR_IO);
5092 if (s_nlines == 0 && *d_nlines == 0)
5093 return NULL;
5096 * If commit info was in dst, increment line offsets
5097 * of the appended diff content, but skip s_lines[0]
5098 * because offset zero is already in *d_lines.
5100 if (*d_nlines > 0) {
5101 for (i = 1; i < s_nlines; ++i)
5102 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
5104 if (s_nlines > 0) {
5105 --s_nlines;
5106 ++s_lines;
5110 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
5111 if (p == NULL) {
5112 /* d_lines is freed in close_diff_view() */
5113 return got_error_from_errno("reallocarray");
5116 *d_lines = p;
5118 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
5119 *d_nlines += s_nlines;
5121 return NULL;
5124 static const struct got_error *
5125 write_commit_info(struct got_diff_line **lines, size_t *nlines,
5126 struct got_object_id *commit_id, struct got_reflist_head *refs,
5127 struct got_repository *repo, int ignore_ws, int force_text_diff,
5128 struct got_diffstat_cb_arg *dsa, FILE *outfile)
5130 const struct got_error *err = NULL;
5131 char datebuf[26], *datestr;
5132 struct got_commit_object *commit;
5133 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
5134 time_t committer_time;
5135 const char *author, *committer;
5136 char *refs_str = NULL;
5137 struct got_pathlist_entry *pe;
5138 off_t outoff = 0;
5139 int n;
5141 err = build_refs_str(&refs_str, refs, commit_id, repo);
5142 if (err)
5143 return err;
5145 err = got_object_open_as_commit(&commit, repo, commit_id);
5146 if (err)
5147 return err;
5149 err = got_object_id_str(&id_str, commit_id);
5150 if (err) {
5151 err = got_error_from_errno("got_object_id_str");
5152 goto done;
5155 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
5156 if (err)
5157 goto done;
5159 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
5160 refs_str ? refs_str : "", refs_str ? ")" : "");
5161 if (n < 0) {
5162 err = got_error_from_errno("fprintf");
5163 goto done;
5165 outoff += n;
5166 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
5167 if (err)
5168 goto done;
5170 n = fprintf(outfile, "from: %s\n",
5171 got_object_commit_get_author(commit));
5172 if (n < 0) {
5173 err = got_error_from_errno("fprintf");
5174 goto done;
5176 outoff += n;
5177 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5178 if (err)
5179 goto done;
5181 author = got_object_commit_get_author(commit);
5182 committer = got_object_commit_get_committer(commit);
5183 if (strcmp(author, committer) != 0) {
5184 n = fprintf(outfile, "via: %s\n", committer);
5185 if (n < 0) {
5186 err = got_error_from_errno("fprintf");
5187 goto done;
5189 outoff += n;
5190 err = add_line_metadata(lines, nlines, outoff,
5191 GOT_DIFF_LINE_AUTHOR);
5192 if (err)
5193 goto done;
5195 committer_time = got_object_commit_get_committer_time(commit);
5196 datestr = get_datestr(&committer_time, datebuf);
5197 if (datestr) {
5198 n = fprintf(outfile, "date: %s UTC\n", datestr);
5199 if (n < 0) {
5200 err = got_error_from_errno("fprintf");
5201 goto done;
5203 outoff += n;
5204 err = add_line_metadata(lines, nlines, outoff,
5205 GOT_DIFF_LINE_DATE);
5206 if (err)
5207 goto done;
5209 if (got_object_commit_get_nparents(commit) > 1) {
5210 const struct got_object_id_queue *parent_ids;
5211 struct got_object_qid *qid;
5212 int pn = 1;
5213 parent_ids = got_object_commit_get_parent_ids(commit);
5214 STAILQ_FOREACH(qid, parent_ids, entry) {
5215 err = got_object_id_str(&id_str, &qid->id);
5216 if (err)
5217 goto done;
5218 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5219 if (n < 0) {
5220 err = got_error_from_errno("fprintf");
5221 goto done;
5223 outoff += n;
5224 err = add_line_metadata(lines, nlines, outoff,
5225 GOT_DIFF_LINE_META);
5226 if (err)
5227 goto done;
5228 free(id_str);
5229 id_str = NULL;
5233 err = got_object_commit_get_logmsg(&logmsg, commit);
5234 if (err)
5235 goto done;
5236 s = logmsg;
5237 while ((line = strsep(&s, "\n")) != NULL) {
5238 n = fprintf(outfile, "%s\n", line);
5239 if (n < 0) {
5240 err = got_error_from_errno("fprintf");
5241 goto done;
5243 outoff += n;
5244 err = add_line_metadata(lines, nlines, outoff,
5245 GOT_DIFF_LINE_LOGMSG);
5246 if (err)
5247 goto done;
5250 TAILQ_FOREACH(pe, dsa->paths, entry) {
5251 struct got_diff_changed_path *cp = pe->data;
5252 int pad = dsa->max_path_len - pe->path_len + 1;
5254 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5255 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5256 dsa->rm_cols + 1, cp->rm);
5257 if (n < 0) {
5258 err = got_error_from_errno("fprintf");
5259 goto done;
5261 outoff += n;
5262 err = add_line_metadata(lines, nlines, outoff,
5263 GOT_DIFF_LINE_CHANGES);
5264 if (err)
5265 goto done;
5268 fputc('\n', outfile);
5269 outoff++;
5270 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5271 if (err)
5272 goto done;
5274 n = fprintf(outfile,
5275 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5276 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5277 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5278 if (n < 0) {
5279 err = got_error_from_errno("fprintf");
5280 goto done;
5282 outoff += n;
5283 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5284 if (err)
5285 goto done;
5287 fputc('\n', outfile);
5288 outoff++;
5289 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5290 done:
5291 free(id_str);
5292 free(logmsg);
5293 free(refs_str);
5294 got_object_commit_close(commit);
5295 if (err) {
5296 free(*lines);
5297 *lines = NULL;
5298 *nlines = 0;
5300 return err;
5303 static const struct got_error *
5304 create_diff(struct tog_diff_view_state *s)
5306 const struct got_error *err = NULL;
5307 FILE *f = NULL, *tmp_diff_file = NULL;
5308 int obj_type;
5309 struct got_diff_line *lines = NULL;
5310 struct got_pathlist_head changed_paths;
5312 TAILQ_INIT(&changed_paths);
5314 free(s->lines);
5315 s->lines = malloc(sizeof(*s->lines));
5316 if (s->lines == NULL)
5317 return got_error_from_errno("malloc");
5318 s->nlines = 0;
5320 f = got_opentemp();
5321 if (f == NULL) {
5322 err = got_error_from_errno("got_opentemp");
5323 goto done;
5325 tmp_diff_file = got_opentemp();
5326 if (tmp_diff_file == NULL) {
5327 err = got_error_from_errno("got_opentemp");
5328 goto done;
5330 if (s->f && fclose(s->f) == EOF) {
5331 err = got_error_from_errno("fclose");
5332 goto done;
5334 s->f = f;
5336 if (s->id1)
5337 err = got_object_get_type(&obj_type, s->repo, s->id1);
5338 else
5339 err = got_object_get_type(&obj_type, s->repo, s->id2);
5340 if (err)
5341 goto done;
5343 switch (obj_type) {
5344 case GOT_OBJ_TYPE_BLOB:
5345 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5346 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5347 s->label1, s->label2, tog_diff_algo, s->diff_context,
5348 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5349 s->f);
5350 break;
5351 case GOT_OBJ_TYPE_TREE:
5352 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5353 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5354 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5355 s->force_text_diff, NULL, s->repo, s->f);
5356 break;
5357 case GOT_OBJ_TYPE_COMMIT: {
5358 const struct got_object_id_queue *parent_ids;
5359 struct got_object_qid *pid;
5360 struct got_commit_object *commit2;
5361 struct got_reflist_head *refs;
5362 size_t nlines = 0;
5363 struct got_diffstat_cb_arg dsa = {
5364 0, 0, 0, 0, 0, 0,
5365 &changed_paths,
5366 s->ignore_whitespace,
5367 s->force_text_diff,
5368 tog_diff_algo
5371 lines = malloc(sizeof(*lines));
5372 if (lines == NULL) {
5373 err = got_error_from_errno("malloc");
5374 goto done;
5377 /* build diff first in tmp file then append to commit info */
5378 err = got_diff_objects_as_commits(&lines, &nlines,
5379 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5380 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5381 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5382 if (err)
5383 break;
5385 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5386 if (err)
5387 goto done;
5388 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5389 /* Show commit info if we're diffing to a parent/root commit. */
5390 if (s->id1 == NULL) {
5391 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5392 refs, s->repo, s->ignore_whitespace,
5393 s->force_text_diff, &dsa, s->f);
5394 if (err)
5395 goto done;
5396 } else {
5397 parent_ids = got_object_commit_get_parent_ids(commit2);
5398 STAILQ_FOREACH(pid, parent_ids, entry) {
5399 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5400 err = write_commit_info(&s->lines,
5401 &s->nlines, s->id2, refs, s->repo,
5402 s->ignore_whitespace,
5403 s->force_text_diff, &dsa, s->f);
5404 if (err)
5405 goto done;
5406 break;
5410 got_object_commit_close(commit2);
5412 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5413 lines, nlines);
5414 break;
5416 default:
5417 err = got_error(GOT_ERR_OBJ_TYPE);
5418 break;
5420 done:
5421 free(lines);
5422 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5423 if (s->f && fflush(s->f) != 0 && err == NULL)
5424 err = got_error_from_errno("fflush");
5425 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5426 err = got_error_from_errno("fclose");
5427 return err;
5430 static void
5431 diff_view_indicate_progress(struct tog_view *view)
5433 mvwaddstr(view->window, 0, 0, "diffing...");
5434 update_panels();
5435 doupdate();
5438 static const struct got_error *
5439 search_start_diff_view(struct tog_view *view)
5441 struct tog_diff_view_state *s = &view->state.diff;
5443 s->matched_line = 0;
5444 return NULL;
5447 static void
5448 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5449 size_t *nlines, int **first, int **last, int **match, int **selected)
5451 struct tog_diff_view_state *s = &view->state.diff;
5453 *f = s->f;
5454 *nlines = s->nlines;
5455 *line_offsets = NULL;
5456 *match = &s->matched_line;
5457 *first = &s->first_displayed_line;
5458 *last = &s->last_displayed_line;
5459 *selected = &s->selected_line;
5462 static const struct got_error *
5463 search_next_view_match(struct tog_view *view)
5465 const struct got_error *err = NULL;
5466 FILE *f;
5467 int lineno;
5468 char *line = NULL;
5469 size_t linesize = 0;
5470 ssize_t linelen;
5471 off_t *line_offsets;
5472 size_t nlines = 0;
5473 int *first, *last, *match, *selected;
5475 if (!view->search_setup)
5476 return got_error_msg(GOT_ERR_NOT_IMPL,
5477 "view search not supported");
5478 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5479 &match, &selected);
5481 if (!view->searching) {
5482 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5483 return NULL;
5486 if (*match) {
5487 if (view->searching == TOG_SEARCH_FORWARD)
5488 lineno = *first + 1;
5489 else
5490 lineno = *first - 1;
5491 } else
5492 lineno = *first - 1 + *selected;
5494 while (1) {
5495 off_t offset;
5497 if (lineno <= 0 || lineno > nlines) {
5498 if (*match == 0) {
5499 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5500 break;
5503 if (view->searching == TOG_SEARCH_FORWARD)
5504 lineno = 1;
5505 else
5506 lineno = nlines;
5509 offset = view->type == TOG_VIEW_DIFF ?
5510 view->state.diff.lines[lineno - 1].offset :
5511 line_offsets[lineno - 1];
5512 if (fseeko(f, offset, SEEK_SET) != 0) {
5513 free(line);
5514 return got_error_from_errno("fseeko");
5516 linelen = getline(&line, &linesize, f);
5517 if (linelen != -1) {
5518 char *exstr;
5519 err = expand_tab(&exstr, line);
5520 if (err)
5521 break;
5522 if (match_line(exstr, &view->regex, 1,
5523 &view->regmatch)) {
5524 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5525 *match = lineno;
5526 free(exstr);
5527 break;
5529 free(exstr);
5531 if (view->searching == TOG_SEARCH_FORWARD)
5532 lineno++;
5533 else
5534 lineno--;
5536 free(line);
5538 if (*match) {
5539 *first = *match;
5540 *selected = 1;
5543 return err;
5546 static const struct got_error *
5547 close_diff_view(struct tog_view *view)
5549 const struct got_error *err = NULL;
5550 struct tog_diff_view_state *s = &view->state.diff;
5552 free(s->id1);
5553 s->id1 = NULL;
5554 free(s->id2);
5555 s->id2 = NULL;
5556 if (s->f && fclose(s->f) == EOF)
5557 err = got_error_from_errno("fclose");
5558 s->f = NULL;
5559 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5560 err = got_error_from_errno("fclose");
5561 s->f1 = NULL;
5562 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5563 err = got_error_from_errno("fclose");
5564 s->f2 = NULL;
5565 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5566 err = got_error_from_errno("close");
5567 s->fd1 = -1;
5568 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5569 err = got_error_from_errno("close");
5570 s->fd2 = -1;
5571 free(s->lines);
5572 s->lines = NULL;
5573 s->nlines = 0;
5574 return err;
5577 static const struct got_error *
5578 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5579 struct got_object_id *id2, const char *label1, const char *label2,
5580 int diff_context, int ignore_whitespace, int force_text_diff,
5581 struct tog_view *parent_view, struct got_repository *repo)
5583 const struct got_error *err;
5584 struct tog_diff_view_state *s = &view->state.diff;
5586 memset(s, 0, sizeof(*s));
5587 s->fd1 = -1;
5588 s->fd2 = -1;
5590 if (id1 != NULL && id2 != NULL) {
5591 int type1, type2;
5593 err = got_object_get_type(&type1, repo, id1);
5594 if (err)
5595 goto done;
5596 err = got_object_get_type(&type2, repo, id2);
5597 if (err)
5598 goto done;
5600 if (type1 != type2) {
5601 err = got_error(GOT_ERR_OBJ_TYPE);
5602 goto done;
5605 s->first_displayed_line = 1;
5606 s->last_displayed_line = view->nlines;
5607 s->selected_line = 1;
5608 s->repo = repo;
5609 s->id1 = id1;
5610 s->id2 = id2;
5611 s->label1 = label1;
5612 s->label2 = label2;
5614 if (id1) {
5615 s->id1 = got_object_id_dup(id1);
5616 if (s->id1 == NULL) {
5617 err = got_error_from_errno("got_object_id_dup");
5618 goto done;
5620 } else
5621 s->id1 = NULL;
5623 s->id2 = got_object_id_dup(id2);
5624 if (s->id2 == NULL) {
5625 err = got_error_from_errno("got_object_id_dup");
5626 goto done;
5629 s->f1 = got_opentemp();
5630 if (s->f1 == NULL) {
5631 err = got_error_from_errno("got_opentemp");
5632 goto done;
5635 s->f2 = got_opentemp();
5636 if (s->f2 == NULL) {
5637 err = got_error_from_errno("got_opentemp");
5638 goto done;
5641 s->fd1 = got_opentempfd();
5642 if (s->fd1 == -1) {
5643 err = got_error_from_errno("got_opentempfd");
5644 goto done;
5647 s->fd2 = got_opentempfd();
5648 if (s->fd2 == -1) {
5649 err = got_error_from_errno("got_opentempfd");
5650 goto done;
5653 s->diff_context = diff_context;
5654 s->ignore_whitespace = ignore_whitespace;
5655 s->force_text_diff = force_text_diff;
5656 s->parent_view = parent_view;
5657 s->repo = repo;
5659 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5660 int rc;
5662 rc = init_pair(GOT_DIFF_LINE_MINUS,
5663 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5664 if (rc != ERR)
5665 rc = init_pair(GOT_DIFF_LINE_PLUS,
5666 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5667 if (rc != ERR)
5668 rc = init_pair(GOT_DIFF_LINE_HUNK,
5669 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5670 if (rc != ERR)
5671 rc = init_pair(GOT_DIFF_LINE_META,
5672 get_color_value("TOG_COLOR_DIFF_META"), -1);
5673 if (rc != ERR)
5674 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5675 get_color_value("TOG_COLOR_DIFF_META"), -1);
5676 if (rc != ERR)
5677 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5678 get_color_value("TOG_COLOR_DIFF_META"), -1);
5679 if (rc != ERR)
5680 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5681 get_color_value("TOG_COLOR_DIFF_META"), -1);
5682 if (rc != ERR)
5683 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5684 get_color_value("TOG_COLOR_AUTHOR"), -1);
5685 if (rc != ERR)
5686 rc = init_pair(GOT_DIFF_LINE_DATE,
5687 get_color_value("TOG_COLOR_DATE"), -1);
5688 if (rc == ERR) {
5689 err = got_error(GOT_ERR_RANGE);
5690 goto done;
5694 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5695 view_is_splitscreen(view))
5696 show_log_view(parent_view); /* draw border */
5697 diff_view_indicate_progress(view);
5699 err = create_diff(s);
5701 view->show = show_diff_view;
5702 view->input = input_diff_view;
5703 view->reset = reset_diff_view;
5704 view->close = close_diff_view;
5705 view->search_start = search_start_diff_view;
5706 view->search_setup = search_setup_diff_view;
5707 view->search_next = search_next_view_match;
5708 done:
5709 if (err) {
5710 if (view->close == NULL)
5711 close_diff_view(view);
5712 view_close(view);
5714 return err;
5717 static const struct got_error *
5718 show_diff_view(struct tog_view *view)
5720 const struct got_error *err;
5721 struct tog_diff_view_state *s = &view->state.diff;
5722 char *id_str1 = NULL, *id_str2, *header;
5723 const char *label1, *label2;
5725 if (s->id1) {
5726 err = got_object_id_str(&id_str1, s->id1);
5727 if (err)
5728 return err;
5729 label1 = s->label1 ? s->label1 : id_str1;
5730 } else
5731 label1 = "/dev/null";
5733 err = got_object_id_str(&id_str2, s->id2);
5734 if (err)
5735 return err;
5736 label2 = s->label2 ? s->label2 : id_str2;
5738 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5739 err = got_error_from_errno("asprintf");
5740 free(id_str1);
5741 free(id_str2);
5742 return err;
5744 free(id_str1);
5745 free(id_str2);
5747 err = draw_file(view, header);
5748 free(header);
5749 return err;
5752 static const struct got_error *
5753 set_selected_commit(struct tog_diff_view_state *s,
5754 struct commit_queue_entry *entry)
5756 const struct got_error *err;
5757 const struct got_object_id_queue *parent_ids;
5758 struct got_commit_object *selected_commit;
5759 struct got_object_qid *pid;
5761 free(s->id2);
5762 s->id2 = got_object_id_dup(entry->id);
5763 if (s->id2 == NULL)
5764 return got_error_from_errno("got_object_id_dup");
5766 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5767 if (err)
5768 return err;
5769 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5770 free(s->id1);
5771 pid = STAILQ_FIRST(parent_ids);
5772 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5773 got_object_commit_close(selected_commit);
5774 return NULL;
5777 static const struct got_error *
5778 reset_diff_view(struct tog_view *view)
5780 struct tog_diff_view_state *s = &view->state.diff;
5782 view->count = 0;
5783 wclear(view->window);
5784 s->first_displayed_line = 1;
5785 s->last_displayed_line = view->nlines;
5786 s->matched_line = 0;
5787 diff_view_indicate_progress(view);
5788 return create_diff(s);
5791 static void
5792 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5794 int start, i;
5796 i = start = s->first_displayed_line - 1;
5798 while (s->lines[i].type != type) {
5799 if (i == 0)
5800 i = s->nlines - 1;
5801 if (--i == start)
5802 return; /* do nothing, requested type not in file */
5805 s->selected_line = 1;
5806 s->first_displayed_line = i;
5809 static void
5810 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5812 int start, i;
5814 i = start = s->first_displayed_line + 1;
5816 while (s->lines[i].type != type) {
5817 if (i == s->nlines - 1)
5818 i = 0;
5819 if (++i == start)
5820 return; /* do nothing, requested type not in file */
5823 s->selected_line = 1;
5824 s->first_displayed_line = i;
5827 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5828 int, int, int);
5829 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5830 int, int);
5832 static const struct got_error *
5833 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5835 const struct got_error *err = NULL;
5836 struct tog_diff_view_state *s = &view->state.diff;
5837 struct tog_log_view_state *ls;
5838 struct commit_queue_entry *old_selected_entry;
5839 char *line = NULL;
5840 size_t linesize = 0;
5841 ssize_t linelen;
5842 int i, nscroll = view->nlines - 1, up = 0;
5844 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5846 switch (ch) {
5847 case '0':
5848 case '$':
5849 case KEY_RIGHT:
5850 case 'l':
5851 case KEY_LEFT:
5852 case 'h':
5853 horizontal_scroll_input(view, ch);
5854 break;
5855 case 'a':
5856 case 'w':
5857 if (ch == 'a') {
5858 s->force_text_diff = !s->force_text_diff;
5859 view->action = s->force_text_diff ?
5860 "force ASCII text enabled" :
5861 "force ASCII text disabled";
5863 else if (ch == 'w') {
5864 s->ignore_whitespace = !s->ignore_whitespace;
5865 view->action = s->ignore_whitespace ?
5866 "ignore whitespace enabled" :
5867 "ignore whitespace disabled";
5869 err = reset_diff_view(view);
5870 break;
5871 case 'g':
5872 case KEY_HOME:
5873 s->first_displayed_line = 1;
5874 view->count = 0;
5875 break;
5876 case 'G':
5877 case KEY_END:
5878 view->count = 0;
5879 if (s->eof)
5880 break;
5882 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5883 s->eof = 1;
5884 break;
5885 case 'k':
5886 case KEY_UP:
5887 case CTRL('p'):
5888 if (s->first_displayed_line > 1)
5889 s->first_displayed_line--;
5890 else
5891 view->count = 0;
5892 break;
5893 case CTRL('u'):
5894 case 'u':
5895 nscroll /= 2;
5896 /* FALL THROUGH */
5897 case KEY_PPAGE:
5898 case CTRL('b'):
5899 case 'b':
5900 if (s->first_displayed_line == 1) {
5901 view->count = 0;
5902 break;
5904 i = 0;
5905 while (i++ < nscroll && s->first_displayed_line > 1)
5906 s->first_displayed_line--;
5907 break;
5908 case 'j':
5909 case KEY_DOWN:
5910 case CTRL('n'):
5911 if (!s->eof)
5912 s->first_displayed_line++;
5913 else
5914 view->count = 0;
5915 break;
5916 case CTRL('d'):
5917 case 'd':
5918 nscroll /= 2;
5919 /* FALL THROUGH */
5920 case KEY_NPAGE:
5921 case CTRL('f'):
5922 case 'f':
5923 case ' ':
5924 if (s->eof) {
5925 view->count = 0;
5926 break;
5928 i = 0;
5929 while (!s->eof && i++ < nscroll) {
5930 linelen = getline(&line, &linesize, s->f);
5931 s->first_displayed_line++;
5932 if (linelen == -1) {
5933 if (feof(s->f)) {
5934 s->eof = 1;
5935 } else
5936 err = got_ferror(s->f, GOT_ERR_IO);
5937 break;
5940 free(line);
5941 break;
5942 case '(':
5943 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5944 break;
5945 case ')':
5946 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5947 break;
5948 case '{':
5949 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5950 break;
5951 case '}':
5952 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5953 break;
5954 case '[':
5955 if (s->diff_context > 0) {
5956 s->diff_context--;
5957 s->matched_line = 0;
5958 diff_view_indicate_progress(view);
5959 err = create_diff(s);
5960 if (s->first_displayed_line + view->nlines - 1 >
5961 s->nlines) {
5962 s->first_displayed_line = 1;
5963 s->last_displayed_line = view->nlines;
5965 } else
5966 view->count = 0;
5967 break;
5968 case ']':
5969 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5970 s->diff_context++;
5971 s->matched_line = 0;
5972 diff_view_indicate_progress(view);
5973 err = create_diff(s);
5974 } else
5975 view->count = 0;
5976 break;
5977 case '<':
5978 case ',':
5979 case 'K':
5980 up = 1;
5981 /* FALL THROUGH */
5982 case '>':
5983 case '.':
5984 case 'J':
5985 if (s->parent_view == NULL) {
5986 view->count = 0;
5987 break;
5989 s->parent_view->count = view->count;
5991 if (s->parent_view->type == TOG_VIEW_LOG) {
5992 ls = &s->parent_view->state.log;
5993 old_selected_entry = ls->selected_entry;
5995 err = input_log_view(NULL, s->parent_view,
5996 up ? KEY_UP : KEY_DOWN);
5997 if (err)
5998 break;
5999 view->count = s->parent_view->count;
6001 if (old_selected_entry == ls->selected_entry)
6002 break;
6004 err = set_selected_commit(s, ls->selected_entry);
6005 if (err)
6006 break;
6007 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
6008 struct tog_blame_view_state *bs;
6009 struct got_object_id *id, *prev_id;
6011 bs = &s->parent_view->state.blame;
6012 prev_id = get_annotation_for_line(bs->blame.lines,
6013 bs->blame.nlines, bs->last_diffed_line);
6015 err = input_blame_view(&view, s->parent_view,
6016 up ? KEY_UP : KEY_DOWN);
6017 if (err)
6018 break;
6019 view->count = s->parent_view->count;
6021 if (prev_id == NULL)
6022 break;
6023 id = get_selected_commit_id(bs->blame.lines,
6024 bs->blame.nlines, bs->first_displayed_line,
6025 bs->selected_line);
6026 if (id == NULL)
6027 break;
6029 if (!got_object_id_cmp(prev_id, id))
6030 break;
6032 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
6033 if (err)
6034 break;
6036 s->first_displayed_line = 1;
6037 s->last_displayed_line = view->nlines;
6038 s->matched_line = 0;
6039 view->x = 0;
6041 diff_view_indicate_progress(view);
6042 err = create_diff(s);
6043 break;
6044 default:
6045 view->count = 0;
6046 break;
6049 return err;
6052 static const struct got_error *
6053 cmd_diff(int argc, char *argv[])
6055 const struct got_error *error;
6056 struct got_repository *repo = NULL;
6057 struct got_worktree *worktree = NULL;
6058 struct got_object_id *id1 = NULL, *id2 = NULL;
6059 char *repo_path = NULL, *cwd = NULL;
6060 char *id_str1 = NULL, *id_str2 = NULL;
6061 char *keyword_idstr1 = NULL, *keyword_idstr2 = NULL;
6062 char *label1 = NULL, *label2 = NULL;
6063 int diff_context = 3, ignore_whitespace = 0;
6064 int ch, force_text_diff = 0;
6065 const char *errstr;
6066 struct tog_view *view;
6067 int *pack_fds = NULL;
6069 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
6070 switch (ch) {
6071 case 'a':
6072 force_text_diff = 1;
6073 break;
6074 case 'C':
6075 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
6076 &errstr);
6077 if (errstr != NULL)
6078 errx(1, "number of context lines is %s: %s",
6079 errstr, errstr);
6080 break;
6081 case 'r':
6082 repo_path = realpath(optarg, NULL);
6083 if (repo_path == NULL)
6084 return got_error_from_errno2("realpath",
6085 optarg);
6086 got_path_strip_trailing_slashes(repo_path);
6087 break;
6088 case 'w':
6089 ignore_whitespace = 1;
6090 break;
6091 default:
6092 usage_diff();
6093 /* NOTREACHED */
6097 argc -= optind;
6098 argv += optind;
6100 if (argc == 0) {
6101 usage_diff(); /* TODO show local worktree changes */
6102 } else if (argc == 2) {
6103 id_str1 = argv[0];
6104 id_str2 = argv[1];
6105 } else
6106 usage_diff();
6108 error = got_repo_pack_fds_open(&pack_fds);
6109 if (error)
6110 goto done;
6112 if (repo_path == NULL) {
6113 cwd = getcwd(NULL, 0);
6114 if (cwd == NULL)
6115 return got_error_from_errno("getcwd");
6116 error = got_worktree_open(&worktree, cwd, NULL);
6117 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6118 goto done;
6119 if (worktree)
6120 repo_path =
6121 strdup(got_worktree_get_repo_path(worktree));
6122 else
6123 repo_path = strdup(cwd);
6124 if (repo_path == NULL) {
6125 error = got_error_from_errno("strdup");
6126 goto done;
6130 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6131 if (error)
6132 goto done;
6134 init_curses();
6136 error = apply_unveil(got_repo_get_path(repo), NULL);
6137 if (error)
6138 goto done;
6140 error = tog_load_refs(repo, 0);
6141 if (error)
6142 goto done;
6144 if (id_str1 != NULL) {
6145 error = got_keyword_to_idstr(&keyword_idstr1, id_str1,
6146 repo, worktree);
6147 if (error != NULL)
6148 goto done;
6149 if (keyword_idstr1 != NULL)
6150 id_str1 = keyword_idstr1;
6152 if (id_str2 != NULL) {
6153 error = got_keyword_to_idstr(&keyword_idstr2, id_str2,
6154 repo, worktree);
6155 if (error != NULL)
6156 goto done;
6157 if (keyword_idstr2 != NULL)
6158 id_str2 = keyword_idstr2;
6161 error = got_repo_match_object_id(&id1, &label1, id_str1,
6162 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6163 if (error)
6164 goto done;
6166 error = got_repo_match_object_id(&id2, &label2, id_str2,
6167 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6168 if (error)
6169 goto done;
6171 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
6172 if (view == NULL) {
6173 error = got_error_from_errno("view_open");
6174 goto done;
6176 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
6177 ignore_whitespace, force_text_diff, NULL, repo);
6178 if (error)
6179 goto done;
6181 if (worktree) {
6182 error = set_tog_base_commit(repo, worktree);
6183 if (error != NULL)
6184 goto done;
6186 /* Release work tree lock. */
6187 got_worktree_close(worktree);
6188 worktree = NULL;
6191 error = view_loop(view);
6193 done:
6194 free(tog_base_commit.id);
6195 free(keyword_idstr1);
6196 free(keyword_idstr2);
6197 free(label1);
6198 free(label2);
6199 free(repo_path);
6200 free(cwd);
6201 if (repo) {
6202 const struct got_error *close_err = got_repo_close(repo);
6203 if (error == NULL)
6204 error = close_err;
6206 if (worktree)
6207 got_worktree_close(worktree);
6208 if (pack_fds) {
6209 const struct got_error *pack_err =
6210 got_repo_pack_fds_close(pack_fds);
6211 if (error == NULL)
6212 error = pack_err;
6214 tog_free_refs();
6215 return error;
6218 __dead static void
6219 usage_blame(void)
6221 endwin();
6222 fprintf(stderr,
6223 "usage: %s blame [-c commit] [-r repository-path] path\n",
6224 getprogname());
6225 exit(1);
6228 struct tog_blame_line {
6229 int annotated;
6230 struct got_object_id *id;
6233 static const struct got_error *
6234 draw_blame(struct tog_view *view)
6236 struct tog_blame_view_state *s = &view->state.blame;
6237 struct tog_blame *blame = &s->blame;
6238 regmatch_t *regmatch = &view->regmatch;
6239 const struct got_error *err;
6240 int lineno = 0, nprinted = 0;
6241 char *line = NULL;
6242 size_t linesize = 0;
6243 ssize_t linelen;
6244 wchar_t *wline;
6245 int width;
6246 struct tog_blame_line *blame_line;
6247 struct got_object_id *prev_id = NULL;
6248 char *id_str;
6249 struct tog_color *tc;
6251 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6252 if (err)
6253 return err;
6255 rewind(blame->f);
6256 werase(view->window);
6258 if (asprintf(&line, "commit %s", id_str) == -1) {
6259 err = got_error_from_errno("asprintf");
6260 free(id_str);
6261 return err;
6264 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6265 free(line);
6266 line = NULL;
6267 if (err)
6268 return err;
6269 if (view_needs_focus_indication(view))
6270 wstandout(view->window);
6271 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6272 if (tc)
6273 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6274 waddwstr(view->window, wline);
6275 while (width++ < view->ncols)
6276 waddch(view->window, ' ');
6277 if (tc)
6278 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6279 if (view_needs_focus_indication(view))
6280 wstandend(view->window);
6281 free(wline);
6282 wline = NULL;
6284 if (view->gline > blame->nlines)
6285 view->gline = blame->nlines;
6287 if (tog_io.wait_for_ui) {
6288 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6289 int rc;
6291 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6292 if (rc)
6293 return got_error_set_errno(rc, "pthread_cond_wait");
6294 tog_io.wait_for_ui = 0;
6297 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6298 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6299 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6300 free(id_str);
6301 return got_error_from_errno("asprintf");
6303 free(id_str);
6304 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6305 free(line);
6306 line = NULL;
6307 if (err)
6308 return err;
6309 waddwstr(view->window, wline);
6310 free(wline);
6311 wline = NULL;
6312 if (width < view->ncols - 1)
6313 waddch(view->window, '\n');
6315 s->eof = 0;
6316 view->maxx = 0;
6317 while (nprinted < view->nlines - 2) {
6318 linelen = getline(&line, &linesize, blame->f);
6319 if (linelen == -1) {
6320 if (feof(blame->f)) {
6321 s->eof = 1;
6322 break;
6324 free(line);
6325 return got_ferror(blame->f, GOT_ERR_IO);
6327 if (++lineno < s->first_displayed_line)
6328 continue;
6329 if (view->gline && !gotoline(view, &lineno, &nprinted))
6330 continue;
6332 /* Set view->maxx based on full line length. */
6333 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6334 if (err) {
6335 free(line);
6336 return err;
6338 free(wline);
6339 wline = NULL;
6340 view->maxx = MAX(view->maxx, width);
6342 if (nprinted == s->selected_line - 1)
6343 wstandout(view->window);
6345 if (blame->nlines > 0) {
6346 blame_line = &blame->lines[lineno - 1];
6347 if (blame_line->annotated && prev_id &&
6348 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6349 !(nprinted == s->selected_line - 1)) {
6350 waddstr(view->window, " ");
6351 } else if (blame_line->annotated) {
6352 char *id_str;
6353 err = got_object_id_str(&id_str,
6354 blame_line->id);
6355 if (err) {
6356 free(line);
6357 return err;
6359 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6360 if (tc)
6361 wattr_on(view->window,
6362 COLOR_PAIR(tc->colorpair), NULL);
6363 wprintw(view->window, "%.8s", id_str);
6364 if (tc)
6365 wattr_off(view->window,
6366 COLOR_PAIR(tc->colorpair), NULL);
6367 free(id_str);
6368 prev_id = blame_line->id;
6369 } else {
6370 waddstr(view->window, "........");
6371 prev_id = NULL;
6373 } else {
6374 waddstr(view->window, "........");
6375 prev_id = NULL;
6378 if (nprinted == s->selected_line - 1)
6379 wstandend(view->window);
6380 waddstr(view->window, " ");
6382 if (view->ncols <= 9) {
6383 width = 9;
6384 } else if (s->first_displayed_line + nprinted ==
6385 s->matched_line &&
6386 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6387 err = add_matched_line(&width, line, view->ncols - 9, 9,
6388 view->window, view->x, regmatch);
6389 if (err) {
6390 free(line);
6391 return err;
6393 width += 9;
6394 } else {
6395 int skip;
6396 err = format_line(&wline, &width, &skip, line,
6397 view->x, view->ncols - 9, 9, 1);
6398 if (err) {
6399 free(line);
6400 return err;
6402 waddwstr(view->window, &wline[skip]);
6403 width += 9;
6404 free(wline);
6405 wline = NULL;
6408 if (width <= view->ncols - 1)
6409 waddch(view->window, '\n');
6410 if (++nprinted == 1)
6411 s->first_displayed_line = lineno;
6413 free(line);
6414 s->last_displayed_line = lineno;
6416 view_border(view);
6418 return NULL;
6421 static const struct got_error *
6422 blame_cb(void *arg, int nlines, int lineno,
6423 struct got_commit_object *commit, struct got_object_id *id)
6425 const struct got_error *err = NULL;
6426 struct tog_blame_cb_args *a = arg;
6427 struct tog_blame_line *line;
6428 int errcode;
6430 if (nlines != a->nlines ||
6431 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6432 return got_error(GOT_ERR_RANGE);
6434 errcode = pthread_mutex_lock(&tog_mutex);
6435 if (errcode)
6436 return got_error_set_errno(errcode, "pthread_mutex_lock");
6438 if (*a->quit) { /* user has quit the blame view */
6439 err = got_error(GOT_ERR_ITER_COMPLETED);
6440 goto done;
6443 if (lineno == -1)
6444 goto done; /* no change in this commit */
6446 line = &a->lines[lineno - 1];
6447 if (line->annotated)
6448 goto done;
6450 line->id = got_object_id_dup(id);
6451 if (line->id == NULL) {
6452 err = got_error_from_errno("got_object_id_dup");
6453 goto done;
6455 line->annotated = 1;
6456 done:
6457 errcode = pthread_mutex_unlock(&tog_mutex);
6458 if (errcode)
6459 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6460 return err;
6463 static void *
6464 blame_thread(void *arg)
6466 const struct got_error *err, *close_err;
6467 struct tog_blame_thread_args *ta = arg;
6468 struct tog_blame_cb_args *a = ta->cb_args;
6469 int errcode, fd1 = -1, fd2 = -1;
6470 FILE *f1 = NULL, *f2 = NULL;
6472 fd1 = got_opentempfd();
6473 if (fd1 == -1)
6474 return (void *)got_error_from_errno("got_opentempfd");
6476 fd2 = got_opentempfd();
6477 if (fd2 == -1) {
6478 err = got_error_from_errno("got_opentempfd");
6479 goto done;
6482 f1 = got_opentemp();
6483 if (f1 == NULL) {
6484 err = (void *)got_error_from_errno("got_opentemp");
6485 goto done;
6487 f2 = got_opentemp();
6488 if (f2 == NULL) {
6489 err = (void *)got_error_from_errno("got_opentemp");
6490 goto done;
6493 err = block_signals_used_by_main_thread();
6494 if (err)
6495 goto done;
6497 err = got_blame(ta->path, a->commit_id, ta->repo,
6498 tog_diff_algo, blame_cb, ta->cb_args,
6499 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6500 if (err && err->code == GOT_ERR_CANCELLED)
6501 err = NULL;
6503 errcode = pthread_mutex_lock(&tog_mutex);
6504 if (errcode) {
6505 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6506 goto done;
6509 close_err = got_repo_close(ta->repo);
6510 if (err == NULL)
6511 err = close_err;
6512 ta->repo = NULL;
6513 *ta->complete = 1;
6515 if (tog_io.wait_for_ui) {
6516 errcode = pthread_cond_signal(&ta->blame_complete);
6517 if (errcode && err == NULL)
6518 err = got_error_set_errno(errcode,
6519 "pthread_cond_signal");
6522 errcode = pthread_mutex_unlock(&tog_mutex);
6523 if (errcode && err == NULL)
6524 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6526 done:
6527 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6528 err = got_error_from_errno("close");
6529 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6530 err = got_error_from_errno("close");
6531 if (f1 && fclose(f1) == EOF && err == NULL)
6532 err = got_error_from_errno("fclose");
6533 if (f2 && fclose(f2) == EOF && err == NULL)
6534 err = got_error_from_errno("fclose");
6536 return (void *)err;
6539 static struct got_object_id *
6540 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6541 int first_displayed_line, int selected_line)
6543 struct tog_blame_line *line;
6545 if (nlines <= 0)
6546 return NULL;
6548 line = &lines[first_displayed_line - 1 + selected_line - 1];
6549 if (!line->annotated)
6550 return NULL;
6552 return line->id;
6555 static struct got_object_id *
6556 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6557 int lineno)
6559 struct tog_blame_line *line;
6561 if (nlines <= 0 || lineno >= nlines)
6562 return NULL;
6564 line = &lines[lineno - 1];
6565 if (!line->annotated)
6566 return NULL;
6568 return line->id;
6571 static const struct got_error *
6572 stop_blame(struct tog_blame *blame)
6574 const struct got_error *err = NULL;
6575 int i;
6577 if (blame->thread) {
6578 int errcode;
6579 errcode = pthread_mutex_unlock(&tog_mutex);
6580 if (errcode)
6581 return got_error_set_errno(errcode,
6582 "pthread_mutex_unlock");
6583 errcode = pthread_join(blame->thread, (void **)&err);
6584 if (errcode)
6585 return got_error_set_errno(errcode, "pthread_join");
6586 errcode = pthread_mutex_lock(&tog_mutex);
6587 if (errcode)
6588 return got_error_set_errno(errcode,
6589 "pthread_mutex_lock");
6590 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6591 err = NULL;
6592 blame->thread = NULL;
6594 if (blame->thread_args.repo) {
6595 const struct got_error *close_err;
6596 close_err = got_repo_close(blame->thread_args.repo);
6597 if (err == NULL)
6598 err = close_err;
6599 blame->thread_args.repo = NULL;
6601 if (blame->f) {
6602 if (fclose(blame->f) == EOF && err == NULL)
6603 err = got_error_from_errno("fclose");
6604 blame->f = NULL;
6606 if (blame->lines) {
6607 for (i = 0; i < blame->nlines; i++)
6608 free(blame->lines[i].id);
6609 free(blame->lines);
6610 blame->lines = NULL;
6612 free(blame->cb_args.commit_id);
6613 blame->cb_args.commit_id = NULL;
6614 if (blame->pack_fds) {
6615 const struct got_error *pack_err =
6616 got_repo_pack_fds_close(blame->pack_fds);
6617 if (err == NULL)
6618 err = pack_err;
6619 blame->pack_fds = NULL;
6621 free(blame->line_offsets);
6622 blame->line_offsets = NULL;
6623 return err;
6626 static const struct got_error *
6627 cancel_blame_view(void *arg)
6629 const struct got_error *err = NULL;
6630 int *done = arg;
6631 int errcode;
6633 errcode = pthread_mutex_lock(&tog_mutex);
6634 if (errcode)
6635 return got_error_set_errno(errcode,
6636 "pthread_mutex_unlock");
6638 if (*done)
6639 err = got_error(GOT_ERR_CANCELLED);
6641 errcode = pthread_mutex_unlock(&tog_mutex);
6642 if (errcode)
6643 return got_error_set_errno(errcode,
6644 "pthread_mutex_lock");
6646 return err;
6649 static const struct got_error *
6650 run_blame(struct tog_view *view)
6652 struct tog_blame_view_state *s = &view->state.blame;
6653 struct tog_blame *blame = &s->blame;
6654 const struct got_error *err = NULL;
6655 struct got_commit_object *commit = NULL;
6656 struct got_blob_object *blob = NULL;
6657 struct got_repository *thread_repo = NULL;
6658 struct got_object_id *obj_id = NULL;
6659 int obj_type, fd = -1;
6660 int *pack_fds = NULL;
6662 err = got_object_open_as_commit(&commit, s->repo,
6663 &s->blamed_commit->id);
6664 if (err)
6665 return err;
6667 fd = got_opentempfd();
6668 if (fd == -1) {
6669 err = got_error_from_errno("got_opentempfd");
6670 goto done;
6673 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6674 if (err)
6675 goto done;
6677 err = got_object_get_type(&obj_type, s->repo, obj_id);
6678 if (err)
6679 goto done;
6681 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6682 err = got_error(GOT_ERR_OBJ_TYPE);
6683 goto done;
6686 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6687 if (err)
6688 goto done;
6689 blame->f = got_opentemp();
6690 if (blame->f == NULL) {
6691 err = got_error_from_errno("got_opentemp");
6692 goto done;
6694 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6695 &blame->line_offsets, blame->f, blob);
6696 if (err)
6697 goto done;
6698 if (blame->nlines == 0) {
6699 s->blame_complete = 1;
6700 goto done;
6703 /* Don't include \n at EOF in the blame line count. */
6704 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6705 blame->nlines--;
6707 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6708 if (blame->lines == NULL) {
6709 err = got_error_from_errno("calloc");
6710 goto done;
6713 err = got_repo_pack_fds_open(&pack_fds);
6714 if (err)
6715 goto done;
6716 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6717 pack_fds);
6718 if (err)
6719 goto done;
6721 blame->pack_fds = pack_fds;
6722 blame->cb_args.view = view;
6723 blame->cb_args.lines = blame->lines;
6724 blame->cb_args.nlines = blame->nlines;
6725 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6726 if (blame->cb_args.commit_id == NULL) {
6727 err = got_error_from_errno("got_object_id_dup");
6728 goto done;
6730 blame->cb_args.quit = &s->done;
6732 blame->thread_args.path = s->path;
6733 blame->thread_args.repo = thread_repo;
6734 blame->thread_args.cb_args = &blame->cb_args;
6735 blame->thread_args.complete = &s->blame_complete;
6736 blame->thread_args.cancel_cb = cancel_blame_view;
6737 blame->thread_args.cancel_arg = &s->done;
6738 s->blame_complete = 0;
6740 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6741 s->first_displayed_line = 1;
6742 s->last_displayed_line = view->nlines;
6743 s->selected_line = 1;
6745 s->matched_line = 0;
6747 done:
6748 if (commit)
6749 got_object_commit_close(commit);
6750 if (fd != -1 && close(fd) == -1 && err == NULL)
6751 err = got_error_from_errno("close");
6752 if (blob)
6753 got_object_blob_close(blob);
6754 free(obj_id);
6755 if (err)
6756 stop_blame(blame);
6757 return err;
6760 static const struct got_error *
6761 open_blame_view(struct tog_view *view, char *path,
6762 struct got_object_id *commit_id, struct got_repository *repo)
6764 const struct got_error *err = NULL;
6765 struct tog_blame_view_state *s = &view->state.blame;
6767 STAILQ_INIT(&s->blamed_commits);
6769 s->path = strdup(path);
6770 if (s->path == NULL)
6771 return got_error_from_errno("strdup");
6773 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6774 if (err) {
6775 free(s->path);
6776 return err;
6779 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6780 s->first_displayed_line = 1;
6781 s->last_displayed_line = view->nlines;
6782 s->selected_line = 1;
6783 s->blame_complete = 0;
6784 s->repo = repo;
6785 s->commit_id = commit_id;
6786 memset(&s->blame, 0, sizeof(s->blame));
6788 STAILQ_INIT(&s->colors);
6789 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6790 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6791 get_color_value("TOG_COLOR_COMMIT"));
6792 if (err)
6793 return err;
6796 view->show = show_blame_view;
6797 view->input = input_blame_view;
6798 view->reset = reset_blame_view;
6799 view->close = close_blame_view;
6800 view->search_start = search_start_blame_view;
6801 view->search_setup = search_setup_blame_view;
6802 view->search_next = search_next_view_match;
6804 if (using_mock_io) {
6805 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6806 int rc;
6808 rc = pthread_cond_init(&bta->blame_complete, NULL);
6809 if (rc)
6810 return got_error_set_errno(rc, "pthread_cond_init");
6813 return run_blame(view);
6816 static const struct got_error *
6817 close_blame_view(struct tog_view *view)
6819 const struct got_error *err = NULL;
6820 struct tog_blame_view_state *s = &view->state.blame;
6822 if (s->blame.thread)
6823 err = stop_blame(&s->blame);
6825 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6826 struct got_object_qid *blamed_commit;
6827 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6828 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6829 got_object_qid_free(blamed_commit);
6832 if (using_mock_io) {
6833 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6834 int rc;
6836 rc = pthread_cond_destroy(&bta->blame_complete);
6837 if (rc && err == NULL)
6838 err = got_error_set_errno(rc, "pthread_cond_destroy");
6841 free(s->path);
6842 free_colors(&s->colors);
6843 return err;
6846 static const struct got_error *
6847 search_start_blame_view(struct tog_view *view)
6849 struct tog_blame_view_state *s = &view->state.blame;
6851 s->matched_line = 0;
6852 return NULL;
6855 static void
6856 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6857 size_t *nlines, int **first, int **last, int **match, int **selected)
6859 struct tog_blame_view_state *s = &view->state.blame;
6861 *f = s->blame.f;
6862 *nlines = s->blame.nlines;
6863 *line_offsets = s->blame.line_offsets;
6864 *match = &s->matched_line;
6865 *first = &s->first_displayed_line;
6866 *last = &s->last_displayed_line;
6867 *selected = &s->selected_line;
6870 static const struct got_error *
6871 show_blame_view(struct tog_view *view)
6873 const struct got_error *err = NULL;
6874 struct tog_blame_view_state *s = &view->state.blame;
6875 int errcode;
6877 if (s->blame.thread == NULL && !s->blame_complete) {
6878 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6879 &s->blame.thread_args);
6880 if (errcode)
6881 return got_error_set_errno(errcode, "pthread_create");
6883 if (!using_mock_io)
6884 halfdelay(1); /* fast refresh while annotating */
6887 if (s->blame_complete && !using_mock_io)
6888 halfdelay(10); /* disable fast refresh */
6890 err = draw_blame(view);
6892 view_border(view);
6893 return err;
6896 static const struct got_error *
6897 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6898 struct got_repository *repo, struct got_object_id *id)
6900 struct tog_view *log_view;
6901 const struct got_error *err = NULL;
6903 *new_view = NULL;
6905 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6906 if (log_view == NULL)
6907 return got_error_from_errno("view_open");
6909 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0, NULL);
6910 if (err)
6911 view_close(log_view);
6912 else
6913 *new_view = log_view;
6915 return err;
6918 static const struct got_error *
6919 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6921 const struct got_error *err = NULL, *thread_err = NULL;
6922 struct tog_view *diff_view;
6923 struct tog_blame_view_state *s = &view->state.blame;
6924 int eos, nscroll, begin_y = 0, begin_x = 0;
6926 eos = nscroll = view->nlines - 2;
6927 if (view_is_hsplit_top(view))
6928 --eos; /* border */
6930 switch (ch) {
6931 case '0':
6932 case '$':
6933 case KEY_RIGHT:
6934 case 'l':
6935 case KEY_LEFT:
6936 case 'h':
6937 horizontal_scroll_input(view, ch);
6938 break;
6939 case 'q':
6940 s->done = 1;
6941 break;
6942 case 'g':
6943 case KEY_HOME:
6944 s->selected_line = 1;
6945 s->first_displayed_line = 1;
6946 view->count = 0;
6947 break;
6948 case 'G':
6949 case KEY_END:
6950 if (s->blame.nlines < eos) {
6951 s->selected_line = s->blame.nlines;
6952 s->first_displayed_line = 1;
6953 } else {
6954 s->selected_line = eos;
6955 s->first_displayed_line = s->blame.nlines - (eos - 1);
6957 view->count = 0;
6958 break;
6959 case 'k':
6960 case KEY_UP:
6961 case CTRL('p'):
6962 if (s->selected_line > 1)
6963 s->selected_line--;
6964 else if (s->selected_line == 1 &&
6965 s->first_displayed_line > 1)
6966 s->first_displayed_line--;
6967 else
6968 view->count = 0;
6969 break;
6970 case CTRL('u'):
6971 case 'u':
6972 nscroll /= 2;
6973 /* FALL THROUGH */
6974 case KEY_PPAGE:
6975 case CTRL('b'):
6976 case 'b':
6977 if (s->first_displayed_line == 1) {
6978 if (view->count > 1)
6979 nscroll += nscroll;
6980 s->selected_line = MAX(1, s->selected_line - nscroll);
6981 view->count = 0;
6982 break;
6984 if (s->first_displayed_line > nscroll)
6985 s->first_displayed_line -= nscroll;
6986 else
6987 s->first_displayed_line = 1;
6988 break;
6989 case 'j':
6990 case KEY_DOWN:
6991 case CTRL('n'):
6992 if (s->selected_line < eos && s->first_displayed_line +
6993 s->selected_line <= s->blame.nlines)
6994 s->selected_line++;
6995 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6996 s->first_displayed_line++;
6997 else
6998 view->count = 0;
6999 break;
7000 case 'c':
7001 case 'p': {
7002 struct got_object_id *id = NULL;
7004 view->count = 0;
7005 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7006 s->first_displayed_line, s->selected_line);
7007 if (id == NULL)
7008 break;
7009 if (ch == 'p') {
7010 struct got_commit_object *commit, *pcommit;
7011 struct got_object_qid *pid;
7012 struct got_object_id *blob_id = NULL;
7013 int obj_type;
7014 err = got_object_open_as_commit(&commit,
7015 s->repo, id);
7016 if (err)
7017 break;
7018 pid = STAILQ_FIRST(
7019 got_object_commit_get_parent_ids(commit));
7020 if (pid == NULL) {
7021 got_object_commit_close(commit);
7022 break;
7024 /* Check if path history ends here. */
7025 err = got_object_open_as_commit(&pcommit,
7026 s->repo, &pid->id);
7027 if (err)
7028 break;
7029 err = got_object_id_by_path(&blob_id, s->repo,
7030 pcommit, s->path);
7031 got_object_commit_close(pcommit);
7032 if (err) {
7033 if (err->code == GOT_ERR_NO_TREE_ENTRY)
7034 err = NULL;
7035 got_object_commit_close(commit);
7036 break;
7038 err = got_object_get_type(&obj_type, s->repo,
7039 blob_id);
7040 free(blob_id);
7041 /* Can't blame non-blob type objects. */
7042 if (obj_type != GOT_OBJ_TYPE_BLOB) {
7043 got_object_commit_close(commit);
7044 break;
7046 err = got_object_qid_alloc(&s->blamed_commit,
7047 &pid->id);
7048 got_object_commit_close(commit);
7049 } else {
7050 if (got_object_id_cmp(id,
7051 &s->blamed_commit->id) == 0)
7052 break;
7053 err = got_object_qid_alloc(&s->blamed_commit,
7054 id);
7056 if (err)
7057 break;
7058 s->done = 1;
7059 thread_err = stop_blame(&s->blame);
7060 s->done = 0;
7061 if (thread_err)
7062 break;
7063 STAILQ_INSERT_HEAD(&s->blamed_commits,
7064 s->blamed_commit, entry);
7065 err = run_blame(view);
7066 if (err)
7067 break;
7068 break;
7070 case 'C': {
7071 struct got_object_qid *first;
7073 view->count = 0;
7074 first = STAILQ_FIRST(&s->blamed_commits);
7075 if (!got_object_id_cmp(&first->id, s->commit_id))
7076 break;
7077 s->done = 1;
7078 thread_err = stop_blame(&s->blame);
7079 s->done = 0;
7080 if (thread_err)
7081 break;
7082 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
7083 got_object_qid_free(s->blamed_commit);
7084 s->blamed_commit =
7085 STAILQ_FIRST(&s->blamed_commits);
7086 err = run_blame(view);
7087 if (err)
7088 break;
7089 break;
7091 case 'L':
7092 view->count = 0;
7093 s->id_to_log = get_selected_commit_id(s->blame.lines,
7094 s->blame.nlines, s->first_displayed_line, s->selected_line);
7095 if (s->id_to_log)
7096 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7097 break;
7098 case KEY_ENTER:
7099 case '\r': {
7100 struct got_object_id *id = NULL;
7101 struct got_object_qid *pid;
7102 struct got_commit_object *commit = NULL;
7104 view->count = 0;
7105 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7106 s->first_displayed_line, s->selected_line);
7107 if (id == NULL)
7108 break;
7109 err = got_object_open_as_commit(&commit, s->repo, id);
7110 if (err)
7111 break;
7112 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7113 if (*new_view) {
7114 /* traversed from diff view, release diff resources */
7115 err = close_diff_view(*new_view);
7116 if (err)
7117 break;
7118 diff_view = *new_view;
7119 } else {
7120 if (view_is_parent_view(view))
7121 view_get_split(view, &begin_y, &begin_x);
7123 diff_view = view_open(0, 0, begin_y, begin_x,
7124 TOG_VIEW_DIFF);
7125 if (diff_view == NULL) {
7126 got_object_commit_close(commit);
7127 err = got_error_from_errno("view_open");
7128 break;
7131 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
7132 id, NULL, NULL, 3, 0, 0, view, s->repo);
7133 got_object_commit_close(commit);
7134 if (err)
7135 break;
7136 s->last_diffed_line = s->first_displayed_line - 1 +
7137 s->selected_line;
7138 if (*new_view)
7139 break; /* still open from active diff view */
7140 if (view_is_parent_view(view) &&
7141 view->mode == TOG_VIEW_SPLIT_HRZN) {
7142 err = view_init_hsplit(view, begin_y);
7143 if (err)
7144 break;
7147 view->focussed = 0;
7148 diff_view->focussed = 1;
7149 diff_view->mode = view->mode;
7150 diff_view->nlines = view->lines - begin_y;
7151 if (view_is_parent_view(view)) {
7152 view_transfer_size(diff_view, view);
7153 err = view_close_child(view);
7154 if (err)
7155 break;
7156 err = view_set_child(view, diff_view);
7157 if (err)
7158 break;
7159 view->focus_child = 1;
7160 } else
7161 *new_view = diff_view;
7162 if (err)
7163 break;
7164 break;
7166 case CTRL('d'):
7167 case 'd':
7168 nscroll /= 2;
7169 /* FALL THROUGH */
7170 case KEY_NPAGE:
7171 case CTRL('f'):
7172 case 'f':
7173 case ' ':
7174 if (s->last_displayed_line >= s->blame.nlines &&
7175 s->selected_line >= MIN(s->blame.nlines,
7176 view->nlines - 2)) {
7177 view->count = 0;
7178 break;
7180 if (s->last_displayed_line >= s->blame.nlines &&
7181 s->selected_line < view->nlines - 2) {
7182 s->selected_line +=
7183 MIN(nscroll, s->last_displayed_line -
7184 s->first_displayed_line - s->selected_line + 1);
7186 if (s->last_displayed_line + nscroll <= s->blame.nlines)
7187 s->first_displayed_line += nscroll;
7188 else
7189 s->first_displayed_line =
7190 s->blame.nlines - (view->nlines - 3);
7191 break;
7192 case KEY_RESIZE:
7193 if (s->selected_line > view->nlines - 2) {
7194 s->selected_line = MIN(s->blame.nlines,
7195 view->nlines - 2);
7197 break;
7198 default:
7199 view->count = 0;
7200 break;
7202 return thread_err ? thread_err : err;
7205 static const struct got_error *
7206 reset_blame_view(struct tog_view *view)
7208 const struct got_error *err;
7209 struct tog_blame_view_state *s = &view->state.blame;
7211 view->count = 0;
7212 s->done = 1;
7213 err = stop_blame(&s->blame);
7214 s->done = 0;
7215 if (err)
7216 return err;
7217 return run_blame(view);
7220 static const struct got_error *
7221 cmd_blame(int argc, char *argv[])
7223 const struct got_error *error;
7224 struct got_repository *repo = NULL;
7225 struct got_worktree *worktree = NULL;
7226 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7227 char *link_target = NULL;
7228 struct got_object_id *commit_id = NULL;
7229 struct got_commit_object *commit = NULL;
7230 char *keyword_idstr = NULL, *commit_id_str = NULL;
7231 int ch;
7232 struct tog_view *view = NULL;
7233 int *pack_fds = NULL;
7235 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7236 switch (ch) {
7237 case 'c':
7238 commit_id_str = optarg;
7239 break;
7240 case 'r':
7241 repo_path = realpath(optarg, NULL);
7242 if (repo_path == NULL)
7243 return got_error_from_errno2("realpath",
7244 optarg);
7245 break;
7246 default:
7247 usage_blame();
7248 /* NOTREACHED */
7252 argc -= optind;
7253 argv += optind;
7255 if (argc != 1)
7256 usage_blame();
7258 error = got_repo_pack_fds_open(&pack_fds);
7259 if (error != NULL)
7260 goto done;
7262 if (repo_path == NULL) {
7263 cwd = getcwd(NULL, 0);
7264 if (cwd == NULL)
7265 return got_error_from_errno("getcwd");
7266 error = got_worktree_open(&worktree, cwd, NULL);
7267 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7268 goto done;
7269 if (worktree)
7270 repo_path =
7271 strdup(got_worktree_get_repo_path(worktree));
7272 else
7273 repo_path = strdup(cwd);
7274 if (repo_path == NULL) {
7275 error = got_error_from_errno("strdup");
7276 goto done;
7280 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7281 if (error != NULL)
7282 goto done;
7284 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7285 worktree);
7286 if (error)
7287 goto done;
7289 init_curses();
7291 error = apply_unveil(got_repo_get_path(repo), NULL);
7292 if (error)
7293 goto done;
7295 error = tog_load_refs(repo, 0);
7296 if (error)
7297 goto done;
7299 if (commit_id_str == NULL) {
7300 struct got_reference *head_ref;
7301 error = got_ref_open(&head_ref, repo, worktree ?
7302 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7303 if (error != NULL)
7304 goto done;
7305 error = got_ref_resolve(&commit_id, repo, head_ref);
7306 got_ref_close(head_ref);
7307 } else {
7308 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
7309 repo, worktree);
7310 if (error != NULL)
7311 goto done;
7312 if (keyword_idstr != NULL)
7313 commit_id_str = keyword_idstr;
7315 error = got_repo_match_object_id(&commit_id, NULL,
7316 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7318 if (error != NULL)
7319 goto done;
7321 error = got_object_open_as_commit(&commit, repo, commit_id);
7322 if (error)
7323 goto done;
7325 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7326 commit, repo);
7327 if (error)
7328 goto done;
7330 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7331 if (view == NULL) {
7332 error = got_error_from_errno("view_open");
7333 goto done;
7335 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7336 commit_id, repo);
7337 if (error != NULL) {
7338 if (view->close == NULL)
7339 close_blame_view(view);
7340 view_close(view);
7341 goto done;
7344 if (worktree) {
7345 error = set_tog_base_commit(repo, worktree);
7346 if (error != NULL)
7347 goto done;
7349 /* Release work tree lock. */
7350 got_worktree_close(worktree);
7351 worktree = NULL;
7354 error = view_loop(view);
7356 done:
7357 free(tog_base_commit.id);
7358 free(repo_path);
7359 free(in_repo_path);
7360 free(link_target);
7361 free(cwd);
7362 free(commit_id);
7363 free(keyword_idstr);
7364 if (commit)
7365 got_object_commit_close(commit);
7366 if (worktree)
7367 got_worktree_close(worktree);
7368 if (repo) {
7369 const struct got_error *close_err = got_repo_close(repo);
7370 if (error == NULL)
7371 error = close_err;
7373 if (pack_fds) {
7374 const struct got_error *pack_err =
7375 got_repo_pack_fds_close(pack_fds);
7376 if (error == NULL)
7377 error = pack_err;
7379 tog_free_refs();
7380 return error;
7383 static const struct got_error *
7384 draw_tree_entries(struct tog_view *view, const char *parent_path)
7386 struct tog_tree_view_state *s = &view->state.tree;
7387 const struct got_error *err = NULL;
7388 struct got_tree_entry *te;
7389 wchar_t *wline;
7390 char *index = NULL;
7391 struct tog_color *tc;
7392 int width, n, nentries, scrollx, i = 1;
7393 int limit = view->nlines;
7395 s->ndisplayed = 0;
7396 if (view_is_hsplit_top(view))
7397 --limit; /* border */
7399 werase(view->window);
7401 if (limit == 0)
7402 return NULL;
7404 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7405 0, 0);
7406 if (err)
7407 return err;
7408 if (view_needs_focus_indication(view))
7409 wstandout(view->window);
7410 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7411 if (tc)
7412 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7413 waddwstr(view->window, wline);
7414 free(wline);
7415 wline = NULL;
7416 while (width++ < view->ncols)
7417 waddch(view->window, ' ');
7418 if (tc)
7419 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7420 if (view_needs_focus_indication(view))
7421 wstandend(view->window);
7422 if (--limit <= 0)
7423 return NULL;
7425 i += s->selected;
7426 if (s->first_displayed_entry) {
7427 i += got_tree_entry_get_index(s->first_displayed_entry);
7428 if (s->tree != s->root)
7429 ++i; /* account for ".." entry */
7431 nentries = got_object_tree_get_nentries(s->tree);
7432 if (asprintf(&index, "[%d/%d] %s",
7433 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7434 return got_error_from_errno("asprintf");
7435 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7436 free(index);
7437 if (err)
7438 return err;
7439 waddwstr(view->window, wline);
7440 free(wline);
7441 wline = NULL;
7442 if (width < view->ncols - 1)
7443 waddch(view->window, '\n');
7444 if (--limit <= 0)
7445 return NULL;
7446 waddch(view->window, '\n');
7447 if (--limit <= 0)
7448 return NULL;
7450 if (s->first_displayed_entry == NULL) {
7451 te = got_object_tree_get_first_entry(s->tree);
7452 if (s->selected == 0) {
7453 if (view->focussed)
7454 wstandout(view->window);
7455 s->selected_entry = NULL;
7457 waddstr(view->window, " ..\n"); /* parent directory */
7458 if (s->selected == 0 && view->focussed)
7459 wstandend(view->window);
7460 s->ndisplayed++;
7461 if (--limit <= 0)
7462 return NULL;
7463 n = 1;
7464 } else {
7465 n = 0;
7466 te = s->first_displayed_entry;
7469 view->maxx = 0;
7470 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7471 char *line = NULL, *id_str = NULL, *link_target = NULL;
7472 const char *modestr = "";
7473 mode_t mode;
7475 te = got_object_tree_get_entry(s->tree, i);
7476 mode = got_tree_entry_get_mode(te);
7478 if (s->show_ids) {
7479 err = got_object_id_str(&id_str,
7480 got_tree_entry_get_id(te));
7481 if (err)
7482 return got_error_from_errno(
7483 "got_object_id_str");
7485 if (got_object_tree_entry_is_submodule(te))
7486 modestr = "$";
7487 else if (S_ISLNK(mode)) {
7488 int i;
7490 err = got_tree_entry_get_symlink_target(&link_target,
7491 te, s->repo);
7492 if (err) {
7493 free(id_str);
7494 return err;
7496 for (i = 0; link_target[i] != '\0'; i++) {
7497 if (!isprint((unsigned char)link_target[i]))
7498 link_target[i] = '?';
7500 modestr = "@";
7502 else if (S_ISDIR(mode))
7503 modestr = "/";
7504 else if (mode & S_IXUSR)
7505 modestr = "*";
7506 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7507 got_tree_entry_get_name(te), modestr,
7508 link_target ? " -> ": "",
7509 link_target ? link_target : "") == -1) {
7510 free(id_str);
7511 free(link_target);
7512 return got_error_from_errno("asprintf");
7514 free(id_str);
7515 free(link_target);
7517 /* use full line width to determine view->maxx */
7518 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7519 if (err) {
7520 free(line);
7521 break;
7523 view->maxx = MAX(view->maxx, width);
7524 free(wline);
7525 wline = NULL;
7527 err = format_line(&wline, &width, &scrollx, line, view->x,
7528 view->ncols, 0, 0);
7529 if (err) {
7530 free(line);
7531 break;
7533 if (n == s->selected) {
7534 if (view->focussed)
7535 wstandout(view->window);
7536 s->selected_entry = te;
7538 tc = match_color(&s->colors, line);
7539 if (tc)
7540 wattr_on(view->window,
7541 COLOR_PAIR(tc->colorpair), NULL);
7542 waddwstr(view->window, &wline[scrollx]);
7543 if (tc)
7544 wattr_off(view->window,
7545 COLOR_PAIR(tc->colorpair), NULL);
7546 if (width < view->ncols)
7547 waddch(view->window, '\n');
7548 if (n == s->selected && view->focussed)
7549 wstandend(view->window);
7550 free(line);
7551 free(wline);
7552 wline = NULL;
7553 n++;
7554 s->ndisplayed++;
7555 s->last_displayed_entry = te;
7556 if (--limit <= 0)
7557 break;
7560 return err;
7563 static void
7564 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7566 struct got_tree_entry *te;
7567 int isroot = s->tree == s->root;
7568 int i = 0;
7570 if (s->first_displayed_entry == NULL)
7571 return;
7573 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7574 while (i++ < maxscroll) {
7575 if (te == NULL) {
7576 if (!isroot)
7577 s->first_displayed_entry = NULL;
7578 break;
7580 s->first_displayed_entry = te;
7581 te = got_tree_entry_get_prev(s->tree, te);
7585 static const struct got_error *
7586 tree_scroll_down(struct tog_view *view, int maxscroll)
7588 struct tog_tree_view_state *s = &view->state.tree;
7589 struct got_tree_entry *next, *last;
7590 int n = 0;
7592 if (s->first_displayed_entry)
7593 next = got_tree_entry_get_next(s->tree,
7594 s->first_displayed_entry);
7595 else
7596 next = got_object_tree_get_first_entry(s->tree);
7598 last = s->last_displayed_entry;
7599 while (next && n++ < maxscroll) {
7600 if (last) {
7601 s->last_displayed_entry = last;
7602 last = got_tree_entry_get_next(s->tree, last);
7604 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7605 s->first_displayed_entry = next;
7606 next = got_tree_entry_get_next(s->tree, next);
7610 return NULL;
7613 static const struct got_error *
7614 tree_entry_path(char **path, struct tog_parent_trees *parents,
7615 struct got_tree_entry *te)
7617 const struct got_error *err = NULL;
7618 struct tog_parent_tree *pt;
7619 size_t len = 2; /* for leading slash and NUL */
7621 TAILQ_FOREACH(pt, parents, entry)
7622 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7623 + 1 /* slash */;
7624 if (te)
7625 len += strlen(got_tree_entry_get_name(te));
7627 *path = calloc(1, len);
7628 if (path == NULL)
7629 return got_error_from_errno("calloc");
7631 (*path)[0] = '/';
7632 pt = TAILQ_LAST(parents, tog_parent_trees);
7633 while (pt) {
7634 const char *name = got_tree_entry_get_name(pt->selected_entry);
7635 if (strlcat(*path, name, len) >= len) {
7636 err = got_error(GOT_ERR_NO_SPACE);
7637 goto done;
7639 if (strlcat(*path, "/", len) >= len) {
7640 err = got_error(GOT_ERR_NO_SPACE);
7641 goto done;
7643 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7645 if (te) {
7646 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7647 err = got_error(GOT_ERR_NO_SPACE);
7648 goto done;
7651 done:
7652 if (err) {
7653 free(*path);
7654 *path = NULL;
7656 return err;
7659 static const struct got_error *
7660 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7661 struct got_tree_entry *te, struct tog_parent_trees *parents,
7662 struct got_object_id *commit_id, struct got_repository *repo)
7664 const struct got_error *err = NULL;
7665 char *path;
7666 struct tog_view *blame_view;
7668 *new_view = NULL;
7670 err = tree_entry_path(&path, parents, te);
7671 if (err)
7672 return err;
7674 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7675 if (blame_view == NULL) {
7676 err = got_error_from_errno("view_open");
7677 goto done;
7680 err = open_blame_view(blame_view, path, commit_id, repo);
7681 if (err) {
7682 if (err->code == GOT_ERR_CANCELLED)
7683 err = NULL;
7684 view_close(blame_view);
7685 } else
7686 *new_view = blame_view;
7687 done:
7688 free(path);
7689 return err;
7692 static const struct got_error *
7693 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7694 struct tog_tree_view_state *s)
7696 struct tog_view *log_view;
7697 const struct got_error *err = NULL;
7698 char *path;
7700 *new_view = NULL;
7702 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7703 if (log_view == NULL)
7704 return got_error_from_errno("view_open");
7706 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7707 if (err)
7708 return err;
7710 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7711 path, 0, NULL);
7712 if (err)
7713 view_close(log_view);
7714 else
7715 *new_view = log_view;
7716 free(path);
7717 return err;
7720 static const struct got_error *
7721 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7722 const char *head_ref_name, struct got_repository *repo)
7724 const struct got_error *err = NULL;
7725 char *commit_id_str = NULL;
7726 struct tog_tree_view_state *s = &view->state.tree;
7727 struct got_commit_object *commit = NULL;
7729 TAILQ_INIT(&s->parents);
7730 STAILQ_INIT(&s->colors);
7732 s->commit_id = got_object_id_dup(commit_id);
7733 if (s->commit_id == NULL) {
7734 err = got_error_from_errno("got_object_id_dup");
7735 goto done;
7738 err = got_object_open_as_commit(&commit, repo, commit_id);
7739 if (err)
7740 goto done;
7743 * The root is opened here and will be closed when the view is closed.
7744 * Any visited subtrees and their path-wise parents are opened and
7745 * closed on demand.
7747 err = got_object_open_as_tree(&s->root, repo,
7748 got_object_commit_get_tree_id(commit));
7749 if (err)
7750 goto done;
7751 s->tree = s->root;
7753 err = got_object_id_str(&commit_id_str, commit_id);
7754 if (err != NULL)
7755 goto done;
7757 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7758 err = got_error_from_errno("asprintf");
7759 goto done;
7762 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7763 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7764 if (head_ref_name) {
7765 s->head_ref_name = strdup(head_ref_name);
7766 if (s->head_ref_name == NULL) {
7767 err = got_error_from_errno("strdup");
7768 goto done;
7771 s->repo = repo;
7773 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7774 err = add_color(&s->colors, "\\$$",
7775 TOG_COLOR_TREE_SUBMODULE,
7776 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7777 if (err)
7778 goto done;
7779 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7780 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7781 if (err)
7782 goto done;
7783 err = add_color(&s->colors, "/$",
7784 TOG_COLOR_TREE_DIRECTORY,
7785 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7786 if (err)
7787 goto done;
7789 err = add_color(&s->colors, "\\*$",
7790 TOG_COLOR_TREE_EXECUTABLE,
7791 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7792 if (err)
7793 goto done;
7795 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7796 get_color_value("TOG_COLOR_COMMIT"));
7797 if (err)
7798 goto done;
7801 view->show = show_tree_view;
7802 view->input = input_tree_view;
7803 view->close = close_tree_view;
7804 view->search_start = search_start_tree_view;
7805 view->search_next = search_next_tree_view;
7806 done:
7807 free(commit_id_str);
7808 if (commit)
7809 got_object_commit_close(commit);
7810 if (err) {
7811 if (view->close == NULL)
7812 close_tree_view(view);
7813 view_close(view);
7815 return err;
7818 static const struct got_error *
7819 close_tree_view(struct tog_view *view)
7821 struct tog_tree_view_state *s = &view->state.tree;
7823 free_colors(&s->colors);
7824 free(s->tree_label);
7825 s->tree_label = NULL;
7826 free(s->commit_id);
7827 s->commit_id = NULL;
7828 free(s->head_ref_name);
7829 s->head_ref_name = NULL;
7830 while (!TAILQ_EMPTY(&s->parents)) {
7831 struct tog_parent_tree *parent;
7832 parent = TAILQ_FIRST(&s->parents);
7833 TAILQ_REMOVE(&s->parents, parent, entry);
7834 if (parent->tree != s->root)
7835 got_object_tree_close(parent->tree);
7836 free(parent);
7839 if (s->tree != NULL && s->tree != s->root)
7840 got_object_tree_close(s->tree);
7841 if (s->root)
7842 got_object_tree_close(s->root);
7843 return NULL;
7846 static const struct got_error *
7847 search_start_tree_view(struct tog_view *view)
7849 struct tog_tree_view_state *s = &view->state.tree;
7851 s->matched_entry = NULL;
7852 return NULL;
7855 static int
7856 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7858 regmatch_t regmatch;
7860 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7861 0) == 0;
7864 static const struct got_error *
7865 search_next_tree_view(struct tog_view *view)
7867 struct tog_tree_view_state *s = &view->state.tree;
7868 struct got_tree_entry *te = NULL;
7870 if (!view->searching) {
7871 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7872 return NULL;
7875 if (s->matched_entry) {
7876 if (view->searching == TOG_SEARCH_FORWARD) {
7877 if (s->selected_entry)
7878 te = got_tree_entry_get_next(s->tree,
7879 s->selected_entry);
7880 else
7881 te = got_object_tree_get_first_entry(s->tree);
7882 } else {
7883 if (s->selected_entry == NULL)
7884 te = got_object_tree_get_last_entry(s->tree);
7885 else
7886 te = got_tree_entry_get_prev(s->tree,
7887 s->selected_entry);
7889 } else {
7890 if (s->selected_entry)
7891 te = s->selected_entry;
7892 else if (view->searching == TOG_SEARCH_FORWARD)
7893 te = got_object_tree_get_first_entry(s->tree);
7894 else
7895 te = got_object_tree_get_last_entry(s->tree);
7898 while (1) {
7899 if (te == NULL) {
7900 if (s->matched_entry == NULL) {
7901 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7902 return NULL;
7904 if (view->searching == TOG_SEARCH_FORWARD)
7905 te = got_object_tree_get_first_entry(s->tree);
7906 else
7907 te = got_object_tree_get_last_entry(s->tree);
7910 if (match_tree_entry(te, &view->regex)) {
7911 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7912 s->matched_entry = te;
7913 break;
7916 if (view->searching == TOG_SEARCH_FORWARD)
7917 te = got_tree_entry_get_next(s->tree, te);
7918 else
7919 te = got_tree_entry_get_prev(s->tree, te);
7922 if (s->matched_entry) {
7923 s->first_displayed_entry = s->matched_entry;
7924 s->selected = 0;
7927 return NULL;
7930 static const struct got_error *
7931 show_tree_view(struct tog_view *view)
7933 const struct got_error *err = NULL;
7934 struct tog_tree_view_state *s = &view->state.tree;
7935 char *parent_path;
7937 err = tree_entry_path(&parent_path, &s->parents, NULL);
7938 if (err)
7939 return err;
7941 err = draw_tree_entries(view, parent_path);
7942 free(parent_path);
7944 view_border(view);
7945 return err;
7948 static const struct got_error *
7949 tree_goto_line(struct tog_view *view, int nlines)
7951 const struct got_error *err = NULL;
7952 struct tog_tree_view_state *s = &view->state.tree;
7953 struct got_tree_entry **fte, **lte, **ste;
7954 int g, last, first = 1, i = 1;
7955 int root = s->tree == s->root;
7956 int off = root ? 1 : 2;
7958 g = view->gline;
7959 view->gline = 0;
7961 if (g == 0)
7962 g = 1;
7963 else if (g > got_object_tree_get_nentries(s->tree))
7964 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7966 fte = &s->first_displayed_entry;
7967 lte = &s->last_displayed_entry;
7968 ste = &s->selected_entry;
7970 if (*fte != NULL) {
7971 first = got_tree_entry_get_index(*fte);
7972 first += off; /* account for ".." */
7974 last = got_tree_entry_get_index(*lte);
7975 last += off;
7977 if (g >= first && g <= last && g - first < nlines) {
7978 s->selected = g - first;
7979 return NULL; /* gline is on the current page */
7982 if (*ste != NULL) {
7983 i = got_tree_entry_get_index(*ste);
7984 i += off;
7987 if (i < g) {
7988 err = tree_scroll_down(view, g - i);
7989 if (err)
7990 return err;
7991 if (got_tree_entry_get_index(*lte) >=
7992 got_object_tree_get_nentries(s->tree) - 1 &&
7993 first + s->selected < g &&
7994 s->selected < s->ndisplayed - 1) {
7995 first = got_tree_entry_get_index(*fte);
7996 first += off;
7997 s->selected = g - first;
7999 } else if (i > g)
8000 tree_scroll_up(s, i - g);
8002 if (g < nlines &&
8003 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
8004 s->selected = g - 1;
8006 return NULL;
8009 static const struct got_error *
8010 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
8012 const struct got_error *err = NULL;
8013 struct tog_tree_view_state *s = &view->state.tree;
8014 struct got_tree_entry *te;
8015 int n, nscroll = view->nlines - 3;
8017 if (view->gline)
8018 return tree_goto_line(view, nscroll);
8020 switch (ch) {
8021 case '0':
8022 case '$':
8023 case KEY_RIGHT:
8024 case 'l':
8025 case KEY_LEFT:
8026 case 'h':
8027 horizontal_scroll_input(view, ch);
8028 break;
8029 case 'i':
8030 s->show_ids = !s->show_ids;
8031 view->count = 0;
8032 break;
8033 case 'L':
8034 view->count = 0;
8035 if (!s->selected_entry)
8036 break;
8037 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8038 break;
8039 case 'R':
8040 view->count = 0;
8041 err = view_request_new(new_view, view, TOG_VIEW_REF);
8042 break;
8043 case 'g':
8044 case '=':
8045 case KEY_HOME:
8046 s->selected = 0;
8047 view->count = 0;
8048 if (s->tree == s->root)
8049 s->first_displayed_entry =
8050 got_object_tree_get_first_entry(s->tree);
8051 else
8052 s->first_displayed_entry = NULL;
8053 break;
8054 case 'G':
8055 case '*':
8056 case KEY_END: {
8057 int eos = view->nlines - 3;
8059 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8060 --eos; /* border */
8061 s->selected = 0;
8062 view->count = 0;
8063 te = got_object_tree_get_last_entry(s->tree);
8064 for (n = 0; n < eos; n++) {
8065 if (te == NULL) {
8066 if (s->tree != s->root) {
8067 s->first_displayed_entry = NULL;
8068 n++;
8070 break;
8072 s->first_displayed_entry = te;
8073 te = got_tree_entry_get_prev(s->tree, te);
8075 if (n > 0)
8076 s->selected = n - 1;
8077 break;
8079 case 'k':
8080 case KEY_UP:
8081 case CTRL('p'):
8082 if (s->selected > 0) {
8083 s->selected--;
8084 break;
8086 tree_scroll_up(s, 1);
8087 if (s->selected_entry == NULL ||
8088 (s->tree == s->root && s->selected_entry ==
8089 got_object_tree_get_first_entry(s->tree)))
8090 view->count = 0;
8091 break;
8092 case CTRL('u'):
8093 case 'u':
8094 nscroll /= 2;
8095 /* FALL THROUGH */
8096 case KEY_PPAGE:
8097 case CTRL('b'):
8098 case 'b':
8099 if (s->tree == s->root) {
8100 if (got_object_tree_get_first_entry(s->tree) ==
8101 s->first_displayed_entry)
8102 s->selected -= MIN(s->selected, nscroll);
8103 } else {
8104 if (s->first_displayed_entry == NULL)
8105 s->selected -= MIN(s->selected, nscroll);
8107 tree_scroll_up(s, MAX(0, nscroll));
8108 if (s->selected_entry == NULL ||
8109 (s->tree == s->root && s->selected_entry ==
8110 got_object_tree_get_first_entry(s->tree)))
8111 view->count = 0;
8112 break;
8113 case 'j':
8114 case KEY_DOWN:
8115 case CTRL('n'):
8116 if (s->selected < s->ndisplayed - 1) {
8117 s->selected++;
8118 break;
8120 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8121 == NULL) {
8122 /* can't scroll any further */
8123 view->count = 0;
8124 break;
8126 tree_scroll_down(view, 1);
8127 break;
8128 case CTRL('d'):
8129 case 'd':
8130 nscroll /= 2;
8131 /* FALL THROUGH */
8132 case KEY_NPAGE:
8133 case CTRL('f'):
8134 case 'f':
8135 case ' ':
8136 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8137 == NULL) {
8138 /* can't scroll any further; move cursor down */
8139 if (s->selected < s->ndisplayed - 1)
8140 s->selected += MIN(nscroll,
8141 s->ndisplayed - s->selected - 1);
8142 else
8143 view->count = 0;
8144 break;
8146 tree_scroll_down(view, nscroll);
8147 break;
8148 case KEY_ENTER:
8149 case '\r':
8150 case KEY_BACKSPACE:
8151 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
8152 struct tog_parent_tree *parent;
8153 /* user selected '..' */
8154 if (s->tree == s->root) {
8155 view->count = 0;
8156 break;
8158 parent = TAILQ_FIRST(&s->parents);
8159 TAILQ_REMOVE(&s->parents, parent,
8160 entry);
8161 got_object_tree_close(s->tree);
8162 s->tree = parent->tree;
8163 s->first_displayed_entry =
8164 parent->first_displayed_entry;
8165 s->selected_entry =
8166 parent->selected_entry;
8167 s->selected = parent->selected;
8168 if (s->selected > view->nlines - 3) {
8169 err = offset_selection_down(view);
8170 if (err)
8171 break;
8173 free(parent);
8174 } else if (S_ISDIR(got_tree_entry_get_mode(
8175 s->selected_entry))) {
8176 struct got_tree_object *subtree;
8177 view->count = 0;
8178 err = got_object_open_as_tree(&subtree, s->repo,
8179 got_tree_entry_get_id(s->selected_entry));
8180 if (err)
8181 break;
8182 err = tree_view_visit_subtree(s, subtree);
8183 if (err) {
8184 got_object_tree_close(subtree);
8185 break;
8187 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
8188 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
8189 break;
8190 case KEY_RESIZE:
8191 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
8192 s->selected = view->nlines - 4;
8193 view->count = 0;
8194 break;
8195 default:
8196 view->count = 0;
8197 break;
8200 return err;
8203 __dead static void
8204 usage_tree(void)
8206 endwin();
8207 fprintf(stderr,
8208 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
8209 getprogname());
8210 exit(1);
8213 static const struct got_error *
8214 cmd_tree(int argc, char *argv[])
8216 const struct got_error *error;
8217 struct got_repository *repo = NULL;
8218 struct got_worktree *worktree = NULL;
8219 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8220 struct got_object_id *commit_id = NULL;
8221 struct got_commit_object *commit = NULL;
8222 const char *commit_id_arg = NULL;
8223 char *keyword_idstr = NULL, *label = NULL;
8224 struct got_reference *ref = NULL;
8225 const char *head_ref_name = NULL;
8226 int ch;
8227 struct tog_view *view;
8228 int *pack_fds = NULL;
8230 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
8231 switch (ch) {
8232 case 'c':
8233 commit_id_arg = optarg;
8234 break;
8235 case 'r':
8236 repo_path = realpath(optarg, NULL);
8237 if (repo_path == NULL)
8238 return got_error_from_errno2("realpath",
8239 optarg);
8240 break;
8241 default:
8242 usage_tree();
8243 /* NOTREACHED */
8247 argc -= optind;
8248 argv += optind;
8250 if (argc > 1)
8251 usage_tree();
8253 error = got_repo_pack_fds_open(&pack_fds);
8254 if (error != NULL)
8255 goto done;
8257 if (repo_path == NULL) {
8258 cwd = getcwd(NULL, 0);
8259 if (cwd == NULL)
8260 return got_error_from_errno("getcwd");
8261 error = got_worktree_open(&worktree, cwd, NULL);
8262 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8263 goto done;
8264 if (worktree)
8265 repo_path =
8266 strdup(got_worktree_get_repo_path(worktree));
8267 else
8268 repo_path = strdup(cwd);
8269 if (repo_path == NULL) {
8270 error = got_error_from_errno("strdup");
8271 goto done;
8275 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8276 if (error != NULL)
8277 goto done;
8279 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8280 repo, worktree);
8281 if (error)
8282 goto done;
8284 init_curses();
8286 error = apply_unveil(got_repo_get_path(repo), NULL);
8287 if (error)
8288 goto done;
8290 error = tog_load_refs(repo, 0);
8291 if (error)
8292 goto done;
8294 if (commit_id_arg == NULL) {
8295 error = got_repo_match_object_id(&commit_id, &label,
8296 worktree ? got_worktree_get_head_ref_name(worktree) :
8297 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8298 if (error)
8299 goto done;
8300 head_ref_name = label;
8301 } else {
8302 error = got_keyword_to_idstr(&keyword_idstr, commit_id_arg,
8303 repo, worktree);
8304 if (error != NULL)
8305 goto done;
8306 if (keyword_idstr != NULL)
8307 commit_id_arg = keyword_idstr;
8309 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8310 if (error == NULL)
8311 head_ref_name = got_ref_get_name(ref);
8312 else if (error->code != GOT_ERR_NOT_REF)
8313 goto done;
8314 error = got_repo_match_object_id(&commit_id, NULL,
8315 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8316 if (error)
8317 goto done;
8320 error = got_object_open_as_commit(&commit, repo, commit_id);
8321 if (error)
8322 goto done;
8324 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8325 if (view == NULL) {
8326 error = got_error_from_errno("view_open");
8327 goto done;
8329 error = open_tree_view(view, commit_id, head_ref_name, repo);
8330 if (error)
8331 goto done;
8332 if (!got_path_is_root_dir(in_repo_path)) {
8333 error = tree_view_walk_path(&view->state.tree, commit,
8334 in_repo_path);
8335 if (error)
8336 goto done;
8339 if (worktree) {
8340 error = set_tog_base_commit(repo, worktree);
8341 if (error != NULL)
8342 goto done;
8344 /* Release work tree lock. */
8345 got_worktree_close(worktree);
8346 worktree = NULL;
8349 error = view_loop(view);
8351 done:
8352 free(tog_base_commit.id);
8353 free(keyword_idstr);
8354 free(repo_path);
8355 free(cwd);
8356 free(commit_id);
8357 free(label);
8358 if (ref)
8359 got_ref_close(ref);
8360 if (worktree != NULL)
8361 got_worktree_close(worktree);
8362 if (repo) {
8363 const struct got_error *close_err = got_repo_close(repo);
8364 if (error == NULL)
8365 error = close_err;
8367 if (pack_fds) {
8368 const struct got_error *pack_err =
8369 got_repo_pack_fds_close(pack_fds);
8370 if (error == NULL)
8371 error = pack_err;
8373 tog_free_refs();
8374 return error;
8377 static const struct got_error *
8378 ref_view_load_refs(struct tog_ref_view_state *s)
8380 struct got_reflist_entry *sre;
8381 struct tog_reflist_entry *re;
8383 s->nrefs = 0;
8384 TAILQ_FOREACH(sre, &tog_refs, entry) {
8385 if (strncmp(got_ref_get_name(sre->ref),
8386 "refs/got/", 9) == 0 &&
8387 strncmp(got_ref_get_name(sre->ref),
8388 "refs/got/backup/", 16) != 0)
8389 continue;
8391 re = malloc(sizeof(*re));
8392 if (re == NULL)
8393 return got_error_from_errno("malloc");
8395 re->ref = got_ref_dup(sre->ref);
8396 if (re->ref == NULL)
8397 return got_error_from_errno("got_ref_dup");
8398 re->idx = s->nrefs++;
8399 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8402 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8403 return NULL;
8406 static void
8407 ref_view_free_refs(struct tog_ref_view_state *s)
8409 struct tog_reflist_entry *re;
8411 while (!TAILQ_EMPTY(&s->refs)) {
8412 re = TAILQ_FIRST(&s->refs);
8413 TAILQ_REMOVE(&s->refs, re, entry);
8414 got_ref_close(re->ref);
8415 free(re);
8419 static const struct got_error *
8420 open_ref_view(struct tog_view *view, struct got_repository *repo)
8422 const struct got_error *err = NULL;
8423 struct tog_ref_view_state *s = &view->state.ref;
8425 s->selected_entry = 0;
8426 s->repo = repo;
8428 TAILQ_INIT(&s->refs);
8429 STAILQ_INIT(&s->colors);
8431 err = ref_view_load_refs(s);
8432 if (err)
8433 goto done;
8435 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8436 err = add_color(&s->colors, "^refs/heads/",
8437 TOG_COLOR_REFS_HEADS,
8438 get_color_value("TOG_COLOR_REFS_HEADS"));
8439 if (err)
8440 goto done;
8442 err = add_color(&s->colors, "^refs/tags/",
8443 TOG_COLOR_REFS_TAGS,
8444 get_color_value("TOG_COLOR_REFS_TAGS"));
8445 if (err)
8446 goto done;
8448 err = add_color(&s->colors, "^refs/remotes/",
8449 TOG_COLOR_REFS_REMOTES,
8450 get_color_value("TOG_COLOR_REFS_REMOTES"));
8451 if (err)
8452 goto done;
8454 err = add_color(&s->colors, "^refs/got/backup/",
8455 TOG_COLOR_REFS_BACKUP,
8456 get_color_value("TOG_COLOR_REFS_BACKUP"));
8457 if (err)
8458 goto done;
8461 view->show = show_ref_view;
8462 view->input = input_ref_view;
8463 view->close = close_ref_view;
8464 view->search_start = search_start_ref_view;
8465 view->search_next = search_next_ref_view;
8466 done:
8467 if (err) {
8468 if (view->close == NULL)
8469 close_ref_view(view);
8470 view_close(view);
8472 return err;
8475 static const struct got_error *
8476 close_ref_view(struct tog_view *view)
8478 struct tog_ref_view_state *s = &view->state.ref;
8480 ref_view_free_refs(s);
8481 free_colors(&s->colors);
8483 return NULL;
8486 static const struct got_error *
8487 resolve_reflist_entry(struct got_object_id **commit_id,
8488 struct tog_reflist_entry *re, struct got_repository *repo)
8490 const struct got_error *err = NULL;
8491 struct got_object_id *obj_id;
8492 struct got_tag_object *tag = NULL;
8493 int obj_type;
8495 *commit_id = NULL;
8497 err = got_ref_resolve(&obj_id, repo, re->ref);
8498 if (err)
8499 return err;
8501 err = got_object_get_type(&obj_type, repo, obj_id);
8502 if (err)
8503 goto done;
8505 switch (obj_type) {
8506 case GOT_OBJ_TYPE_COMMIT:
8507 *commit_id = obj_id;
8508 break;
8509 case GOT_OBJ_TYPE_TAG:
8510 err = got_object_open_as_tag(&tag, repo, obj_id);
8511 if (err)
8512 goto done;
8513 free(obj_id);
8514 err = got_object_get_type(&obj_type, repo,
8515 got_object_tag_get_object_id(tag));
8516 if (err)
8517 goto done;
8518 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8519 err = got_error(GOT_ERR_OBJ_TYPE);
8520 goto done;
8522 *commit_id = got_object_id_dup(
8523 got_object_tag_get_object_id(tag));
8524 if (*commit_id == NULL) {
8525 err = got_error_from_errno("got_object_id_dup");
8526 goto done;
8528 break;
8529 default:
8530 err = got_error(GOT_ERR_OBJ_TYPE);
8531 break;
8534 done:
8535 if (tag)
8536 got_object_tag_close(tag);
8537 if (err) {
8538 free(*commit_id);
8539 *commit_id = NULL;
8541 return err;
8544 static const struct got_error *
8545 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8546 struct tog_reflist_entry *re, struct got_repository *repo)
8548 struct tog_view *log_view;
8549 const struct got_error *err = NULL;
8550 struct got_object_id *commit_id = NULL;
8552 *new_view = NULL;
8554 err = resolve_reflist_entry(&commit_id, re, repo);
8555 if (err) {
8556 if (err->code != GOT_ERR_OBJ_TYPE)
8557 return err;
8558 else
8559 return NULL;
8562 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8563 if (log_view == NULL) {
8564 err = got_error_from_errno("view_open");
8565 goto done;
8568 err = open_log_view(log_view, commit_id, repo,
8569 got_ref_get_name(re->ref), "", 0, NULL);
8570 done:
8571 if (err)
8572 view_close(log_view);
8573 else
8574 *new_view = log_view;
8575 free(commit_id);
8576 return err;
8579 static void
8580 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8582 struct tog_reflist_entry *re;
8583 int i = 0;
8585 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8586 return;
8588 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8589 while (i++ < maxscroll) {
8590 if (re == NULL)
8591 break;
8592 s->first_displayed_entry = re;
8593 re = TAILQ_PREV(re, tog_reflist_head, entry);
8597 static const struct got_error *
8598 ref_scroll_down(struct tog_view *view, int maxscroll)
8600 struct tog_ref_view_state *s = &view->state.ref;
8601 struct tog_reflist_entry *next, *last;
8602 int n = 0;
8604 if (s->first_displayed_entry)
8605 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8606 else
8607 next = TAILQ_FIRST(&s->refs);
8609 last = s->last_displayed_entry;
8610 while (next && n++ < maxscroll) {
8611 if (last) {
8612 s->last_displayed_entry = last;
8613 last = TAILQ_NEXT(last, entry);
8615 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8616 s->first_displayed_entry = next;
8617 next = TAILQ_NEXT(next, entry);
8621 return NULL;
8624 static const struct got_error *
8625 search_start_ref_view(struct tog_view *view)
8627 struct tog_ref_view_state *s = &view->state.ref;
8629 s->matched_entry = NULL;
8630 return NULL;
8633 static int
8634 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8636 regmatch_t regmatch;
8638 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8639 0) == 0;
8642 static const struct got_error *
8643 search_next_ref_view(struct tog_view *view)
8645 struct tog_ref_view_state *s = &view->state.ref;
8646 struct tog_reflist_entry *re = NULL;
8648 if (!view->searching) {
8649 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8650 return NULL;
8653 if (s->matched_entry) {
8654 if (view->searching == TOG_SEARCH_FORWARD) {
8655 if (s->selected_entry)
8656 re = TAILQ_NEXT(s->selected_entry, entry);
8657 else
8658 re = TAILQ_PREV(s->selected_entry,
8659 tog_reflist_head, entry);
8660 } else {
8661 if (s->selected_entry == NULL)
8662 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8663 else
8664 re = TAILQ_PREV(s->selected_entry,
8665 tog_reflist_head, entry);
8667 } else {
8668 if (s->selected_entry)
8669 re = s->selected_entry;
8670 else if (view->searching == TOG_SEARCH_FORWARD)
8671 re = TAILQ_FIRST(&s->refs);
8672 else
8673 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8676 while (1) {
8677 if (re == NULL) {
8678 if (s->matched_entry == NULL) {
8679 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8680 return NULL;
8682 if (view->searching == TOG_SEARCH_FORWARD)
8683 re = TAILQ_FIRST(&s->refs);
8684 else
8685 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8688 if (match_reflist_entry(re, &view->regex)) {
8689 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8690 s->matched_entry = re;
8691 break;
8694 if (view->searching == TOG_SEARCH_FORWARD)
8695 re = TAILQ_NEXT(re, entry);
8696 else
8697 re = TAILQ_PREV(re, tog_reflist_head, entry);
8700 if (s->matched_entry) {
8701 s->first_displayed_entry = s->matched_entry;
8702 s->selected = 0;
8705 return NULL;
8708 static const struct got_error *
8709 show_ref_view(struct tog_view *view)
8711 const struct got_error *err = NULL;
8712 struct tog_ref_view_state *s = &view->state.ref;
8713 struct tog_reflist_entry *re;
8714 char *line = NULL;
8715 wchar_t *wline;
8716 struct tog_color *tc;
8717 int width, n, scrollx;
8718 int limit = view->nlines;
8720 werase(view->window);
8722 s->ndisplayed = 0;
8723 if (view_is_hsplit_top(view))
8724 --limit; /* border */
8726 if (limit == 0)
8727 return NULL;
8729 re = s->first_displayed_entry;
8731 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8732 s->nrefs) == -1)
8733 return got_error_from_errno("asprintf");
8735 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8736 if (err) {
8737 free(line);
8738 return err;
8740 if (view_needs_focus_indication(view))
8741 wstandout(view->window);
8742 waddwstr(view->window, wline);
8743 while (width++ < view->ncols)
8744 waddch(view->window, ' ');
8745 if (view_needs_focus_indication(view))
8746 wstandend(view->window);
8747 free(wline);
8748 wline = NULL;
8749 free(line);
8750 line = NULL;
8751 if (--limit <= 0)
8752 return NULL;
8754 n = 0;
8755 view->maxx = 0;
8756 while (re && limit > 0) {
8757 char *line = NULL;
8758 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8760 if (s->show_date) {
8761 struct got_commit_object *ci;
8762 struct got_tag_object *tag;
8763 struct got_object_id *id;
8764 struct tm tm;
8765 time_t t;
8767 err = got_ref_resolve(&id, s->repo, re->ref);
8768 if (err)
8769 return err;
8770 err = got_object_open_as_tag(&tag, s->repo, id);
8771 if (err) {
8772 if (err->code != GOT_ERR_OBJ_TYPE) {
8773 free(id);
8774 return err;
8776 err = got_object_open_as_commit(&ci, s->repo,
8777 id);
8778 if (err) {
8779 free(id);
8780 return err;
8782 t = got_object_commit_get_committer_time(ci);
8783 got_object_commit_close(ci);
8784 } else {
8785 t = got_object_tag_get_tagger_time(tag);
8786 got_object_tag_close(tag);
8788 free(id);
8789 if (gmtime_r(&t, &tm) == NULL)
8790 return got_error_from_errno("gmtime_r");
8791 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8792 return got_error(GOT_ERR_NO_SPACE);
8794 if (got_ref_is_symbolic(re->ref)) {
8795 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8796 ymd : "", got_ref_get_name(re->ref),
8797 got_ref_get_symref_target(re->ref)) == -1)
8798 return got_error_from_errno("asprintf");
8799 } else if (s->show_ids) {
8800 struct got_object_id *id;
8801 char *id_str;
8802 err = got_ref_resolve(&id, s->repo, re->ref);
8803 if (err)
8804 return err;
8805 err = got_object_id_str(&id_str, id);
8806 if (err) {
8807 free(id);
8808 return err;
8810 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8811 got_ref_get_name(re->ref), id_str) == -1) {
8812 err = got_error_from_errno("asprintf");
8813 free(id);
8814 free(id_str);
8815 return err;
8817 free(id);
8818 free(id_str);
8819 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8820 got_ref_get_name(re->ref)) == -1)
8821 return got_error_from_errno("asprintf");
8823 /* use full line width to determine view->maxx */
8824 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8825 if (err) {
8826 free(line);
8827 return err;
8829 view->maxx = MAX(view->maxx, width);
8830 free(wline);
8831 wline = NULL;
8833 err = format_line(&wline, &width, &scrollx, line, view->x,
8834 view->ncols, 0, 0);
8835 if (err) {
8836 free(line);
8837 return err;
8839 if (n == s->selected) {
8840 if (view->focussed)
8841 wstandout(view->window);
8842 s->selected_entry = re;
8844 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8845 if (tc)
8846 wattr_on(view->window,
8847 COLOR_PAIR(tc->colorpair), NULL);
8848 waddwstr(view->window, &wline[scrollx]);
8849 if (tc)
8850 wattr_off(view->window,
8851 COLOR_PAIR(tc->colorpair), NULL);
8852 if (width < view->ncols)
8853 waddch(view->window, '\n');
8854 if (n == s->selected && view->focussed)
8855 wstandend(view->window);
8856 free(line);
8857 free(wline);
8858 wline = NULL;
8859 n++;
8860 s->ndisplayed++;
8861 s->last_displayed_entry = re;
8863 limit--;
8864 re = TAILQ_NEXT(re, entry);
8867 view_border(view);
8868 return err;
8871 static const struct got_error *
8872 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8873 struct tog_reflist_entry *re, struct got_repository *repo)
8875 const struct got_error *err = NULL;
8876 struct got_object_id *commit_id = NULL;
8877 struct tog_view *tree_view;
8879 *new_view = NULL;
8881 err = resolve_reflist_entry(&commit_id, re, repo);
8882 if (err) {
8883 if (err->code != GOT_ERR_OBJ_TYPE)
8884 return err;
8885 else
8886 return NULL;
8890 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8891 if (tree_view == NULL) {
8892 err = got_error_from_errno("view_open");
8893 goto done;
8896 err = open_tree_view(tree_view, commit_id,
8897 got_ref_get_name(re->ref), repo);
8898 if (err)
8899 goto done;
8901 *new_view = tree_view;
8902 done:
8903 free(commit_id);
8904 return err;
8907 static const struct got_error *
8908 ref_goto_line(struct tog_view *view, int nlines)
8910 const struct got_error *err = NULL;
8911 struct tog_ref_view_state *s = &view->state.ref;
8912 int g, idx = s->selected_entry->idx;
8914 g = view->gline;
8915 view->gline = 0;
8917 if (g == 0)
8918 g = 1;
8919 else if (g > s->nrefs)
8920 g = s->nrefs;
8922 if (g >= s->first_displayed_entry->idx + 1 &&
8923 g <= s->last_displayed_entry->idx + 1 &&
8924 g - s->first_displayed_entry->idx - 1 < nlines) {
8925 s->selected = g - s->first_displayed_entry->idx - 1;
8926 return NULL;
8929 if (idx + 1 < g) {
8930 err = ref_scroll_down(view, g - idx - 1);
8931 if (err)
8932 return err;
8933 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8934 s->first_displayed_entry->idx + s->selected < g &&
8935 s->selected < s->ndisplayed - 1)
8936 s->selected = g - s->first_displayed_entry->idx - 1;
8937 } else if (idx + 1 > g)
8938 ref_scroll_up(s, idx - g + 1);
8940 if (g < nlines && s->first_displayed_entry->idx == 0)
8941 s->selected = g - 1;
8943 return NULL;
8947 static const struct got_error *
8948 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8950 const struct got_error *err = NULL;
8951 struct tog_ref_view_state *s = &view->state.ref;
8952 struct tog_reflist_entry *re;
8953 int n, nscroll = view->nlines - 1;
8955 if (view->gline)
8956 return ref_goto_line(view, nscroll);
8958 switch (ch) {
8959 case '0':
8960 case '$':
8961 case KEY_RIGHT:
8962 case 'l':
8963 case KEY_LEFT:
8964 case 'h':
8965 horizontal_scroll_input(view, ch);
8966 break;
8967 case 'i':
8968 s->show_ids = !s->show_ids;
8969 view->count = 0;
8970 break;
8971 case 'm':
8972 s->show_date = !s->show_date;
8973 view->count = 0;
8974 break;
8975 case 'o':
8976 s->sort_by_date = !s->sort_by_date;
8977 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8978 view->count = 0;
8979 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8980 got_ref_cmp_by_commit_timestamp_descending :
8981 tog_ref_cmp_by_name, s->repo);
8982 if (err)
8983 break;
8984 got_reflist_object_id_map_free(tog_refs_idmap);
8985 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8986 &tog_refs, s->repo);
8987 if (err)
8988 break;
8989 ref_view_free_refs(s);
8990 err = ref_view_load_refs(s);
8991 break;
8992 case KEY_ENTER:
8993 case '\r':
8994 view->count = 0;
8995 if (!s->selected_entry)
8996 break;
8997 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8998 break;
8999 case 'T':
9000 view->count = 0;
9001 if (!s->selected_entry)
9002 break;
9003 err = view_request_new(new_view, view, TOG_VIEW_TREE);
9004 break;
9005 case 'g':
9006 case '=':
9007 case KEY_HOME:
9008 s->selected = 0;
9009 view->count = 0;
9010 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
9011 break;
9012 case 'G':
9013 case '*':
9014 case KEY_END: {
9015 int eos = view->nlines - 1;
9017 if (view->mode == TOG_VIEW_SPLIT_HRZN)
9018 --eos; /* border */
9019 s->selected = 0;
9020 view->count = 0;
9021 re = TAILQ_LAST(&s->refs, tog_reflist_head);
9022 for (n = 0; n < eos; n++) {
9023 if (re == NULL)
9024 break;
9025 s->first_displayed_entry = re;
9026 re = TAILQ_PREV(re, tog_reflist_head, entry);
9028 if (n > 0)
9029 s->selected = n - 1;
9030 break;
9032 case 'k':
9033 case KEY_UP:
9034 case CTRL('p'):
9035 if (s->selected > 0) {
9036 s->selected--;
9037 break;
9039 ref_scroll_up(s, 1);
9040 if (s->selected_entry == TAILQ_FIRST(&s->refs))
9041 view->count = 0;
9042 break;
9043 case CTRL('u'):
9044 case 'u':
9045 nscroll /= 2;
9046 /* FALL THROUGH */
9047 case KEY_PPAGE:
9048 case CTRL('b'):
9049 case 'b':
9050 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
9051 s->selected -= MIN(nscroll, s->selected);
9052 ref_scroll_up(s, MAX(0, nscroll));
9053 if (s->selected_entry == TAILQ_FIRST(&s->refs))
9054 view->count = 0;
9055 break;
9056 case 'j':
9057 case KEY_DOWN:
9058 case CTRL('n'):
9059 if (s->selected < s->ndisplayed - 1) {
9060 s->selected++;
9061 break;
9063 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
9064 /* can't scroll any further */
9065 view->count = 0;
9066 break;
9068 ref_scroll_down(view, 1);
9069 break;
9070 case CTRL('d'):
9071 case 'd':
9072 nscroll /= 2;
9073 /* FALL THROUGH */
9074 case KEY_NPAGE:
9075 case CTRL('f'):
9076 case 'f':
9077 case ' ':
9078 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
9079 /* can't scroll any further; move cursor down */
9080 if (s->selected < s->ndisplayed - 1)
9081 s->selected += MIN(nscroll,
9082 s->ndisplayed - s->selected - 1);
9083 if (view->count > 1 && s->selected < s->ndisplayed - 1)
9084 s->selected += s->ndisplayed - s->selected - 1;
9085 view->count = 0;
9086 break;
9088 ref_scroll_down(view, nscroll);
9089 break;
9090 case CTRL('l'):
9091 view->count = 0;
9092 tog_free_refs();
9093 err = tog_load_refs(s->repo, s->sort_by_date);
9094 if (err)
9095 break;
9096 ref_view_free_refs(s);
9097 err = ref_view_load_refs(s);
9098 break;
9099 case KEY_RESIZE:
9100 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
9101 s->selected = view->nlines - 2;
9102 break;
9103 default:
9104 view->count = 0;
9105 break;
9108 return err;
9111 __dead static void
9112 usage_ref(void)
9114 endwin();
9115 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
9116 getprogname());
9117 exit(1);
9120 static const struct got_error *
9121 cmd_ref(int argc, char *argv[])
9123 const struct got_error *error;
9124 struct got_repository *repo = NULL;
9125 struct got_worktree *worktree = NULL;
9126 char *cwd = NULL, *repo_path = NULL;
9127 int ch;
9128 struct tog_view *view;
9129 int *pack_fds = NULL;
9131 while ((ch = getopt(argc, argv, "r:")) != -1) {
9132 switch (ch) {
9133 case 'r':
9134 repo_path = realpath(optarg, NULL);
9135 if (repo_path == NULL)
9136 return got_error_from_errno2("realpath",
9137 optarg);
9138 break;
9139 default:
9140 usage_ref();
9141 /* NOTREACHED */
9145 argc -= optind;
9146 argv += optind;
9148 if (argc > 1)
9149 usage_ref();
9151 error = got_repo_pack_fds_open(&pack_fds);
9152 if (error != NULL)
9153 goto done;
9155 if (repo_path == NULL) {
9156 cwd = getcwd(NULL, 0);
9157 if (cwd == NULL)
9158 return got_error_from_errno("getcwd");
9159 error = got_worktree_open(&worktree, cwd, NULL);
9160 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9161 goto done;
9162 if (worktree)
9163 repo_path =
9164 strdup(got_worktree_get_repo_path(worktree));
9165 else
9166 repo_path = strdup(cwd);
9167 if (repo_path == NULL) {
9168 error = got_error_from_errno("strdup");
9169 goto done;
9173 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9174 if (error != NULL)
9175 goto done;
9177 init_curses();
9179 error = apply_unveil(got_repo_get_path(repo), NULL);
9180 if (error)
9181 goto done;
9183 error = tog_load_refs(repo, 0);
9184 if (error)
9185 goto done;
9187 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
9188 if (view == NULL) {
9189 error = got_error_from_errno("view_open");
9190 goto done;
9193 error = open_ref_view(view, repo);
9194 if (error)
9195 goto done;
9197 if (worktree) {
9198 error = set_tog_base_commit(repo, worktree);
9199 if (error != NULL)
9200 goto done;
9202 /* Release work tree lock. */
9203 got_worktree_close(worktree);
9204 worktree = NULL;
9207 error = view_loop(view);
9209 done:
9210 free(tog_base_commit.id);
9211 free(repo_path);
9212 free(cwd);
9213 if (worktree != NULL)
9214 got_worktree_close(worktree);
9215 if (repo) {
9216 const struct got_error *close_err = got_repo_close(repo);
9217 if (close_err)
9218 error = close_err;
9220 if (pack_fds) {
9221 const struct got_error *pack_err =
9222 got_repo_pack_fds_close(pack_fds);
9223 if (error == NULL)
9224 error = pack_err;
9226 tog_free_refs();
9227 return error;
9230 static const struct got_error*
9231 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
9232 const char *str)
9234 size_t len;
9236 if (win == NULL)
9237 win = stdscr;
9239 len = strlen(str);
9240 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
9242 if (focus)
9243 wstandout(win);
9244 if (mvwprintw(win, y, x, "%s", str) == ERR)
9245 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
9246 if (focus)
9247 wstandend(win);
9249 return NULL;
9252 static const struct got_error *
9253 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
9255 off_t *p;
9257 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
9258 if (p == NULL) {
9259 free(*line_offsets);
9260 *line_offsets = NULL;
9261 return got_error_from_errno("reallocarray");
9264 *line_offsets = p;
9265 (*line_offsets)[*nlines] = off;
9266 ++(*nlines);
9267 return NULL;
9270 static const struct got_error *
9271 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
9273 *ret = 0;
9275 for (;n > 0; --n, ++km) {
9276 char *t0, *t, *k;
9277 size_t len = 1;
9279 if (km->keys == NULL)
9280 continue;
9282 t = t0 = strdup(km->keys);
9283 if (t0 == NULL)
9284 return got_error_from_errno("strdup");
9286 len += strlen(t);
9287 while ((k = strsep(&t, " ")) != NULL)
9288 len += strlen(k) > 1 ? 2 : 0;
9289 free(t0);
9290 *ret = MAX(*ret, len);
9293 return NULL;
9297 * Write keymap section headers, keys, and key info in km to f.
9298 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9299 * wrap control and symbolic keys in guillemets, else use <>.
9301 static const struct got_error *
9302 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9304 int n, len = width;
9306 if (km->keys) {
9307 static const char *u8_glyph[] = {
9308 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9309 "\xe2\x80\xba" /* U+203A (utf8 >) */
9311 char *t0, *t, *k;
9312 int cs, s, first = 1;
9314 cs = got_locale_is_utf8();
9316 t = t0 = strdup(km->keys);
9317 if (t0 == NULL)
9318 return got_error_from_errno("strdup");
9320 len = strlen(km->keys);
9321 while ((k = strsep(&t, " ")) != NULL) {
9322 s = strlen(k) > 1; /* control or symbolic key */
9323 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9324 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9325 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9326 if (n < 0) {
9327 free(t0);
9328 return got_error_from_errno("fprintf");
9330 first = 0;
9331 len += s ? 2 : 0;
9332 *off += n;
9334 free(t0);
9336 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9337 if (n < 0)
9338 return got_error_from_errno("fprintf");
9339 *off += n;
9341 return NULL;
9344 static const struct got_error *
9345 format_help(struct tog_help_view_state *s)
9347 const struct got_error *err = NULL;
9348 off_t off = 0;
9349 int i, max, n, show = s->all;
9350 static const struct tog_key_map km[] = {
9351 #define KEYMAP_(info, type) { NULL, (info), type }
9352 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9353 GENERATE_HELP
9354 #undef KEYMAP_
9355 #undef KEY_
9358 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9359 if (err)
9360 return err;
9362 n = nitems(km);
9363 err = max_key_str(&max, km, n);
9364 if (err)
9365 return err;
9367 for (i = 0; i < n; ++i) {
9368 if (km[i].keys == NULL) {
9369 show = s->all;
9370 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9371 km[i].type == s->type || s->all)
9372 show = 1;
9374 if (show) {
9375 err = format_help_line(&off, s->f, &km[i], max);
9376 if (err)
9377 return err;
9378 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9379 if (err)
9380 return err;
9383 fputc('\n', s->f);
9384 ++off;
9385 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9386 return err;
9389 static const struct got_error *
9390 create_help(struct tog_help_view_state *s)
9392 FILE *f;
9393 const struct got_error *err;
9395 free(s->line_offsets);
9396 s->line_offsets = NULL;
9397 s->nlines = 0;
9399 f = got_opentemp();
9400 if (f == NULL)
9401 return got_error_from_errno("got_opentemp");
9402 s->f = f;
9404 err = format_help(s);
9405 if (err)
9406 return err;
9408 if (s->f && fflush(s->f) != 0)
9409 return got_error_from_errno("fflush");
9411 return NULL;
9414 static const struct got_error *
9415 search_start_help_view(struct tog_view *view)
9417 view->state.help.matched_line = 0;
9418 return NULL;
9421 static void
9422 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9423 size_t *nlines, int **first, int **last, int **match, int **selected)
9425 struct tog_help_view_state *s = &view->state.help;
9427 *f = s->f;
9428 *nlines = s->nlines;
9429 *line_offsets = s->line_offsets;
9430 *match = &s->matched_line;
9431 *first = &s->first_displayed_line;
9432 *last = &s->last_displayed_line;
9433 *selected = &s->selected_line;
9436 static const struct got_error *
9437 show_help_view(struct tog_view *view)
9439 struct tog_help_view_state *s = &view->state.help;
9440 const struct got_error *err;
9441 regmatch_t *regmatch = &view->regmatch;
9442 wchar_t *wline;
9443 char *line;
9444 ssize_t linelen;
9445 size_t linesz = 0;
9446 int width, nprinted = 0, rc = 0;
9447 int eos = view->nlines;
9449 if (view_is_hsplit_top(view))
9450 --eos; /* account for border */
9452 s->lineno = 0;
9453 rewind(s->f);
9454 werase(view->window);
9456 if (view->gline > s->nlines - 1)
9457 view->gline = s->nlines - 1;
9459 err = win_draw_center(view->window, 0, 0, view->ncols,
9460 view_needs_focus_indication(view),
9461 "tog help (press q to return to tog)");
9462 if (err)
9463 return err;
9464 if (eos <= 1)
9465 return NULL;
9466 waddstr(view->window, "\n\n");
9467 eos -= 2;
9469 s->eof = 0;
9470 view->maxx = 0;
9471 line = NULL;
9472 while (eos > 0 && nprinted < eos) {
9473 attr_t attr = 0;
9475 linelen = getline(&line, &linesz, s->f);
9476 if (linelen == -1) {
9477 if (!feof(s->f)) {
9478 free(line);
9479 return got_ferror(s->f, GOT_ERR_IO);
9481 s->eof = 1;
9482 break;
9484 if (++s->lineno < s->first_displayed_line)
9485 continue;
9486 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9487 continue;
9488 if (s->lineno == view->hiline)
9489 attr = A_STANDOUT;
9491 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9492 view->x ? 1 : 0);
9493 if (err) {
9494 free(line);
9495 return err;
9497 view->maxx = MAX(view->maxx, width);
9498 free(wline);
9499 wline = NULL;
9501 if (attr)
9502 wattron(view->window, attr);
9503 if (s->first_displayed_line + nprinted == s->matched_line &&
9504 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9505 err = add_matched_line(&width, line, view->ncols - 1, 0,
9506 view->window, view->x, regmatch);
9507 if (err) {
9508 free(line);
9509 return err;
9511 } else {
9512 int skip;
9514 err = format_line(&wline, &width, &skip, line,
9515 view->x, view->ncols, 0, view->x ? 1 : 0);
9516 if (err) {
9517 free(line);
9518 return err;
9520 waddwstr(view->window, &wline[skip]);
9521 free(wline);
9522 wline = NULL;
9524 if (s->lineno == view->hiline) {
9525 while (width++ < view->ncols)
9526 waddch(view->window, ' ');
9527 } else {
9528 if (width < view->ncols)
9529 waddch(view->window, '\n');
9531 if (attr)
9532 wattroff(view->window, attr);
9533 if (++nprinted == 1)
9534 s->first_displayed_line = s->lineno;
9536 free(line);
9537 if (nprinted > 0)
9538 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9539 else
9540 s->last_displayed_line = s->first_displayed_line;
9542 view_border(view);
9544 if (s->eof) {
9545 rc = waddnstr(view->window,
9546 "See the tog(1) manual page for full documentation",
9547 view->ncols - 1);
9548 if (rc == ERR)
9549 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9550 } else {
9551 wmove(view->window, view->nlines - 1, 0);
9552 wclrtoeol(view->window);
9553 wstandout(view->window);
9554 rc = waddnstr(view->window, "scroll down for more...",
9555 view->ncols - 1);
9556 if (rc == ERR)
9557 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9558 if (getcurx(view->window) < view->ncols - 6) {
9559 rc = wprintw(view->window, "[%.0f%%]",
9560 100.00 * s->last_displayed_line / s->nlines);
9561 if (rc == ERR)
9562 return got_error_msg(GOT_ERR_IO, "wprintw");
9564 wstandend(view->window);
9567 return NULL;
9570 static const struct got_error *
9571 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9573 struct tog_help_view_state *s = &view->state.help;
9574 const struct got_error *err = NULL;
9575 char *line = NULL;
9576 ssize_t linelen;
9577 size_t linesz = 0;
9578 int eos, nscroll;
9580 eos = nscroll = view->nlines;
9581 if (view_is_hsplit_top(view))
9582 --eos; /* border */
9584 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9586 switch (ch) {
9587 case '0':
9588 case '$':
9589 case KEY_RIGHT:
9590 case 'l':
9591 case KEY_LEFT:
9592 case 'h':
9593 horizontal_scroll_input(view, ch);
9594 break;
9595 case 'g':
9596 case KEY_HOME:
9597 s->first_displayed_line = 1;
9598 view->count = 0;
9599 break;
9600 case 'G':
9601 case KEY_END:
9602 view->count = 0;
9603 if (s->eof)
9604 break;
9605 s->first_displayed_line = (s->nlines - eos) + 3;
9606 s->eof = 1;
9607 break;
9608 case 'k':
9609 case KEY_UP:
9610 if (s->first_displayed_line > 1)
9611 --s->first_displayed_line;
9612 else
9613 view->count = 0;
9614 break;
9615 case CTRL('u'):
9616 case 'u':
9617 nscroll /= 2;
9618 /* FALL THROUGH */
9619 case KEY_PPAGE:
9620 case CTRL('b'):
9621 case 'b':
9622 if (s->first_displayed_line == 1) {
9623 view->count = 0;
9624 break;
9626 while (--nscroll > 0 && s->first_displayed_line > 1)
9627 s->first_displayed_line--;
9628 break;
9629 case 'j':
9630 case KEY_DOWN:
9631 case CTRL('n'):
9632 if (!s->eof)
9633 ++s->first_displayed_line;
9634 else
9635 view->count = 0;
9636 break;
9637 case CTRL('d'):
9638 case 'd':
9639 nscroll /= 2;
9640 /* FALL THROUGH */
9641 case KEY_NPAGE:
9642 case CTRL('f'):
9643 case 'f':
9644 case ' ':
9645 if (s->eof) {
9646 view->count = 0;
9647 break;
9649 while (!s->eof && --nscroll > 0) {
9650 linelen = getline(&line, &linesz, s->f);
9651 s->first_displayed_line++;
9652 if (linelen == -1) {
9653 if (feof(s->f))
9654 s->eof = 1;
9655 else
9656 err = got_ferror(s->f, GOT_ERR_IO);
9657 break;
9660 free(line);
9661 break;
9662 default:
9663 view->count = 0;
9664 break;
9667 return err;
9670 static const struct got_error *
9671 close_help_view(struct tog_view *view)
9673 struct tog_help_view_state *s = &view->state.help;
9675 free(s->line_offsets);
9676 s->line_offsets = NULL;
9677 if (fclose(s->f) == EOF)
9678 return got_error_from_errno("fclose");
9680 return NULL;
9683 static const struct got_error *
9684 reset_help_view(struct tog_view *view)
9686 struct tog_help_view_state *s = &view->state.help;
9689 if (s->f && fclose(s->f) == EOF)
9690 return got_error_from_errno("fclose");
9692 wclear(view->window);
9693 view->count = 0;
9694 view->x = 0;
9695 s->all = !s->all;
9696 s->first_displayed_line = 1;
9697 s->last_displayed_line = view->nlines;
9698 s->matched_line = 0;
9700 return create_help(s);
9703 static const struct got_error *
9704 open_help_view(struct tog_view *view, struct tog_view *parent)
9706 const struct got_error *err = NULL;
9707 struct tog_help_view_state *s = &view->state.help;
9709 s->type = (enum tog_keymap_type)parent->type;
9710 s->first_displayed_line = 1;
9711 s->last_displayed_line = view->nlines;
9712 s->selected_line = 1;
9714 view->show = show_help_view;
9715 view->input = input_help_view;
9716 view->reset = reset_help_view;
9717 view->close = close_help_view;
9718 view->search_start = search_start_help_view;
9719 view->search_setup = search_setup_help_view;
9720 view->search_next = search_next_view_match;
9722 err = create_help(s);
9723 return err;
9726 static const struct got_error *
9727 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9728 enum tog_view_type request, int y, int x)
9730 const struct got_error *err = NULL;
9732 *new_view = NULL;
9734 switch (request) {
9735 case TOG_VIEW_DIFF:
9736 if (view->type == TOG_VIEW_LOG) {
9737 struct tog_log_view_state *s = &view->state.log;
9739 err = open_diff_view_for_commit(new_view, y, x,
9740 s->selected_entry->commit, s->selected_entry->id,
9741 view, s->repo);
9742 } else
9743 return got_error_msg(GOT_ERR_NOT_IMPL,
9744 "parent/child view pair not supported");
9745 break;
9746 case TOG_VIEW_BLAME:
9747 if (view->type == TOG_VIEW_TREE) {
9748 struct tog_tree_view_state *s = &view->state.tree;
9750 err = blame_tree_entry(new_view, y, x,
9751 s->selected_entry, &s->parents, s->commit_id,
9752 s->repo);
9753 } else
9754 return got_error_msg(GOT_ERR_NOT_IMPL,
9755 "parent/child view pair not supported");
9756 break;
9757 case TOG_VIEW_LOG:
9758 if (view->type == TOG_VIEW_BLAME)
9759 err = log_annotated_line(new_view, y, x,
9760 view->state.blame.repo, view->state.blame.id_to_log);
9761 else if (view->type == TOG_VIEW_TREE)
9762 err = log_selected_tree_entry(new_view, y, x,
9763 &view->state.tree);
9764 else if (view->type == TOG_VIEW_REF)
9765 err = log_ref_entry(new_view, y, x,
9766 view->state.ref.selected_entry,
9767 view->state.ref.repo);
9768 else
9769 return got_error_msg(GOT_ERR_NOT_IMPL,
9770 "parent/child view pair not supported");
9771 break;
9772 case TOG_VIEW_TREE:
9773 if (view->type == TOG_VIEW_LOG)
9774 err = browse_commit_tree(new_view, y, x,
9775 view->state.log.selected_entry,
9776 view->state.log.in_repo_path,
9777 view->state.log.head_ref_name,
9778 view->state.log.repo);
9779 else if (view->type == TOG_VIEW_REF)
9780 err = browse_ref_tree(new_view, y, x,
9781 view->state.ref.selected_entry,
9782 view->state.ref.repo);
9783 else
9784 return got_error_msg(GOT_ERR_NOT_IMPL,
9785 "parent/child view pair not supported");
9786 break;
9787 case TOG_VIEW_REF:
9788 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9789 if (*new_view == NULL)
9790 return got_error_from_errno("view_open");
9791 if (view->type == TOG_VIEW_LOG)
9792 err = open_ref_view(*new_view, view->state.log.repo);
9793 else if (view->type == TOG_VIEW_TREE)
9794 err = open_ref_view(*new_view, view->state.tree.repo);
9795 else
9796 err = got_error_msg(GOT_ERR_NOT_IMPL,
9797 "parent/child view pair not supported");
9798 if (err)
9799 view_close(*new_view);
9800 break;
9801 case TOG_VIEW_HELP:
9802 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9803 if (*new_view == NULL)
9804 return got_error_from_errno("view_open");
9805 err = open_help_view(*new_view, view);
9806 if (err)
9807 view_close(*new_view);
9808 break;
9809 default:
9810 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9813 return err;
9817 * If view was scrolled down to move the selected line into view when opening a
9818 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9820 static void
9821 offset_selection_up(struct tog_view *view)
9823 switch (view->type) {
9824 case TOG_VIEW_BLAME: {
9825 struct tog_blame_view_state *s = &view->state.blame;
9826 if (s->first_displayed_line == 1) {
9827 s->selected_line = MAX(s->selected_line - view->offset,
9828 1);
9829 break;
9831 if (s->first_displayed_line > view->offset)
9832 s->first_displayed_line -= view->offset;
9833 else
9834 s->first_displayed_line = 1;
9835 s->selected_line += view->offset;
9836 break;
9838 case TOG_VIEW_LOG:
9839 log_scroll_up(&view->state.log, view->offset);
9840 view->state.log.selected += view->offset;
9841 break;
9842 case TOG_VIEW_REF:
9843 ref_scroll_up(&view->state.ref, view->offset);
9844 view->state.ref.selected += view->offset;
9845 break;
9846 case TOG_VIEW_TREE:
9847 tree_scroll_up(&view->state.tree, view->offset);
9848 view->state.tree.selected += view->offset;
9849 break;
9850 default:
9851 break;
9854 view->offset = 0;
9858 * If the selected line is in the section of screen covered by the bottom split,
9859 * scroll down offset lines to move it into view and index its new position.
9861 static const struct got_error *
9862 offset_selection_down(struct tog_view *view)
9864 const struct got_error *err = NULL;
9865 const struct got_error *(*scrolld)(struct tog_view *, int);
9866 int *selected = NULL;
9867 int header, offset;
9869 switch (view->type) {
9870 case TOG_VIEW_BLAME: {
9871 struct tog_blame_view_state *s = &view->state.blame;
9872 header = 3;
9873 scrolld = NULL;
9874 if (s->selected_line > view->nlines - header) {
9875 offset = abs(view->nlines - s->selected_line - header);
9876 s->first_displayed_line += offset;
9877 s->selected_line -= offset;
9878 view->offset = offset;
9880 break;
9882 case TOG_VIEW_LOG: {
9883 struct tog_log_view_state *s = &view->state.log;
9884 scrolld = &log_scroll_down;
9885 header = view_is_parent_view(view) ? 3 : 2;
9886 selected = &s->selected;
9887 break;
9889 case TOG_VIEW_REF: {
9890 struct tog_ref_view_state *s = &view->state.ref;
9891 scrolld = &ref_scroll_down;
9892 header = 3;
9893 selected = &s->selected;
9894 break;
9896 case TOG_VIEW_TREE: {
9897 struct tog_tree_view_state *s = &view->state.tree;
9898 scrolld = &tree_scroll_down;
9899 header = 5;
9900 selected = &s->selected;
9901 break;
9903 default:
9904 selected = NULL;
9905 scrolld = NULL;
9906 header = 0;
9907 break;
9910 if (selected && *selected > view->nlines - header) {
9911 offset = abs(view->nlines - *selected - header);
9912 view->offset = offset;
9913 if (scrolld && offset) {
9914 err = scrolld(view, offset);
9915 *selected -= offset;
9919 return err;
9922 static void
9923 list_commands(FILE *fp)
9925 size_t i;
9927 fprintf(fp, "commands:");
9928 for (i = 0; i < nitems(tog_commands); i++) {
9929 const struct tog_cmd *cmd = &tog_commands[i];
9930 fprintf(fp, " %s", cmd->name);
9932 fputc('\n', fp);
9935 __dead static void
9936 usage(int hflag, int status)
9938 FILE *fp = (status == 0) ? stdout : stderr;
9940 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9941 getprogname());
9942 if (hflag) {
9943 fprintf(fp, "lazy usage: %s path\n", getprogname());
9944 list_commands(fp);
9946 exit(status);
9949 static char **
9950 make_argv(int argc, ...)
9952 va_list ap;
9953 char **argv;
9954 int i;
9956 va_start(ap, argc);
9958 argv = calloc(argc, sizeof(char *));
9959 if (argv == NULL)
9960 err(1, "calloc");
9961 for (i = 0; i < argc; i++) {
9962 argv[i] = strdup(va_arg(ap, char *));
9963 if (argv[i] == NULL)
9964 err(1, "strdup");
9967 va_end(ap);
9968 return argv;
9972 * Try to convert 'tog path' into a 'tog log path' command.
9973 * The user could simply have mistyped the command rather than knowingly
9974 * provided a path. So check whether argv[0] can in fact be resolved
9975 * to a path in the HEAD commit and print a special error if not.
9976 * This hack is for mpi@ <3
9978 static const struct got_error *
9979 tog_log_with_path(int argc, char *argv[])
9981 const struct got_error *error = NULL, *close_err;
9982 const struct tog_cmd *cmd = NULL;
9983 struct got_repository *repo = NULL;
9984 struct got_worktree *worktree = NULL;
9985 struct got_object_id *commit_id = NULL, *id = NULL;
9986 struct got_commit_object *commit = NULL;
9987 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9988 char *commit_id_str = NULL, **cmd_argv = NULL;
9989 int *pack_fds = NULL;
9991 cwd = getcwd(NULL, 0);
9992 if (cwd == NULL)
9993 return got_error_from_errno("getcwd");
9995 error = got_repo_pack_fds_open(&pack_fds);
9996 if (error != NULL)
9997 goto done;
9999 error = got_worktree_open(&worktree, cwd, NULL);
10000 if (error && error->code != GOT_ERR_NOT_WORKTREE)
10001 goto done;
10003 if (worktree)
10004 repo_path = strdup(got_worktree_get_repo_path(worktree));
10005 else
10006 repo_path = strdup(cwd);
10007 if (repo_path == NULL) {
10008 error = got_error_from_errno("strdup");
10009 goto done;
10012 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
10013 if (error != NULL)
10014 goto done;
10016 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
10017 repo, worktree);
10018 if (error)
10019 goto done;
10021 error = tog_load_refs(repo, 0);
10022 if (error)
10023 goto done;
10024 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
10025 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
10026 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
10027 if (error)
10028 goto done;
10030 if (worktree) {
10031 got_worktree_close(worktree);
10032 worktree = NULL;
10035 error = got_object_open_as_commit(&commit, repo, commit_id);
10036 if (error)
10037 goto done;
10039 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
10040 if (error) {
10041 if (error->code != GOT_ERR_NO_TREE_ENTRY)
10042 goto done;
10043 fprintf(stderr, "%s: '%s' is no known command or path\n",
10044 getprogname(), argv[0]);
10045 usage(1, 1);
10046 /* not reached */
10049 error = got_object_id_str(&commit_id_str, commit_id);
10050 if (error)
10051 goto done;
10053 cmd = &tog_commands[0]; /* log */
10054 argc = 4;
10055 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
10056 error = cmd->cmd_main(argc, cmd_argv);
10057 done:
10058 if (repo) {
10059 close_err = got_repo_close(repo);
10060 if (error == NULL)
10061 error = close_err;
10063 if (commit)
10064 got_object_commit_close(commit);
10065 if (worktree)
10066 got_worktree_close(worktree);
10067 if (pack_fds) {
10068 const struct got_error *pack_err =
10069 got_repo_pack_fds_close(pack_fds);
10070 if (error == NULL)
10071 error = pack_err;
10073 free(id);
10074 free(commit_id_str);
10075 free(commit_id);
10076 free(cwd);
10077 free(repo_path);
10078 free(in_repo_path);
10079 if (cmd_argv) {
10080 int i;
10081 for (i = 0; i < argc; i++)
10082 free(cmd_argv[i]);
10083 free(cmd_argv);
10085 tog_free_refs();
10086 return error;
10089 int
10090 main(int argc, char *argv[])
10092 const struct got_error *io_err, *error = NULL;
10093 const struct tog_cmd *cmd = NULL;
10094 int ch, hflag = 0, Vflag = 0;
10095 char **cmd_argv = NULL;
10096 static const struct option longopts[] = {
10097 { "version", no_argument, NULL, 'V' },
10098 { NULL, 0, NULL, 0}
10100 char *diff_algo_str = NULL;
10101 const char *test_script_path;
10103 setlocale(LC_CTYPE, "");
10106 * Override default signal handlers before starting ncurses.
10107 * This should prevent ncurses from installing its own
10108 * broken cleanup() signal handler.
10110 signal(SIGWINCH, tog_sigwinch);
10111 signal(SIGPIPE, tog_sigpipe);
10112 signal(SIGCONT, tog_sigcont);
10113 signal(SIGINT, tog_sigint);
10114 signal(SIGTERM, tog_sigterm);
10117 * Test mode init must happen before pledge() because "tty" will
10118 * not allow TTY-related ioctls to occur via regular files.
10120 test_script_path = getenv("TOG_TEST_SCRIPT");
10121 if (test_script_path != NULL) {
10122 error = init_mock_term(test_script_path);
10123 if (error) {
10124 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10125 return 1;
10127 } else if (!isatty(STDIN_FILENO))
10128 errx(1, "standard input is not a tty");
10130 #if !defined(PROFILE)
10131 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
10132 NULL) == -1)
10133 err(1, "pledge");
10134 #endif
10136 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
10137 switch (ch) {
10138 case 'h':
10139 hflag = 1;
10140 break;
10141 case 'V':
10142 Vflag = 1;
10143 break;
10144 default:
10145 usage(hflag, 1);
10146 /* NOTREACHED */
10150 argc -= optind;
10151 argv += optind;
10152 optind = 1;
10153 optreset = 1;
10155 if (Vflag) {
10156 got_version_print_str();
10157 return 0;
10160 if (argc == 0) {
10161 if (hflag)
10162 usage(hflag, 0);
10163 /* Build an argument vector which runs a default command. */
10164 cmd = &tog_commands[0];
10165 argc = 1;
10166 cmd_argv = make_argv(argc, cmd->name);
10167 } else {
10168 size_t i;
10170 /* Did the user specify a command? */
10171 for (i = 0; i < nitems(tog_commands); i++) {
10172 if (strncmp(tog_commands[i].name, argv[0],
10173 strlen(argv[0])) == 0) {
10174 cmd = &tog_commands[i];
10175 break;
10180 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
10181 if (diff_algo_str) {
10182 if (strcasecmp(diff_algo_str, "patience") == 0)
10183 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
10184 if (strcasecmp(diff_algo_str, "myers") == 0)
10185 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
10188 tog_base_commit.idx = -1;
10189 tog_base_commit.marker = GOT_WORKTREE_STATE_UNKNOWN;
10191 if (cmd == NULL) {
10192 if (argc != 1)
10193 usage(0, 1);
10194 /* No command specified; try log with a path */
10195 error = tog_log_with_path(argc, argv);
10196 } else {
10197 if (hflag)
10198 cmd->cmd_usage();
10199 else
10200 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
10203 if (using_mock_io) {
10204 io_err = tog_io_close();
10205 if (error == NULL)
10206 error = io_err;
10208 endwin();
10209 if (cmd_argv) {
10210 int i;
10211 for (i = 0; i < argc; i++)
10212 free(cmd_argv[i]);
10213 free(cmd_argv);
10216 if (error && error->code != GOT_ERR_CANCELLED &&
10217 error->code != GOT_ERR_EOF &&
10218 error->code != GOT_ERR_PRIVSEP_EXIT &&
10219 error->code != GOT_ERR_PRIVSEP_PIPE &&
10220 !(error->code == GOT_ERR_ERRNO && errno == EINTR)) {
10221 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10222 return 1;
10224 return 0;