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_MYERS;
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(s->in_repo_path);
3539 s->in_repo_path = NULL;
3540 free(s->start_id);
3541 s->start_id = NULL;
3542 free(s->head_ref_name);
3543 s->head_ref_name = NULL;
3544 return err;
3548 * We use two queues to implement the limit feature: first consists of
3549 * commits matching the current limit_regex; second is the real queue
3550 * of all known commits (real_commits). When the user starts limiting,
3551 * we swap queues such that all movement and displaying functionality
3552 * works with very slight change.
3554 static const struct got_error *
3555 limit_log_view(struct tog_view *view)
3557 struct tog_log_view_state *s = &view->state.log;
3558 struct commit_queue_entry *entry;
3559 struct tog_view *v = view;
3560 const struct got_error *err = NULL;
3561 char pattern[1024];
3562 int ret;
3564 if (view_is_hsplit_top(view))
3565 v = view->child;
3566 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3567 v = view->parent;
3569 if (tog_io.input_str != NULL) {
3570 if (strlcpy(pattern, tog_io.input_str, sizeof(pattern)) >=
3571 sizeof(pattern))
3572 return got_error(GOT_ERR_NO_SPACE);
3573 } else {
3574 wmove(v->window, v->nlines - 1, 0);
3575 wclrtoeol(v->window);
3576 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3577 nodelay(v->window, FALSE);
3578 nocbreak();
3579 echo();
3580 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3581 cbreak();
3582 noecho();
3583 nodelay(v->window, TRUE);
3584 if (ret == ERR)
3585 return NULL;
3588 if (*pattern == '\0') {
3590 * Safety measure for the situation where the user
3591 * resets limit without previously limiting anything.
3593 if (!s->limit_view)
3594 return NULL;
3597 * User could have pressed Ctrl+L, which refreshed the
3598 * commit queues, it means we can't save previously
3599 * (before limit took place) displayed entries,
3600 * because they would point to already free'ed memory,
3601 * so we are forced to always select first entry of
3602 * the queue.
3604 s->commits = &s->real_commits;
3605 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3606 s->selected_entry = s->first_displayed_entry;
3607 s->selected = 0;
3608 s->limit_view = 0;
3610 return NULL;
3613 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3614 return NULL;
3616 s->limit_view = 1;
3618 /* Clear the screen while loading limit view */
3619 s->first_displayed_entry = NULL;
3620 s->last_displayed_entry = NULL;
3621 s->selected_entry = NULL;
3622 s->commits = &s->limit_commits;
3624 /* Prepare limit queue for new search */
3625 free_commits(&s->limit_commits);
3626 s->limit_commits.ncommits = 0;
3628 /* First process commits, which are in queue already */
3629 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3630 int have_match = 0;
3632 err = match_commit(&have_match, entry->id,
3633 entry->commit, &s->limit_regex);
3634 if (err)
3635 return err;
3637 if (have_match) {
3638 struct commit_queue_entry *matched;
3640 matched = alloc_commit_queue_entry(entry->commit,
3641 entry->id);
3642 if (matched == NULL) {
3643 err = got_error_from_errno(
3644 "alloc_commit_queue_entry");
3645 break;
3647 matched->commit = entry->commit;
3648 got_object_commit_retain(entry->commit);
3650 matched->idx = s->limit_commits.ncommits;
3651 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3652 matched, entry);
3653 s->limit_commits.ncommits++;
3657 /* Second process all the commits, until we fill the screen */
3658 if (s->limit_commits.ncommits < view->nlines - 1 &&
3659 !s->thread_args.log_complete) {
3660 s->thread_args.commits_needed +=
3661 view->nlines - s->limit_commits.ncommits - 1;
3662 err = trigger_log_thread(view, 1);
3663 if (err)
3664 return err;
3667 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3668 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3669 s->selected = 0;
3671 return NULL;
3674 static const struct got_error *
3675 search_start_log_view(struct tog_view *view)
3677 struct tog_log_view_state *s = &view->state.log;
3679 s->matched_entry = NULL;
3680 s->search_entry = NULL;
3681 return NULL;
3684 static const struct got_error *
3685 search_next_log_view(struct tog_view *view)
3687 const struct got_error *err = NULL;
3688 struct tog_log_view_state *s = &view->state.log;
3689 struct commit_queue_entry *entry;
3691 /* Display progress update in log view. */
3692 show_log_view(view);
3693 update_panels();
3694 doupdate();
3696 if (s->search_entry) {
3697 if (!using_mock_io) {
3698 int errcode, ch;
3700 errcode = pthread_mutex_unlock(&tog_mutex);
3701 if (errcode)
3702 return got_error_set_errno(errcode,
3703 "pthread_mutex_unlock");
3704 ch = wgetch(view->window);
3705 errcode = pthread_mutex_lock(&tog_mutex);
3706 if (errcode)
3707 return got_error_set_errno(errcode,
3708 "pthread_mutex_lock");
3709 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3710 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3711 return NULL;
3714 if (view->searching == TOG_SEARCH_FORWARD)
3715 entry = TAILQ_NEXT(s->search_entry, entry);
3716 else
3717 entry = TAILQ_PREV(s->search_entry,
3718 commit_queue_head, entry);
3719 } else if (s->matched_entry) {
3721 * If the user has moved the cursor after we hit a match,
3722 * the position from where we should continue searching
3723 * might have changed.
3725 if (view->searching == TOG_SEARCH_FORWARD)
3726 entry = TAILQ_NEXT(s->selected_entry, entry);
3727 else
3728 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3729 entry);
3730 } else {
3731 entry = s->selected_entry;
3734 while (1) {
3735 int have_match = 0;
3737 if (entry == NULL) {
3738 if (s->thread_args.log_complete ||
3739 view->searching == TOG_SEARCH_BACKWARD) {
3740 view->search_next_done =
3741 (s->matched_entry == NULL ?
3742 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3743 s->search_entry = NULL;
3744 return NULL;
3747 * Poke the log thread for more commits and return,
3748 * allowing the main loop to make progress. Search
3749 * will resume at s->search_entry once we come back.
3751 s->search_entry = s->selected_entry;
3752 s->thread_args.commits_needed++;
3753 return trigger_log_thread(view, 0);
3756 err = match_commit(&have_match, entry->id, entry->commit,
3757 &view->regex);
3758 if (err)
3759 break;
3760 if (have_match) {
3761 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3762 s->matched_entry = entry;
3763 break;
3766 s->search_entry = entry;
3767 if (view->searching == TOG_SEARCH_FORWARD)
3768 entry = TAILQ_NEXT(entry, entry);
3769 else
3770 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3773 if (s->matched_entry) {
3774 int cur = s->selected_entry->idx;
3775 while (cur < s->matched_entry->idx) {
3776 err = input_log_view(NULL, view, KEY_DOWN);
3777 if (err)
3778 return err;
3779 cur++;
3781 while (cur > s->matched_entry->idx) {
3782 err = input_log_view(NULL, view, KEY_UP);
3783 if (err)
3784 return err;
3785 cur--;
3789 s->search_entry = NULL;
3791 return NULL;
3794 static const struct got_error *
3795 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3796 struct got_repository *repo, const char *head_ref_name,
3797 const char *in_repo_path, int log_branches,
3798 struct got_worktree *worktree)
3800 const struct got_error *err = NULL;
3801 struct tog_log_view_state *s = &view->state.log;
3802 struct got_repository *thread_repo = NULL;
3803 struct got_commit_graph *thread_graph = NULL;
3804 int errcode;
3806 if (in_repo_path != s->in_repo_path) {
3807 free(s->in_repo_path);
3808 s->in_repo_path = strdup(in_repo_path);
3809 if (s->in_repo_path == NULL) {
3810 err = got_error_from_errno("strdup");
3811 goto done;
3815 /* The commit queue only contains commits being displayed. */
3816 TAILQ_INIT(&s->real_commits.head);
3817 s->real_commits.ncommits = 0;
3818 s->commits = &s->real_commits;
3820 TAILQ_INIT(&s->limit_commits.head);
3821 s->limit_view = 0;
3822 s->limit_commits.ncommits = 0;
3824 s->repo = repo;
3825 if (head_ref_name) {
3826 s->head_ref_name = strdup(head_ref_name);
3827 if (s->head_ref_name == NULL) {
3828 err = got_error_from_errno("strdup");
3829 goto done;
3832 s->start_id = got_object_id_dup(start_id);
3833 if (s->start_id == NULL) {
3834 err = got_error_from_errno("got_object_id_dup");
3835 goto done;
3837 s->log_branches = log_branches;
3838 s->use_committer = 1;
3840 STAILQ_INIT(&s->colors);
3841 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3842 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3843 get_color_value("TOG_COLOR_COMMIT"));
3844 if (err)
3845 goto done;
3846 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3847 get_color_value("TOG_COLOR_AUTHOR"));
3848 if (err) {
3849 free_colors(&s->colors);
3850 goto done;
3852 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3853 get_color_value("TOG_COLOR_DATE"));
3854 if (err) {
3855 free_colors(&s->colors);
3856 goto done;
3860 view->show = show_log_view;
3861 view->input = input_log_view;
3862 view->resize = resize_log_view;
3863 view->close = close_log_view;
3864 view->search_start = search_start_log_view;
3865 view->search_next = search_next_log_view;
3867 if (s->thread_args.pack_fds == NULL) {
3868 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3869 if (err)
3870 goto done;
3872 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3873 s->thread_args.pack_fds);
3874 if (err)
3875 goto done;
3876 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3877 !s->log_branches);
3878 if (err)
3879 goto done;
3880 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3881 s->repo, NULL, NULL);
3882 if (err)
3883 goto done;
3885 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3886 if (errcode) {
3887 err = got_error_set_errno(errcode, "pthread_cond_init");
3888 goto done;
3890 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3891 if (errcode) {
3892 err = got_error_set_errno(errcode, "pthread_cond_init");
3893 goto done;
3896 if (using_mock_io) {
3897 int rc;
3899 rc = pthread_cond_init(&s->thread_args.log_loaded, NULL);
3900 if (rc)
3901 return got_error_set_errno(rc, "pthread_cond_init");
3904 s->thread_args.commits_needed = view->nlines;
3905 s->thread_args.graph = thread_graph;
3906 s->thread_args.real_commits = &s->real_commits;
3907 s->thread_args.limit_commits = &s->limit_commits;
3908 s->thread_args.in_repo_path = s->in_repo_path;
3909 s->thread_args.start_id = s->start_id;
3910 s->thread_args.repo = thread_repo;
3911 s->thread_args.log_complete = 0;
3912 s->thread_args.quit = &s->quit;
3913 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3914 s->thread_args.selected_entry = &s->selected_entry;
3915 s->thread_args.searching = &view->searching;
3916 s->thread_args.search_next_done = &view->search_next_done;
3917 s->thread_args.regex = &view->regex;
3918 s->thread_args.limiting = &s->limit_view;
3919 s->thread_args.limit_regex = &s->limit_regex;
3920 s->thread_args.limit_commits = &s->limit_commits;
3921 s->thread_args.worktree = worktree;
3922 if (worktree)
3923 s->thread_args.need_commit_marker = 1;
3924 done:
3925 if (err) {
3926 if (view->close == NULL)
3927 close_log_view(view);
3928 view_close(view);
3930 return err;
3933 static const struct got_error *
3934 show_log_view(struct tog_view *view)
3936 const struct got_error *err;
3937 struct tog_log_view_state *s = &view->state.log;
3939 if (s->thread == NULL) {
3940 int errcode = pthread_create(&s->thread, NULL, log_thread,
3941 &s->thread_args);
3942 if (errcode)
3943 return got_error_set_errno(errcode, "pthread_create");
3944 if (s->thread_args.commits_needed > 0) {
3945 err = trigger_log_thread(view, 1);
3946 if (err)
3947 return err;
3951 return draw_commits(view);
3954 static void
3955 log_move_cursor_up(struct tog_view *view, int page, int home)
3957 struct tog_log_view_state *s = &view->state.log;
3959 if (s->first_displayed_entry == NULL)
3960 return;
3961 if (s->selected_entry->idx == 0)
3962 view->count = 0;
3964 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3965 || home)
3966 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3968 if (!page && !home && s->selected > 0)
3969 --s->selected;
3970 else
3971 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3973 select_commit(s);
3974 return;
3977 static const struct got_error *
3978 log_move_cursor_down(struct tog_view *view, int page)
3980 struct tog_log_view_state *s = &view->state.log;
3981 const struct got_error *err = NULL;
3982 int eos = view->nlines - 2;
3984 if (s->first_displayed_entry == NULL)
3985 return NULL;
3987 if (s->thread_args.log_complete &&
3988 s->selected_entry->idx >= s->commits->ncommits - 1)
3989 return NULL;
3991 if (view_is_hsplit_top(view))
3992 --eos; /* border consumes the last line */
3994 if (!page) {
3995 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3996 ++s->selected;
3997 else
3998 err = log_scroll_down(view, 1);
3999 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
4000 struct commit_queue_entry *entry;
4001 int n;
4003 s->selected = 0;
4004 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
4005 s->last_displayed_entry = entry;
4006 for (n = 0; n <= eos; n++) {
4007 if (entry == NULL)
4008 break;
4009 s->first_displayed_entry = entry;
4010 entry = TAILQ_PREV(entry, commit_queue_head, entry);
4012 if (n > 0)
4013 s->selected = n - 1;
4014 } else {
4015 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
4016 s->thread_args.log_complete)
4017 s->selected += MIN(page,
4018 s->commits->ncommits - s->selected_entry->idx - 1);
4019 else
4020 err = log_scroll_down(view, page);
4022 if (err)
4023 return err;
4026 * We might necessarily overshoot in horizontal
4027 * splits; if so, select the last displayed commit.
4029 if (s->first_displayed_entry && s->last_displayed_entry) {
4030 s->selected = MIN(s->selected,
4031 s->last_displayed_entry->idx -
4032 s->first_displayed_entry->idx);
4035 select_commit(s);
4037 if (s->thread_args.log_complete &&
4038 s->selected_entry->idx == s->commits->ncommits - 1)
4039 view->count = 0;
4041 return NULL;
4044 static void
4045 view_get_split(struct tog_view *view, int *y, int *x)
4047 *x = 0;
4048 *y = 0;
4050 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
4051 if (view->child && view->child->resized_y)
4052 *y = view->child->resized_y;
4053 else if (view->resized_y)
4054 *y = view->resized_y;
4055 else
4056 *y = view_split_begin_y(view->lines);
4057 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
4058 if (view->child && view->child->resized_x)
4059 *x = view->child->resized_x;
4060 else if (view->resized_x)
4061 *x = view->resized_x;
4062 else
4063 *x = view_split_begin_x(view->begin_x);
4067 /* Split view horizontally at y and offset view->state->selected line. */
4068 static const struct got_error *
4069 view_init_hsplit(struct tog_view *view, int y)
4071 const struct got_error *err = NULL;
4073 view->nlines = y;
4074 view->ncols = COLS;
4075 err = view_resize(view);
4076 if (err)
4077 return err;
4079 err = offset_selection_down(view);
4081 return err;
4084 static const struct got_error *
4085 log_goto_line(struct tog_view *view, int nlines)
4087 const struct got_error *err = NULL;
4088 struct tog_log_view_state *s = &view->state.log;
4089 int g, idx = s->selected_entry->idx;
4091 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
4092 return NULL;
4094 g = view->gline;
4095 view->gline = 0;
4097 if (g >= s->first_displayed_entry->idx + 1 &&
4098 g <= s->last_displayed_entry->idx + 1 &&
4099 g - s->first_displayed_entry->idx - 1 < nlines) {
4100 s->selected = g - s->first_displayed_entry->idx - 1;
4101 select_commit(s);
4102 return NULL;
4105 if (idx + 1 < g) {
4106 err = log_move_cursor_down(view, g - idx - 1);
4107 if (!err && g > s->selected_entry->idx + 1)
4108 err = log_move_cursor_down(view,
4109 g - s->first_displayed_entry->idx - 1);
4110 if (err)
4111 return err;
4112 } else if (idx + 1 > g)
4113 log_move_cursor_up(view, idx - g + 1, 0);
4115 if (g < nlines && s->first_displayed_entry->idx == 0)
4116 s->selected = g - 1;
4118 select_commit(s);
4119 return NULL;
4123 static void
4124 horizontal_scroll_input(struct tog_view *view, int ch)
4127 switch (ch) {
4128 case KEY_LEFT:
4129 case 'h':
4130 view->x -= MIN(view->x, 2);
4131 if (view->x <= 0)
4132 view->count = 0;
4133 break;
4134 case KEY_RIGHT:
4135 case 'l':
4136 if (view->x + view->ncols / 2 < view->maxx)
4137 view->x += 2;
4138 else
4139 view->count = 0;
4140 break;
4141 case '0':
4142 view->x = 0;
4143 break;
4144 case '$':
4145 view->x = MAX(view->maxx - view->ncols / 2, 0);
4146 view->count = 0;
4147 break;
4148 default:
4149 break;
4153 static const struct got_error *
4154 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4156 const struct got_error *err = NULL;
4157 struct tog_log_view_state *s = &view->state.log;
4158 int eos, nscroll;
4160 if (s->thread_args.load_all) {
4161 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4162 s->thread_args.load_all = 0;
4163 else if (s->thread_args.log_complete) {
4164 err = log_move_cursor_down(view, s->commits->ncommits);
4165 s->thread_args.load_all = 0;
4167 if (err)
4168 return err;
4171 eos = nscroll = view->nlines - 1;
4172 if (view_is_hsplit_top(view))
4173 --eos; /* border */
4175 if (view->gline)
4176 return log_goto_line(view, eos);
4178 switch (ch) {
4179 case '&':
4180 err = limit_log_view(view);
4181 break;
4182 case 'q':
4183 s->quit = 1;
4184 break;
4185 case '0':
4186 case '$':
4187 case KEY_RIGHT:
4188 case 'l':
4189 case KEY_LEFT:
4190 case 'h':
4191 horizontal_scroll_input(view, ch);
4192 break;
4193 case 'k':
4194 case KEY_UP:
4195 case '<':
4196 case ',':
4197 case CTRL('p'):
4198 log_move_cursor_up(view, 0, 0);
4199 break;
4200 case 'g':
4201 case '=':
4202 case KEY_HOME:
4203 log_move_cursor_up(view, 0, 1);
4204 view->count = 0;
4205 break;
4206 case CTRL('u'):
4207 case 'u':
4208 nscroll /= 2;
4209 /* FALL THROUGH */
4210 case KEY_PPAGE:
4211 case CTRL('b'):
4212 case 'b':
4213 log_move_cursor_up(view, nscroll, 0);
4214 break;
4215 case 'j':
4216 case KEY_DOWN:
4217 case '>':
4218 case '.':
4219 case CTRL('n'):
4220 err = log_move_cursor_down(view, 0);
4221 break;
4222 case '@':
4223 s->use_committer = !s->use_committer;
4224 view->action = s->use_committer ?
4225 "show committer" : "show commit author";
4226 break;
4227 case 'G':
4228 case '*':
4229 case KEY_END: {
4230 /* We don't know yet how many commits, so we're forced to
4231 * traverse them all. */
4232 view->count = 0;
4233 s->thread_args.load_all = 1;
4234 if (!s->thread_args.log_complete)
4235 return trigger_log_thread(view, 0);
4236 err = log_move_cursor_down(view, s->commits->ncommits);
4237 s->thread_args.load_all = 0;
4238 break;
4240 case CTRL('d'):
4241 case 'd':
4242 nscroll /= 2;
4243 /* FALL THROUGH */
4244 case KEY_NPAGE:
4245 case CTRL('f'):
4246 case 'f':
4247 case ' ':
4248 err = log_move_cursor_down(view, nscroll);
4249 break;
4250 case KEY_RESIZE:
4251 if (s->selected > view->nlines - 2)
4252 s->selected = view->nlines - 2;
4253 if (s->selected > s->commits->ncommits - 1)
4254 s->selected = s->commits->ncommits - 1;
4255 select_commit(s);
4256 if (s->commits->ncommits < view->nlines - 1 &&
4257 !s->thread_args.log_complete) {
4258 s->thread_args.commits_needed += (view->nlines - 1) -
4259 s->commits->ncommits;
4260 err = trigger_log_thread(view, 1);
4262 break;
4263 case KEY_ENTER:
4264 case '\r':
4265 view->count = 0;
4266 if (s->selected_entry == NULL)
4267 break;
4268 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4269 break;
4270 case 'T':
4271 view->count = 0;
4272 if (s->selected_entry == NULL)
4273 break;
4274 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4275 break;
4276 case KEY_BACKSPACE:
4277 case CTRL('l'):
4278 case 'B':
4279 view->count = 0;
4280 if (ch == KEY_BACKSPACE &&
4281 got_path_is_root_dir(s->in_repo_path))
4282 break;
4283 err = stop_log_thread(s);
4284 if (err)
4285 return err;
4286 if (ch == KEY_BACKSPACE) {
4287 char *parent_path;
4288 err = got_path_dirname(&parent_path, s->in_repo_path);
4289 if (err)
4290 return err;
4291 free(s->in_repo_path);
4292 s->in_repo_path = parent_path;
4293 s->thread_args.in_repo_path = s->in_repo_path;
4294 } else if (ch == CTRL('l')) {
4295 struct got_object_id *start_id;
4296 err = got_repo_match_object_id(&start_id, NULL,
4297 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4298 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4299 if (err) {
4300 if (s->head_ref_name == NULL ||
4301 err->code != GOT_ERR_NOT_REF)
4302 return err;
4303 /* Try to cope with deleted references. */
4304 free(s->head_ref_name);
4305 s->head_ref_name = NULL;
4306 err = got_repo_match_object_id(&start_id,
4307 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4308 &tog_refs, s->repo);
4309 if (err)
4310 return err;
4312 free(s->start_id);
4313 s->start_id = start_id;
4314 s->thread_args.start_id = s->start_id;
4315 } else /* 'B' */
4316 s->log_branches = !s->log_branches;
4318 if (s->thread_args.pack_fds == NULL) {
4319 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4320 if (err)
4321 return err;
4323 err = got_repo_open(&s->thread_args.repo,
4324 got_repo_get_path(s->repo), NULL,
4325 s->thread_args.pack_fds);
4326 if (err)
4327 return err;
4328 tog_free_refs();
4329 err = tog_load_refs(s->repo, 0);
4330 if (err)
4331 return err;
4332 err = got_commit_graph_open(&s->thread_args.graph,
4333 s->in_repo_path, !s->log_branches);
4334 if (err)
4335 return err;
4336 err = got_commit_graph_iter_start(s->thread_args.graph,
4337 s->start_id, s->repo, NULL, NULL);
4338 if (err)
4339 return err;
4340 free_commits(&s->real_commits);
4341 free_commits(&s->limit_commits);
4342 s->first_displayed_entry = NULL;
4343 s->last_displayed_entry = NULL;
4344 s->selected_entry = NULL;
4345 s->selected = 0;
4346 s->thread_args.log_complete = 0;
4347 s->quit = 0;
4348 s->thread_args.commits_needed = view->lines;
4349 s->matched_entry = NULL;
4350 s->search_entry = NULL;
4351 view->offset = 0;
4352 break;
4353 case 'R':
4354 view->count = 0;
4355 err = view_request_new(new_view, view, TOG_VIEW_REF);
4356 break;
4357 default:
4358 view->count = 0;
4359 break;
4362 return err;
4365 static const struct got_error *
4366 apply_unveil(const char *repo_path, const char *worktree_path)
4368 const struct got_error *error;
4370 #ifdef PROFILE
4371 if (unveil("gmon.out", "rwc") != 0)
4372 return got_error_from_errno2("unveil", "gmon.out");
4373 #endif
4374 if (repo_path && unveil(repo_path, "r") != 0)
4375 return got_error_from_errno2("unveil", repo_path);
4377 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4378 return got_error_from_errno2("unveil", worktree_path);
4380 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4381 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4383 error = got_privsep_unveil_exec_helpers();
4384 if (error != NULL)
4385 return error;
4387 if (unveil(NULL, NULL) != 0)
4388 return got_error_from_errno("unveil");
4390 return NULL;
4393 static const struct got_error *
4394 init_mock_term(const char *test_script_path)
4396 const struct got_error *err = NULL;
4397 const char *screen_dump_path;
4398 int in;
4400 if (test_script_path == NULL || *test_script_path == '\0')
4401 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4403 tog_io.f = fopen(test_script_path, "re");
4404 if (tog_io.f == NULL) {
4405 err = got_error_from_errno_fmt("fopen: %s",
4406 test_script_path);
4407 goto done;
4410 /* test mode, we don't want any output */
4411 tog_io.cout = fopen("/dev/null", "w+");
4412 if (tog_io.cout == NULL) {
4413 err = got_error_from_errno2("fopen", "/dev/null");
4414 goto done;
4417 in = dup(fileno(tog_io.cout));
4418 if (in == -1) {
4419 err = got_error_from_errno("dup");
4420 goto done;
4422 tog_io.cin = fdopen(in, "r");
4423 if (tog_io.cin == NULL) {
4424 err = got_error_from_errno("fdopen");
4425 close(in);
4426 goto done;
4429 screen_dump_path = getenv("TOG_SCR_DUMP");
4430 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4431 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4432 tog_io.sdump = fopen(screen_dump_path, "we");
4433 if (tog_io.sdump == NULL) {
4434 err = got_error_from_errno2("fopen", screen_dump_path);
4435 goto done;
4438 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4439 err = got_error_from_errno("fseeko");
4440 goto done;
4443 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4444 err = got_error_msg(GOT_ERR_IO,
4445 "newterm: failed to initialise curses");
4447 using_mock_io = 1;
4449 done:
4450 if (err)
4451 tog_io_close();
4452 return err;
4455 static void
4456 init_curses(void)
4458 if (using_mock_io) /* In test mode we use a fake terminal */
4459 return;
4461 initscr();
4463 cbreak();
4464 halfdelay(1); /* Fast refresh while initial view is loading. */
4465 noecho();
4466 nonl();
4467 intrflush(stdscr, FALSE);
4468 keypad(stdscr, TRUE);
4469 curs_set(0);
4470 if (getenv("TOG_COLORS") != NULL) {
4471 start_color();
4472 use_default_colors();
4475 return;
4478 static const struct got_error *
4479 set_tog_base_commit(struct got_repository *repo, struct got_worktree *worktree)
4481 tog_base_commit.id = got_object_id_dup(
4482 got_worktree_get_base_commit_id(worktree));
4483 if (tog_base_commit.id == NULL)
4484 return got_error_from_errno( "got_object_id_dup");
4486 return NULL;
4489 static const struct got_error *
4490 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4491 struct got_repository *repo, struct got_worktree *worktree)
4493 const struct got_error *err = NULL;
4495 if (argc == 0) {
4496 *in_repo_path = strdup("/");
4497 if (*in_repo_path == NULL)
4498 return got_error_from_errno("strdup");
4499 return NULL;
4502 if (worktree) {
4503 const char *prefix = got_worktree_get_path_prefix(worktree);
4504 char *p;
4506 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4507 if (err)
4508 return err;
4509 if (asprintf(in_repo_path, "%s%s%s", prefix,
4510 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4511 p) == -1) {
4512 err = got_error_from_errno("asprintf");
4513 *in_repo_path = NULL;
4515 free(p);
4516 } else
4517 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4519 return err;
4522 static const struct got_error *
4523 cmd_log(int argc, char *argv[])
4525 const struct got_error *error;
4526 struct got_repository *repo = NULL;
4527 struct got_worktree *worktree = NULL;
4528 struct got_object_id *start_id = NULL;
4529 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4530 char *keyword_idstr = NULL, *start_commit = NULL, *label = NULL;
4531 struct got_reference *ref = NULL;
4532 const char *head_ref_name = NULL;
4533 int ch, log_branches = 0;
4534 struct tog_view *view;
4535 int *pack_fds = NULL;
4537 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4538 switch (ch) {
4539 case 'b':
4540 log_branches = 1;
4541 break;
4542 case 'c':
4543 start_commit = optarg;
4544 break;
4545 case 'r':
4546 repo_path = realpath(optarg, NULL);
4547 if (repo_path == NULL)
4548 return got_error_from_errno2("realpath",
4549 optarg);
4550 break;
4551 default:
4552 usage_log();
4553 /* NOTREACHED */
4557 argc -= optind;
4558 argv += optind;
4560 if (argc > 1)
4561 usage_log();
4563 error = got_repo_pack_fds_open(&pack_fds);
4564 if (error != NULL)
4565 goto done;
4567 if (repo_path == NULL) {
4568 cwd = getcwd(NULL, 0);
4569 if (cwd == NULL) {
4570 error = got_error_from_errno("getcwd");
4571 goto done;
4573 error = got_worktree_open(&worktree, cwd, NULL);
4574 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4575 goto done;
4576 if (worktree)
4577 repo_path =
4578 strdup(got_worktree_get_repo_path(worktree));
4579 else
4580 repo_path = strdup(cwd);
4581 if (repo_path == NULL) {
4582 error = got_error_from_errno("strdup");
4583 goto done;
4587 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4588 if (error != NULL)
4589 goto done;
4591 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4592 repo, worktree);
4593 if (error)
4594 goto done;
4596 init_curses();
4598 error = apply_unveil(got_repo_get_path(repo),
4599 worktree ? got_worktree_get_root_path(worktree) : NULL);
4600 if (error)
4601 goto done;
4603 /* already loaded by tog_log_with_path()? */
4604 if (TAILQ_EMPTY(&tog_refs)) {
4605 error = tog_load_refs(repo, 0);
4606 if (error)
4607 goto done;
4610 if (start_commit == NULL) {
4611 error = got_repo_match_object_id(&start_id, &label,
4612 worktree ? got_worktree_get_head_ref_name(worktree) :
4613 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4614 if (error)
4615 goto done;
4616 head_ref_name = label;
4617 } else {
4618 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4619 repo, worktree);
4620 if (error != NULL)
4621 goto done;
4622 if (keyword_idstr != NULL)
4623 start_commit = keyword_idstr;
4625 error = got_ref_open(&ref, repo, start_commit, 0);
4626 if (error == NULL)
4627 head_ref_name = got_ref_get_name(ref);
4628 else if (error->code != GOT_ERR_NOT_REF)
4629 goto done;
4630 error = got_repo_match_object_id(&start_id, NULL,
4631 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4632 if (error)
4633 goto done;
4636 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4637 if (view == NULL) {
4638 error = got_error_from_errno("view_open");
4639 goto done;
4642 if (worktree) {
4643 error = set_tog_base_commit(repo, worktree);
4644 if (error != NULL)
4645 goto done;
4648 error = open_log_view(view, start_id, repo, head_ref_name,
4649 in_repo_path, log_branches, worktree);
4650 if (error)
4651 goto done;
4653 if (worktree) {
4654 /* The work tree will be closed by the log thread. */
4655 worktree = NULL;
4658 error = view_loop(view);
4660 done:
4661 free(tog_base_commit.id);
4662 free(keyword_idstr);
4663 free(in_repo_path);
4664 free(repo_path);
4665 free(cwd);
4666 free(start_id);
4667 free(label);
4668 if (ref)
4669 got_ref_close(ref);
4670 if (repo) {
4671 const struct got_error *close_err = got_repo_close(repo);
4672 if (error == NULL)
4673 error = close_err;
4675 if (worktree)
4676 got_worktree_close(worktree);
4677 if (pack_fds) {
4678 const struct got_error *pack_err =
4679 got_repo_pack_fds_close(pack_fds);
4680 if (error == NULL)
4681 error = pack_err;
4683 tog_free_refs();
4684 return error;
4687 __dead static void
4688 usage_diff(void)
4690 endwin();
4691 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4692 "object1 object2\n", getprogname());
4693 exit(1);
4696 static int
4697 match_line(const char *line, regex_t *regex, size_t nmatch,
4698 regmatch_t *regmatch)
4700 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4703 static struct tog_color *
4704 match_color(struct tog_colors *colors, const char *line)
4706 struct tog_color *tc = NULL;
4708 STAILQ_FOREACH(tc, colors, entry) {
4709 if (match_line(line, &tc->regex, 0, NULL))
4710 return tc;
4713 return NULL;
4716 static const struct got_error *
4717 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4718 WINDOW *window, int skipcol, regmatch_t *regmatch)
4720 const struct got_error *err = NULL;
4721 char *exstr = NULL;
4722 wchar_t *wline = NULL;
4723 int rme, rms, n, width, scrollx;
4724 int width0 = 0, width1 = 0, width2 = 0;
4725 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4727 *wtotal = 0;
4729 rms = regmatch->rm_so;
4730 rme = regmatch->rm_eo;
4732 err = expand_tab(&exstr, line);
4733 if (err)
4734 return err;
4736 /* Split the line into 3 segments, according to match offsets. */
4737 seg0 = strndup(exstr, rms);
4738 if (seg0 == NULL) {
4739 err = got_error_from_errno("strndup");
4740 goto done;
4742 seg1 = strndup(exstr + rms, rme - rms);
4743 if (seg1 == NULL) {
4744 err = got_error_from_errno("strndup");
4745 goto done;
4747 seg2 = strdup(exstr + rme);
4748 if (seg2 == NULL) {
4749 err = got_error_from_errno("strndup");
4750 goto done;
4753 /* draw up to matched token if we haven't scrolled past it */
4754 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4755 col_tab_align, 1);
4756 if (err)
4757 goto done;
4758 n = MAX(width0 - skipcol, 0);
4759 if (n) {
4760 free(wline);
4761 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4762 wlimit, col_tab_align, 1);
4763 if (err)
4764 goto done;
4765 waddwstr(window, &wline[scrollx]);
4766 wlimit -= width;
4767 *wtotal += width;
4770 if (wlimit > 0) {
4771 int i = 0, w = 0;
4772 size_t wlen;
4774 free(wline);
4775 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4776 col_tab_align, 1);
4777 if (err)
4778 goto done;
4779 wlen = wcslen(wline);
4780 while (i < wlen) {
4781 width = wcwidth(wline[i]);
4782 if (width == -1) {
4783 /* should not happen, tabs are expanded */
4784 err = got_error(GOT_ERR_RANGE);
4785 goto done;
4787 if (width0 + w + width > skipcol)
4788 break;
4789 w += width;
4790 i++;
4792 /* draw (visible part of) matched token (if scrolled into it) */
4793 if (width1 - w > 0) {
4794 wattron(window, A_STANDOUT);
4795 waddwstr(window, &wline[i]);
4796 wattroff(window, A_STANDOUT);
4797 wlimit -= (width1 - w);
4798 *wtotal += (width1 - w);
4802 if (wlimit > 0) { /* draw rest of line */
4803 free(wline);
4804 if (skipcol > width0 + width1) {
4805 err = format_line(&wline, &width2, &scrollx, seg2,
4806 skipcol - (width0 + width1), wlimit,
4807 col_tab_align, 1);
4808 if (err)
4809 goto done;
4810 waddwstr(window, &wline[scrollx]);
4811 } else {
4812 err = format_line(&wline, &width2, NULL, seg2, 0,
4813 wlimit, col_tab_align, 1);
4814 if (err)
4815 goto done;
4816 waddwstr(window, wline);
4818 *wtotal += width2;
4820 done:
4821 free(wline);
4822 free(exstr);
4823 free(seg0);
4824 free(seg1);
4825 free(seg2);
4826 return err;
4829 static int
4830 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4832 FILE *f = NULL;
4833 int *eof, *first, *selected;
4835 if (view->type == TOG_VIEW_DIFF) {
4836 struct tog_diff_view_state *s = &view->state.diff;
4838 first = &s->first_displayed_line;
4839 selected = first;
4840 eof = &s->eof;
4841 f = s->f;
4842 } else if (view->type == TOG_VIEW_HELP) {
4843 struct tog_help_view_state *s = &view->state.help;
4845 first = &s->first_displayed_line;
4846 selected = first;
4847 eof = &s->eof;
4848 f = s->f;
4849 } else if (view->type == TOG_VIEW_BLAME) {
4850 struct tog_blame_view_state *s = &view->state.blame;
4852 first = &s->first_displayed_line;
4853 selected = &s->selected_line;
4854 eof = &s->eof;
4855 f = s->blame.f;
4856 } else
4857 return 0;
4859 /* Center gline in the middle of the page like vi(1). */
4860 if (*lineno < view->gline - (view->nlines - 3) / 2)
4861 return 0;
4862 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4863 rewind(f);
4864 *eof = 0;
4865 *first = 1;
4866 *lineno = 0;
4867 *nprinted = 0;
4868 return 0;
4871 *selected = view->gline <= (view->nlines - 3) / 2 ?
4872 view->gline : (view->nlines - 3) / 2 + 1;
4873 view->gline = 0;
4875 return 1;
4878 static const struct got_error *
4879 draw_file(struct tog_view *view, const char *header)
4881 struct tog_diff_view_state *s = &view->state.diff;
4882 regmatch_t *regmatch = &view->regmatch;
4883 const struct got_error *err;
4884 int nprinted = 0;
4885 char *line;
4886 size_t linesize = 0;
4887 ssize_t linelen;
4888 wchar_t *wline;
4889 int width;
4890 int max_lines = view->nlines;
4891 int nlines = s->nlines;
4892 off_t line_offset;
4894 s->lineno = s->first_displayed_line - 1;
4895 line_offset = s->lines[s->first_displayed_line - 1].offset;
4896 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4897 return got_error_from_errno("fseek");
4899 werase(view->window);
4901 if (view->gline > s->nlines - 1)
4902 view->gline = s->nlines - 1;
4904 if (header) {
4905 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4906 1 : view->gline - (view->nlines - 3) / 2 :
4907 s->lineno + s->selected_line;
4909 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4910 return got_error_from_errno("asprintf");
4911 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4912 0, 0);
4913 free(line);
4914 if (err)
4915 return err;
4917 if (view_needs_focus_indication(view))
4918 wstandout(view->window);
4919 waddwstr(view->window, wline);
4920 free(wline);
4921 wline = NULL;
4922 while (width++ < view->ncols)
4923 waddch(view->window, ' ');
4924 if (view_needs_focus_indication(view))
4925 wstandend(view->window);
4927 if (max_lines <= 1)
4928 return NULL;
4929 max_lines--;
4932 s->eof = 0;
4933 view->maxx = 0;
4934 line = NULL;
4935 while (max_lines > 0 && nprinted < max_lines) {
4936 enum got_diff_line_type linetype;
4937 attr_t attr = 0;
4939 linelen = getline(&line, &linesize, s->f);
4940 if (linelen == -1) {
4941 if (feof(s->f)) {
4942 s->eof = 1;
4943 break;
4945 free(line);
4946 return got_ferror(s->f, GOT_ERR_IO);
4949 if (++s->lineno < s->first_displayed_line)
4950 continue;
4951 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4952 continue;
4953 if (s->lineno == view->hiline)
4954 attr = A_STANDOUT;
4956 /* Set view->maxx based on full line length. */
4957 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4958 view->x ? 1 : 0);
4959 if (err) {
4960 free(line);
4961 return err;
4963 view->maxx = MAX(view->maxx, width);
4964 free(wline);
4965 wline = NULL;
4967 linetype = s->lines[s->lineno].type;
4968 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4969 linetype < GOT_DIFF_LINE_CONTEXT)
4970 attr |= COLOR_PAIR(linetype);
4971 if (attr)
4972 wattron(view->window, attr);
4973 if (s->first_displayed_line + nprinted == s->matched_line &&
4974 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4975 err = add_matched_line(&width, line, view->ncols, 0,
4976 view->window, view->x, regmatch);
4977 if (err) {
4978 free(line);
4979 return err;
4981 } else {
4982 int skip;
4983 err = format_line(&wline, &width, &skip, line,
4984 view->x, view->ncols, 0, view->x ? 1 : 0);
4985 if (err) {
4986 free(line);
4987 return err;
4989 waddwstr(view->window, &wline[skip]);
4990 free(wline);
4991 wline = NULL;
4993 if (s->lineno == view->hiline) {
4994 /* highlight full gline length */
4995 while (width++ < view->ncols)
4996 waddch(view->window, ' ');
4997 } else {
4998 if (width <= view->ncols - 1)
4999 waddch(view->window, '\n');
5001 if (attr)
5002 wattroff(view->window, attr);
5003 if (++nprinted == 1)
5004 s->first_displayed_line = s->lineno;
5006 free(line);
5007 if (nprinted >= 1)
5008 s->last_displayed_line = s->first_displayed_line +
5009 (nprinted - 1);
5010 else
5011 s->last_displayed_line = s->first_displayed_line;
5013 view_border(view);
5015 if (s->eof) {
5016 while (nprinted < view->nlines) {
5017 waddch(view->window, '\n');
5018 nprinted++;
5021 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
5022 view->ncols, 0, 0);
5023 if (err) {
5024 return err;
5027 wstandout(view->window);
5028 waddwstr(view->window, wline);
5029 free(wline);
5030 wline = NULL;
5031 wstandend(view->window);
5034 return NULL;
5037 static char *
5038 get_datestr(time_t *time, char *datebuf)
5040 struct tm mytm, *tm;
5041 char *p, *s;
5043 tm = gmtime_r(time, &mytm);
5044 if (tm == NULL)
5045 return NULL;
5046 s = asctime_r(tm, datebuf);
5047 if (s == NULL)
5048 return NULL;
5049 p = strchr(s, '\n');
5050 if (p)
5051 *p = '\0';
5052 return s;
5055 static const struct got_error *
5056 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
5057 off_t off, uint8_t type)
5059 struct got_diff_line *p;
5061 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
5062 if (p == NULL)
5063 return got_error_from_errno("reallocarray");
5064 *lines = p;
5065 (*lines)[*nlines].offset = off;
5066 (*lines)[*nlines].type = type;
5067 (*nlines)++;
5069 return NULL;
5072 static const struct got_error *
5073 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
5074 struct got_diff_line *s_lines, size_t s_nlines)
5076 struct got_diff_line *p;
5077 char buf[BUFSIZ];
5078 size_t i, r;
5080 if (fseeko(src, 0L, SEEK_SET) == -1)
5081 return got_error_from_errno("fseeko");
5083 for (;;) {
5084 r = fread(buf, 1, sizeof(buf), src);
5085 if (r == 0) {
5086 if (ferror(src))
5087 return got_error_from_errno("fread");
5088 if (feof(src))
5089 break;
5091 if (fwrite(buf, 1, r, dst) != r)
5092 return got_ferror(dst, GOT_ERR_IO);
5095 if (s_nlines == 0 && *d_nlines == 0)
5096 return NULL;
5099 * If commit info was in dst, increment line offsets
5100 * of the appended diff content, but skip s_lines[0]
5101 * because offset zero is already in *d_lines.
5103 if (*d_nlines > 0) {
5104 for (i = 1; i < s_nlines; ++i)
5105 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
5107 if (s_nlines > 0) {
5108 --s_nlines;
5109 ++s_lines;
5113 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
5114 if (p == NULL) {
5115 /* d_lines is freed in close_diff_view() */
5116 return got_error_from_errno("reallocarray");
5119 *d_lines = p;
5121 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
5122 *d_nlines += s_nlines;
5124 return NULL;
5127 static const struct got_error *
5128 write_commit_info(struct got_diff_line **lines, size_t *nlines,
5129 struct got_object_id *commit_id, struct got_reflist_head *refs,
5130 struct got_repository *repo, int ignore_ws, int force_text_diff,
5131 struct got_diffstat_cb_arg *dsa, FILE *outfile)
5133 const struct got_error *err = NULL;
5134 char datebuf[26], *datestr;
5135 struct got_commit_object *commit;
5136 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
5137 time_t committer_time;
5138 const char *author, *committer;
5139 char *refs_str = NULL;
5140 struct got_pathlist_entry *pe;
5141 off_t outoff = 0;
5142 int n;
5144 err = build_refs_str(&refs_str, refs, commit_id, repo);
5145 if (err)
5146 return err;
5148 err = got_object_open_as_commit(&commit, repo, commit_id);
5149 if (err)
5150 return err;
5152 err = got_object_id_str(&id_str, commit_id);
5153 if (err) {
5154 err = got_error_from_errno("got_object_id_str");
5155 goto done;
5158 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
5159 if (err)
5160 goto done;
5162 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
5163 refs_str ? refs_str : "", refs_str ? ")" : "");
5164 if (n < 0) {
5165 err = got_error_from_errno("fprintf");
5166 goto done;
5168 outoff += n;
5169 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
5170 if (err)
5171 goto done;
5173 n = fprintf(outfile, "from: %s\n",
5174 got_object_commit_get_author(commit));
5175 if (n < 0) {
5176 err = got_error_from_errno("fprintf");
5177 goto done;
5179 outoff += n;
5180 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5181 if (err)
5182 goto done;
5184 author = got_object_commit_get_author(commit);
5185 committer = got_object_commit_get_committer(commit);
5186 if (strcmp(author, committer) != 0) {
5187 n = fprintf(outfile, "via: %s\n", committer);
5188 if (n < 0) {
5189 err = got_error_from_errno("fprintf");
5190 goto done;
5192 outoff += n;
5193 err = add_line_metadata(lines, nlines, outoff,
5194 GOT_DIFF_LINE_AUTHOR);
5195 if (err)
5196 goto done;
5198 committer_time = got_object_commit_get_committer_time(commit);
5199 datestr = get_datestr(&committer_time, datebuf);
5200 if (datestr) {
5201 n = fprintf(outfile, "date: %s UTC\n", datestr);
5202 if (n < 0) {
5203 err = got_error_from_errno("fprintf");
5204 goto done;
5206 outoff += n;
5207 err = add_line_metadata(lines, nlines, outoff,
5208 GOT_DIFF_LINE_DATE);
5209 if (err)
5210 goto done;
5212 if (got_object_commit_get_nparents(commit) > 1) {
5213 const struct got_object_id_queue *parent_ids;
5214 struct got_object_qid *qid;
5215 int pn = 1;
5216 parent_ids = got_object_commit_get_parent_ids(commit);
5217 STAILQ_FOREACH(qid, parent_ids, entry) {
5218 err = got_object_id_str(&id_str, &qid->id);
5219 if (err)
5220 goto done;
5221 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5222 if (n < 0) {
5223 err = got_error_from_errno("fprintf");
5224 goto done;
5226 outoff += n;
5227 err = add_line_metadata(lines, nlines, outoff,
5228 GOT_DIFF_LINE_META);
5229 if (err)
5230 goto done;
5231 free(id_str);
5232 id_str = NULL;
5236 err = got_object_commit_get_logmsg(&logmsg, commit);
5237 if (err)
5238 goto done;
5239 s = logmsg;
5240 while ((line = strsep(&s, "\n")) != NULL) {
5241 n = fprintf(outfile, "%s\n", line);
5242 if (n < 0) {
5243 err = got_error_from_errno("fprintf");
5244 goto done;
5246 outoff += n;
5247 err = add_line_metadata(lines, nlines, outoff,
5248 GOT_DIFF_LINE_LOGMSG);
5249 if (err)
5250 goto done;
5253 TAILQ_FOREACH(pe, dsa->paths, entry) {
5254 struct got_diff_changed_path *cp = pe->data;
5255 int pad = dsa->max_path_len - pe->path_len + 1;
5257 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5258 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5259 dsa->rm_cols + 1, cp->rm);
5260 if (n < 0) {
5261 err = got_error_from_errno("fprintf");
5262 goto done;
5264 outoff += n;
5265 err = add_line_metadata(lines, nlines, outoff,
5266 GOT_DIFF_LINE_CHANGES);
5267 if (err)
5268 goto done;
5271 fputc('\n', outfile);
5272 outoff++;
5273 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5274 if (err)
5275 goto done;
5277 n = fprintf(outfile,
5278 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5279 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5280 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5281 if (n < 0) {
5282 err = got_error_from_errno("fprintf");
5283 goto done;
5285 outoff += n;
5286 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5287 if (err)
5288 goto done;
5290 fputc('\n', outfile);
5291 outoff++;
5292 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5293 done:
5294 free(id_str);
5295 free(logmsg);
5296 free(refs_str);
5297 got_object_commit_close(commit);
5298 if (err) {
5299 free(*lines);
5300 *lines = NULL;
5301 *nlines = 0;
5303 return err;
5306 static const struct got_error *
5307 create_diff(struct tog_diff_view_state *s)
5309 const struct got_error *err = NULL;
5310 FILE *f = NULL, *tmp_diff_file = NULL;
5311 int obj_type;
5312 struct got_diff_line *lines = NULL;
5313 struct got_pathlist_head changed_paths;
5315 TAILQ_INIT(&changed_paths);
5317 free(s->lines);
5318 s->lines = malloc(sizeof(*s->lines));
5319 if (s->lines == NULL)
5320 return got_error_from_errno("malloc");
5321 s->nlines = 0;
5323 f = got_opentemp();
5324 if (f == NULL) {
5325 err = got_error_from_errno("got_opentemp");
5326 goto done;
5328 tmp_diff_file = got_opentemp();
5329 if (tmp_diff_file == NULL) {
5330 err = got_error_from_errno("got_opentemp");
5331 goto done;
5333 if (s->f && fclose(s->f) == EOF) {
5334 err = got_error_from_errno("fclose");
5335 goto done;
5337 s->f = f;
5339 if (s->id1)
5340 err = got_object_get_type(&obj_type, s->repo, s->id1);
5341 else
5342 err = got_object_get_type(&obj_type, s->repo, s->id2);
5343 if (err)
5344 goto done;
5346 switch (obj_type) {
5347 case GOT_OBJ_TYPE_BLOB:
5348 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5349 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5350 s->label1, s->label2, tog_diff_algo, s->diff_context,
5351 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5352 s->f);
5353 break;
5354 case GOT_OBJ_TYPE_TREE:
5355 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5356 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5357 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5358 s->force_text_diff, NULL, s->repo, s->f);
5359 break;
5360 case GOT_OBJ_TYPE_COMMIT: {
5361 const struct got_object_id_queue *parent_ids;
5362 struct got_object_qid *pid;
5363 struct got_commit_object *commit2;
5364 struct got_reflist_head *refs;
5365 size_t nlines = 0;
5366 struct got_diffstat_cb_arg dsa = {
5367 0, 0, 0, 0, 0, 0,
5368 &changed_paths,
5369 s->ignore_whitespace,
5370 s->force_text_diff,
5371 tog_diff_algo
5374 lines = malloc(sizeof(*lines));
5375 if (lines == NULL) {
5376 err = got_error_from_errno("malloc");
5377 goto done;
5380 /* build diff first in tmp file then append to commit info */
5381 err = got_diff_objects_as_commits(&lines, &nlines,
5382 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5383 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5384 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5385 if (err)
5386 break;
5388 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5389 if (err)
5390 goto done;
5391 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5392 /* Show commit info if we're diffing to a parent/root commit. */
5393 if (s->id1 == NULL) {
5394 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5395 refs, s->repo, s->ignore_whitespace,
5396 s->force_text_diff, &dsa, s->f);
5397 if (err)
5398 goto done;
5399 } else {
5400 parent_ids = got_object_commit_get_parent_ids(commit2);
5401 STAILQ_FOREACH(pid, parent_ids, entry) {
5402 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5403 err = write_commit_info(&s->lines,
5404 &s->nlines, s->id2, refs, s->repo,
5405 s->ignore_whitespace,
5406 s->force_text_diff, &dsa, s->f);
5407 if (err)
5408 goto done;
5409 break;
5413 got_object_commit_close(commit2);
5415 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5416 lines, nlines);
5417 break;
5419 default:
5420 err = got_error(GOT_ERR_OBJ_TYPE);
5421 break;
5423 done:
5424 free(lines);
5425 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5426 if (s->f && fflush(s->f) != 0 && err == NULL)
5427 err = got_error_from_errno("fflush");
5428 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5429 err = got_error_from_errno("fclose");
5430 return err;
5433 static void
5434 diff_view_indicate_progress(struct tog_view *view)
5436 mvwaddstr(view->window, 0, 0, "diffing...");
5437 update_panels();
5438 doupdate();
5441 static const struct got_error *
5442 search_start_diff_view(struct tog_view *view)
5444 struct tog_diff_view_state *s = &view->state.diff;
5446 s->matched_line = 0;
5447 return NULL;
5450 static void
5451 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5452 size_t *nlines, int **first, int **last, int **match, int **selected)
5454 struct tog_diff_view_state *s = &view->state.diff;
5456 *f = s->f;
5457 *nlines = s->nlines;
5458 *line_offsets = NULL;
5459 *match = &s->matched_line;
5460 *first = &s->first_displayed_line;
5461 *last = &s->last_displayed_line;
5462 *selected = &s->selected_line;
5465 static const struct got_error *
5466 search_next_view_match(struct tog_view *view)
5468 const struct got_error *err = NULL;
5469 FILE *f;
5470 int lineno;
5471 char *line = NULL;
5472 size_t linesize = 0;
5473 ssize_t linelen;
5474 off_t *line_offsets;
5475 size_t nlines = 0;
5476 int *first, *last, *match, *selected;
5478 if (!view->search_setup)
5479 return got_error_msg(GOT_ERR_NOT_IMPL,
5480 "view search not supported");
5481 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5482 &match, &selected);
5484 if (!view->searching) {
5485 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5486 return NULL;
5489 if (*match) {
5490 if (view->searching == TOG_SEARCH_FORWARD)
5491 lineno = *first + 1;
5492 else
5493 lineno = *first - 1;
5494 } else
5495 lineno = *first - 1 + *selected;
5497 while (1) {
5498 off_t offset;
5500 if (lineno <= 0 || lineno > nlines) {
5501 if (*match == 0) {
5502 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5503 break;
5506 if (view->searching == TOG_SEARCH_FORWARD)
5507 lineno = 1;
5508 else
5509 lineno = nlines;
5512 offset = view->type == TOG_VIEW_DIFF ?
5513 view->state.diff.lines[lineno - 1].offset :
5514 line_offsets[lineno - 1];
5515 if (fseeko(f, offset, SEEK_SET) != 0) {
5516 free(line);
5517 return got_error_from_errno("fseeko");
5519 linelen = getline(&line, &linesize, f);
5520 if (linelen != -1) {
5521 char *exstr;
5522 err = expand_tab(&exstr, line);
5523 if (err)
5524 break;
5525 if (match_line(exstr, &view->regex, 1,
5526 &view->regmatch)) {
5527 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5528 *match = lineno;
5529 free(exstr);
5530 break;
5532 free(exstr);
5534 if (view->searching == TOG_SEARCH_FORWARD)
5535 lineno++;
5536 else
5537 lineno--;
5539 free(line);
5541 if (*match) {
5542 *first = *match;
5543 *selected = 1;
5546 return err;
5549 static const struct got_error *
5550 close_diff_view(struct tog_view *view)
5552 const struct got_error *err = NULL;
5553 struct tog_diff_view_state *s = &view->state.diff;
5555 free(s->id1);
5556 s->id1 = NULL;
5557 free(s->id2);
5558 s->id2 = NULL;
5559 if (s->f && fclose(s->f) == EOF)
5560 err = got_error_from_errno("fclose");
5561 s->f = NULL;
5562 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5563 err = got_error_from_errno("fclose");
5564 s->f1 = NULL;
5565 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5566 err = got_error_from_errno("fclose");
5567 s->f2 = NULL;
5568 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5569 err = got_error_from_errno("close");
5570 s->fd1 = -1;
5571 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5572 err = got_error_from_errno("close");
5573 s->fd2 = -1;
5574 free(s->lines);
5575 s->lines = NULL;
5576 s->nlines = 0;
5577 return err;
5580 static const struct got_error *
5581 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5582 struct got_object_id *id2, const char *label1, const char *label2,
5583 int diff_context, int ignore_whitespace, int force_text_diff,
5584 struct tog_view *parent_view, struct got_repository *repo)
5586 const struct got_error *err;
5587 struct tog_diff_view_state *s = &view->state.diff;
5589 memset(s, 0, sizeof(*s));
5590 s->fd1 = -1;
5591 s->fd2 = -1;
5593 if (id1 != NULL && id2 != NULL) {
5594 int type1, type2;
5596 err = got_object_get_type(&type1, repo, id1);
5597 if (err)
5598 goto done;
5599 err = got_object_get_type(&type2, repo, id2);
5600 if (err)
5601 goto done;
5603 if (type1 != type2) {
5604 err = got_error(GOT_ERR_OBJ_TYPE);
5605 goto done;
5608 s->first_displayed_line = 1;
5609 s->last_displayed_line = view->nlines;
5610 s->selected_line = 1;
5611 s->repo = repo;
5612 s->id1 = id1;
5613 s->id2 = id2;
5614 s->label1 = label1;
5615 s->label2 = label2;
5617 if (id1) {
5618 s->id1 = got_object_id_dup(id1);
5619 if (s->id1 == NULL) {
5620 err = got_error_from_errno("got_object_id_dup");
5621 goto done;
5623 } else
5624 s->id1 = NULL;
5626 s->id2 = got_object_id_dup(id2);
5627 if (s->id2 == NULL) {
5628 err = got_error_from_errno("got_object_id_dup");
5629 goto done;
5632 s->f1 = got_opentemp();
5633 if (s->f1 == NULL) {
5634 err = got_error_from_errno("got_opentemp");
5635 goto done;
5638 s->f2 = got_opentemp();
5639 if (s->f2 == NULL) {
5640 err = got_error_from_errno("got_opentemp");
5641 goto done;
5644 s->fd1 = got_opentempfd();
5645 if (s->fd1 == -1) {
5646 err = got_error_from_errno("got_opentempfd");
5647 goto done;
5650 s->fd2 = got_opentempfd();
5651 if (s->fd2 == -1) {
5652 err = got_error_from_errno("got_opentempfd");
5653 goto done;
5656 s->diff_context = diff_context;
5657 s->ignore_whitespace = ignore_whitespace;
5658 s->force_text_diff = force_text_diff;
5659 s->parent_view = parent_view;
5660 s->repo = repo;
5662 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5663 int rc;
5665 rc = init_pair(GOT_DIFF_LINE_MINUS,
5666 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5667 if (rc != ERR)
5668 rc = init_pair(GOT_DIFF_LINE_PLUS,
5669 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5670 if (rc != ERR)
5671 rc = init_pair(GOT_DIFF_LINE_HUNK,
5672 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5673 if (rc != ERR)
5674 rc = init_pair(GOT_DIFF_LINE_META,
5675 get_color_value("TOG_COLOR_DIFF_META"), -1);
5676 if (rc != ERR)
5677 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5678 get_color_value("TOG_COLOR_DIFF_META"), -1);
5679 if (rc != ERR)
5680 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5681 get_color_value("TOG_COLOR_DIFF_META"), -1);
5682 if (rc != ERR)
5683 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5684 get_color_value("TOG_COLOR_DIFF_META"), -1);
5685 if (rc != ERR)
5686 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5687 get_color_value("TOG_COLOR_AUTHOR"), -1);
5688 if (rc != ERR)
5689 rc = init_pair(GOT_DIFF_LINE_DATE,
5690 get_color_value("TOG_COLOR_DATE"), -1);
5691 if (rc == ERR) {
5692 err = got_error(GOT_ERR_RANGE);
5693 goto done;
5697 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5698 view_is_splitscreen(view))
5699 show_log_view(parent_view); /* draw border */
5700 diff_view_indicate_progress(view);
5702 err = create_diff(s);
5704 view->show = show_diff_view;
5705 view->input = input_diff_view;
5706 view->reset = reset_diff_view;
5707 view->close = close_diff_view;
5708 view->search_start = search_start_diff_view;
5709 view->search_setup = search_setup_diff_view;
5710 view->search_next = search_next_view_match;
5711 done:
5712 if (err) {
5713 if (view->close == NULL)
5714 close_diff_view(view);
5715 view_close(view);
5717 return err;
5720 static const struct got_error *
5721 show_diff_view(struct tog_view *view)
5723 const struct got_error *err;
5724 struct tog_diff_view_state *s = &view->state.diff;
5725 char *id_str1 = NULL, *id_str2, *header;
5726 const char *label1, *label2;
5728 if (s->id1) {
5729 err = got_object_id_str(&id_str1, s->id1);
5730 if (err)
5731 return err;
5732 label1 = s->label1 ? s->label1 : id_str1;
5733 } else
5734 label1 = "/dev/null";
5736 err = got_object_id_str(&id_str2, s->id2);
5737 if (err)
5738 return err;
5739 label2 = s->label2 ? s->label2 : id_str2;
5741 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5742 err = got_error_from_errno("asprintf");
5743 free(id_str1);
5744 free(id_str2);
5745 return err;
5747 free(id_str1);
5748 free(id_str2);
5750 err = draw_file(view, header);
5751 free(header);
5752 return err;
5755 static const struct got_error *
5756 set_selected_commit(struct tog_diff_view_state *s,
5757 struct commit_queue_entry *entry)
5759 const struct got_error *err;
5760 const struct got_object_id_queue *parent_ids;
5761 struct got_commit_object *selected_commit;
5762 struct got_object_qid *pid;
5764 free(s->id2);
5765 s->id2 = got_object_id_dup(entry->id);
5766 if (s->id2 == NULL)
5767 return got_error_from_errno("got_object_id_dup");
5769 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5770 if (err)
5771 return err;
5772 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5773 free(s->id1);
5774 pid = STAILQ_FIRST(parent_ids);
5775 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5776 got_object_commit_close(selected_commit);
5777 return NULL;
5780 static const struct got_error *
5781 reset_diff_view(struct tog_view *view)
5783 struct tog_diff_view_state *s = &view->state.diff;
5785 view->count = 0;
5786 wclear(view->window);
5787 s->first_displayed_line = 1;
5788 s->last_displayed_line = view->nlines;
5789 s->matched_line = 0;
5790 diff_view_indicate_progress(view);
5791 return create_diff(s);
5794 static void
5795 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5797 int start, i;
5799 i = start = s->first_displayed_line - 1;
5801 while (s->lines[i].type != type) {
5802 if (i == 0)
5803 i = s->nlines - 1;
5804 if (--i == start)
5805 return; /* do nothing, requested type not in file */
5808 s->selected_line = 1;
5809 s->first_displayed_line = i;
5812 static void
5813 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5815 int start, i;
5817 i = start = s->first_displayed_line + 1;
5819 while (s->lines[i].type != type) {
5820 if (i == s->nlines - 1)
5821 i = 0;
5822 if (++i == start)
5823 return; /* do nothing, requested type not in file */
5826 s->selected_line = 1;
5827 s->first_displayed_line = i;
5830 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5831 int, int, int);
5832 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5833 int, int);
5835 static const struct got_error *
5836 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5838 const struct got_error *err = NULL;
5839 struct tog_diff_view_state *s = &view->state.diff;
5840 struct tog_log_view_state *ls;
5841 struct commit_queue_entry *old_selected_entry;
5842 char *line = NULL;
5843 size_t linesize = 0;
5844 ssize_t linelen;
5845 int i, nscroll = view->nlines - 1, up = 0;
5847 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5849 switch (ch) {
5850 case '0':
5851 case '$':
5852 case KEY_RIGHT:
5853 case 'l':
5854 case KEY_LEFT:
5855 case 'h':
5856 horizontal_scroll_input(view, ch);
5857 break;
5858 case 'a':
5859 case 'w':
5860 if (ch == 'a') {
5861 s->force_text_diff = !s->force_text_diff;
5862 view->action = s->force_text_diff ?
5863 "force ASCII text enabled" :
5864 "force ASCII text disabled";
5866 else if (ch == 'w') {
5867 s->ignore_whitespace = !s->ignore_whitespace;
5868 view->action = s->ignore_whitespace ?
5869 "ignore whitespace enabled" :
5870 "ignore whitespace disabled";
5872 err = reset_diff_view(view);
5873 break;
5874 case 'g':
5875 case KEY_HOME:
5876 s->first_displayed_line = 1;
5877 view->count = 0;
5878 break;
5879 case 'G':
5880 case KEY_END:
5881 view->count = 0;
5882 if (s->eof)
5883 break;
5885 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5886 s->eof = 1;
5887 break;
5888 case 'k':
5889 case KEY_UP:
5890 case CTRL('p'):
5891 if (s->first_displayed_line > 1)
5892 s->first_displayed_line--;
5893 else
5894 view->count = 0;
5895 break;
5896 case CTRL('u'):
5897 case 'u':
5898 nscroll /= 2;
5899 /* FALL THROUGH */
5900 case KEY_PPAGE:
5901 case CTRL('b'):
5902 case 'b':
5903 if (s->first_displayed_line == 1) {
5904 view->count = 0;
5905 break;
5907 i = 0;
5908 while (i++ < nscroll && s->first_displayed_line > 1)
5909 s->first_displayed_line--;
5910 break;
5911 case 'j':
5912 case KEY_DOWN:
5913 case CTRL('n'):
5914 if (!s->eof)
5915 s->first_displayed_line++;
5916 else
5917 view->count = 0;
5918 break;
5919 case CTRL('d'):
5920 case 'd':
5921 nscroll /= 2;
5922 /* FALL THROUGH */
5923 case KEY_NPAGE:
5924 case CTRL('f'):
5925 case 'f':
5926 case ' ':
5927 if (s->eof) {
5928 view->count = 0;
5929 break;
5931 i = 0;
5932 while (!s->eof && i++ < nscroll) {
5933 linelen = getline(&line, &linesize, s->f);
5934 s->first_displayed_line++;
5935 if (linelen == -1) {
5936 if (feof(s->f)) {
5937 s->eof = 1;
5938 } else
5939 err = got_ferror(s->f, GOT_ERR_IO);
5940 break;
5943 free(line);
5944 break;
5945 case '(':
5946 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5947 break;
5948 case ')':
5949 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5950 break;
5951 case '{':
5952 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5953 break;
5954 case '}':
5955 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5956 break;
5957 case '[':
5958 if (s->diff_context > 0) {
5959 s->diff_context--;
5960 s->matched_line = 0;
5961 diff_view_indicate_progress(view);
5962 err = create_diff(s);
5963 if (s->first_displayed_line + view->nlines - 1 >
5964 s->nlines) {
5965 s->first_displayed_line = 1;
5966 s->last_displayed_line = view->nlines;
5968 } else
5969 view->count = 0;
5970 break;
5971 case ']':
5972 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5973 s->diff_context++;
5974 s->matched_line = 0;
5975 diff_view_indicate_progress(view);
5976 err = create_diff(s);
5977 } else
5978 view->count = 0;
5979 break;
5980 case '<':
5981 case ',':
5982 case 'K':
5983 up = 1;
5984 /* FALL THROUGH */
5985 case '>':
5986 case '.':
5987 case 'J':
5988 if (s->parent_view == NULL) {
5989 view->count = 0;
5990 break;
5992 s->parent_view->count = view->count;
5994 if (s->parent_view->type == TOG_VIEW_LOG) {
5995 ls = &s->parent_view->state.log;
5996 old_selected_entry = ls->selected_entry;
5998 err = input_log_view(NULL, s->parent_view,
5999 up ? KEY_UP : KEY_DOWN);
6000 if (err)
6001 break;
6002 view->count = s->parent_view->count;
6004 if (old_selected_entry == ls->selected_entry)
6005 break;
6007 err = set_selected_commit(s, ls->selected_entry);
6008 if (err)
6009 break;
6010 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
6011 struct tog_blame_view_state *bs;
6012 struct got_object_id *id, *prev_id;
6014 bs = &s->parent_view->state.blame;
6015 prev_id = get_annotation_for_line(bs->blame.lines,
6016 bs->blame.nlines, bs->last_diffed_line);
6018 err = input_blame_view(&view, s->parent_view,
6019 up ? KEY_UP : KEY_DOWN);
6020 if (err)
6021 break;
6022 view->count = s->parent_view->count;
6024 if (prev_id == NULL)
6025 break;
6026 id = get_selected_commit_id(bs->blame.lines,
6027 bs->blame.nlines, bs->first_displayed_line,
6028 bs->selected_line);
6029 if (id == NULL)
6030 break;
6032 if (!got_object_id_cmp(prev_id, id))
6033 break;
6035 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
6036 if (err)
6037 break;
6039 s->first_displayed_line = 1;
6040 s->last_displayed_line = view->nlines;
6041 s->matched_line = 0;
6042 view->x = 0;
6044 diff_view_indicate_progress(view);
6045 err = create_diff(s);
6046 break;
6047 default:
6048 view->count = 0;
6049 break;
6052 return err;
6055 static const struct got_error *
6056 cmd_diff(int argc, char *argv[])
6058 const struct got_error *error;
6059 struct got_repository *repo = NULL;
6060 struct got_worktree *worktree = NULL;
6061 struct got_object_id *id1 = NULL, *id2 = NULL;
6062 char *repo_path = NULL, *cwd = NULL;
6063 char *id_str1 = NULL, *id_str2 = NULL;
6064 char *keyword_idstr1 = NULL, *keyword_idstr2 = NULL;
6065 char *label1 = NULL, *label2 = NULL;
6066 int diff_context = 3, ignore_whitespace = 0;
6067 int ch, force_text_diff = 0;
6068 const char *errstr;
6069 struct tog_view *view;
6070 int *pack_fds = NULL;
6072 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
6073 switch (ch) {
6074 case 'a':
6075 force_text_diff = 1;
6076 break;
6077 case 'C':
6078 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
6079 &errstr);
6080 if (errstr != NULL)
6081 errx(1, "number of context lines is %s: %s",
6082 errstr, errstr);
6083 break;
6084 case 'r':
6085 repo_path = realpath(optarg, NULL);
6086 if (repo_path == NULL)
6087 return got_error_from_errno2("realpath",
6088 optarg);
6089 got_path_strip_trailing_slashes(repo_path);
6090 break;
6091 case 'w':
6092 ignore_whitespace = 1;
6093 break;
6094 default:
6095 usage_diff();
6096 /* NOTREACHED */
6100 argc -= optind;
6101 argv += optind;
6103 if (argc == 0) {
6104 usage_diff(); /* TODO show local worktree changes */
6105 } else if (argc == 2) {
6106 id_str1 = argv[0];
6107 id_str2 = argv[1];
6108 } else
6109 usage_diff();
6111 error = got_repo_pack_fds_open(&pack_fds);
6112 if (error)
6113 goto done;
6115 if (repo_path == NULL) {
6116 cwd = getcwd(NULL, 0);
6117 if (cwd == NULL)
6118 return got_error_from_errno("getcwd");
6119 error = got_worktree_open(&worktree, cwd, NULL);
6120 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6121 goto done;
6122 if (worktree)
6123 repo_path =
6124 strdup(got_worktree_get_repo_path(worktree));
6125 else
6126 repo_path = strdup(cwd);
6127 if (repo_path == NULL) {
6128 error = got_error_from_errno("strdup");
6129 goto done;
6133 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6134 if (error)
6135 goto done;
6137 init_curses();
6139 error = apply_unveil(got_repo_get_path(repo), NULL);
6140 if (error)
6141 goto done;
6143 error = tog_load_refs(repo, 0);
6144 if (error)
6145 goto done;
6147 if (id_str1 != NULL) {
6148 error = got_keyword_to_idstr(&keyword_idstr1, id_str1,
6149 repo, worktree);
6150 if (error != NULL)
6151 goto done;
6152 if (keyword_idstr1 != NULL)
6153 id_str1 = keyword_idstr1;
6155 if (id_str2 != NULL) {
6156 error = got_keyword_to_idstr(&keyword_idstr2, id_str2,
6157 repo, worktree);
6158 if (error != NULL)
6159 goto done;
6160 if (keyword_idstr2 != NULL)
6161 id_str2 = keyword_idstr2;
6164 error = got_repo_match_object_id(&id1, &label1, id_str1,
6165 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6166 if (error)
6167 goto done;
6169 error = got_repo_match_object_id(&id2, &label2, id_str2,
6170 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6171 if (error)
6172 goto done;
6174 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
6175 if (view == NULL) {
6176 error = got_error_from_errno("view_open");
6177 goto done;
6179 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
6180 ignore_whitespace, force_text_diff, NULL, repo);
6181 if (error)
6182 goto done;
6184 if (worktree) {
6185 error = set_tog_base_commit(repo, worktree);
6186 if (error != NULL)
6187 goto done;
6190 error = view_loop(view);
6192 done:
6193 free(tog_base_commit.id);
6194 free(keyword_idstr1);
6195 free(keyword_idstr2);
6196 free(label1);
6197 free(label2);
6198 free(repo_path);
6199 free(cwd);
6200 if (repo) {
6201 const struct got_error *close_err = got_repo_close(repo);
6202 if (error == NULL)
6203 error = close_err;
6205 if (worktree)
6206 got_worktree_close(worktree);
6207 if (pack_fds) {
6208 const struct got_error *pack_err =
6209 got_repo_pack_fds_close(pack_fds);
6210 if (error == NULL)
6211 error = pack_err;
6213 tog_free_refs();
6214 return error;
6217 __dead static void
6218 usage_blame(void)
6220 endwin();
6221 fprintf(stderr,
6222 "usage: %s blame [-c commit] [-r repository-path] path\n",
6223 getprogname());
6224 exit(1);
6227 struct tog_blame_line {
6228 int annotated;
6229 struct got_object_id *id;
6232 static const struct got_error *
6233 draw_blame(struct tog_view *view)
6235 struct tog_blame_view_state *s = &view->state.blame;
6236 struct tog_blame *blame = &s->blame;
6237 regmatch_t *regmatch = &view->regmatch;
6238 const struct got_error *err;
6239 int lineno = 0, nprinted = 0;
6240 char *line = NULL;
6241 size_t linesize = 0;
6242 ssize_t linelen;
6243 wchar_t *wline;
6244 int width;
6245 struct tog_blame_line *blame_line;
6246 struct got_object_id *prev_id = NULL;
6247 char *id_str;
6248 struct tog_color *tc;
6250 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6251 if (err)
6252 return err;
6254 rewind(blame->f);
6255 werase(view->window);
6257 if (asprintf(&line, "commit %s", id_str) == -1) {
6258 err = got_error_from_errno("asprintf");
6259 free(id_str);
6260 return err;
6263 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6264 free(line);
6265 line = NULL;
6266 if (err)
6267 return err;
6268 if (view_needs_focus_indication(view))
6269 wstandout(view->window);
6270 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6271 if (tc)
6272 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6273 waddwstr(view->window, wline);
6274 while (width++ < view->ncols)
6275 waddch(view->window, ' ');
6276 if (tc)
6277 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6278 if (view_needs_focus_indication(view))
6279 wstandend(view->window);
6280 free(wline);
6281 wline = NULL;
6283 if (view->gline > blame->nlines)
6284 view->gline = blame->nlines;
6286 if (tog_io.wait_for_ui) {
6287 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6288 int rc;
6290 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6291 if (rc)
6292 return got_error_set_errno(rc, "pthread_cond_wait");
6293 tog_io.wait_for_ui = 0;
6296 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6297 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6298 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6299 free(id_str);
6300 return got_error_from_errno("asprintf");
6302 free(id_str);
6303 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6304 free(line);
6305 line = NULL;
6306 if (err)
6307 return err;
6308 waddwstr(view->window, wline);
6309 free(wline);
6310 wline = NULL;
6311 if (width < view->ncols - 1)
6312 waddch(view->window, '\n');
6314 s->eof = 0;
6315 view->maxx = 0;
6316 while (nprinted < view->nlines - 2) {
6317 linelen = getline(&line, &linesize, blame->f);
6318 if (linelen == -1) {
6319 if (feof(blame->f)) {
6320 s->eof = 1;
6321 break;
6323 free(line);
6324 return got_ferror(blame->f, GOT_ERR_IO);
6326 if (++lineno < s->first_displayed_line)
6327 continue;
6328 if (view->gline && !gotoline(view, &lineno, &nprinted))
6329 continue;
6331 /* Set view->maxx based on full line length. */
6332 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6333 if (err) {
6334 free(line);
6335 return err;
6337 free(wline);
6338 wline = NULL;
6339 view->maxx = MAX(view->maxx, width);
6341 if (nprinted == s->selected_line - 1)
6342 wstandout(view->window);
6344 if (blame->nlines > 0) {
6345 blame_line = &blame->lines[lineno - 1];
6346 if (blame_line->annotated && prev_id &&
6347 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6348 !(nprinted == s->selected_line - 1)) {
6349 waddstr(view->window, " ");
6350 } else if (blame_line->annotated) {
6351 char *id_str;
6352 err = got_object_id_str(&id_str,
6353 blame_line->id);
6354 if (err) {
6355 free(line);
6356 return err;
6358 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6359 if (tc)
6360 wattr_on(view->window,
6361 COLOR_PAIR(tc->colorpair), NULL);
6362 wprintw(view->window, "%.8s", id_str);
6363 if (tc)
6364 wattr_off(view->window,
6365 COLOR_PAIR(tc->colorpair), NULL);
6366 free(id_str);
6367 prev_id = blame_line->id;
6368 } else {
6369 waddstr(view->window, "........");
6370 prev_id = NULL;
6372 } else {
6373 waddstr(view->window, "........");
6374 prev_id = NULL;
6377 if (nprinted == s->selected_line - 1)
6378 wstandend(view->window);
6379 waddstr(view->window, " ");
6381 if (view->ncols <= 9) {
6382 width = 9;
6383 } else if (s->first_displayed_line + nprinted ==
6384 s->matched_line &&
6385 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6386 err = add_matched_line(&width, line, view->ncols - 9, 9,
6387 view->window, view->x, regmatch);
6388 if (err) {
6389 free(line);
6390 return err;
6392 width += 9;
6393 } else {
6394 int skip;
6395 err = format_line(&wline, &width, &skip, line,
6396 view->x, view->ncols - 9, 9, 1);
6397 if (err) {
6398 free(line);
6399 return err;
6401 waddwstr(view->window, &wline[skip]);
6402 width += 9;
6403 free(wline);
6404 wline = NULL;
6407 if (width <= view->ncols - 1)
6408 waddch(view->window, '\n');
6409 if (++nprinted == 1)
6410 s->first_displayed_line = lineno;
6412 free(line);
6413 s->last_displayed_line = lineno;
6415 view_border(view);
6417 return NULL;
6420 static const struct got_error *
6421 blame_cb(void *arg, int nlines, int lineno,
6422 struct got_commit_object *commit, struct got_object_id *id)
6424 const struct got_error *err = NULL;
6425 struct tog_blame_cb_args *a = arg;
6426 struct tog_blame_line *line;
6427 int errcode;
6429 if (nlines != a->nlines ||
6430 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6431 return got_error(GOT_ERR_RANGE);
6433 errcode = pthread_mutex_lock(&tog_mutex);
6434 if (errcode)
6435 return got_error_set_errno(errcode, "pthread_mutex_lock");
6437 if (*a->quit) { /* user has quit the blame view */
6438 err = got_error(GOT_ERR_ITER_COMPLETED);
6439 goto done;
6442 if (lineno == -1)
6443 goto done; /* no change in this commit */
6445 line = &a->lines[lineno - 1];
6446 if (line->annotated)
6447 goto done;
6449 line->id = got_object_id_dup(id);
6450 if (line->id == NULL) {
6451 err = got_error_from_errno("got_object_id_dup");
6452 goto done;
6454 line->annotated = 1;
6455 done:
6456 errcode = pthread_mutex_unlock(&tog_mutex);
6457 if (errcode)
6458 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6459 return err;
6462 static void *
6463 blame_thread(void *arg)
6465 const struct got_error *err, *close_err;
6466 struct tog_blame_thread_args *ta = arg;
6467 struct tog_blame_cb_args *a = ta->cb_args;
6468 int errcode, fd1 = -1, fd2 = -1;
6469 FILE *f1 = NULL, *f2 = NULL;
6471 fd1 = got_opentempfd();
6472 if (fd1 == -1)
6473 return (void *)got_error_from_errno("got_opentempfd");
6475 fd2 = got_opentempfd();
6476 if (fd2 == -1) {
6477 err = got_error_from_errno("got_opentempfd");
6478 goto done;
6481 f1 = got_opentemp();
6482 if (f1 == NULL) {
6483 err = (void *)got_error_from_errno("got_opentemp");
6484 goto done;
6486 f2 = got_opentemp();
6487 if (f2 == NULL) {
6488 err = (void *)got_error_from_errno("got_opentemp");
6489 goto done;
6492 err = block_signals_used_by_main_thread();
6493 if (err)
6494 goto done;
6496 err = got_blame(ta->path, a->commit_id, ta->repo,
6497 tog_diff_algo, blame_cb, ta->cb_args,
6498 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6499 if (err && err->code == GOT_ERR_CANCELLED)
6500 err = NULL;
6502 errcode = pthread_mutex_lock(&tog_mutex);
6503 if (errcode) {
6504 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6505 goto done;
6508 close_err = got_repo_close(ta->repo);
6509 if (err == NULL)
6510 err = close_err;
6511 ta->repo = NULL;
6512 *ta->complete = 1;
6514 if (tog_io.wait_for_ui) {
6515 errcode = pthread_cond_signal(&ta->blame_complete);
6516 if (errcode && err == NULL)
6517 err = got_error_set_errno(errcode,
6518 "pthread_cond_signal");
6521 errcode = pthread_mutex_unlock(&tog_mutex);
6522 if (errcode && err == NULL)
6523 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6525 done:
6526 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6527 err = got_error_from_errno("close");
6528 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6529 err = got_error_from_errno("close");
6530 if (f1 && fclose(f1) == EOF && err == NULL)
6531 err = got_error_from_errno("fclose");
6532 if (f2 && fclose(f2) == EOF && err == NULL)
6533 err = got_error_from_errno("fclose");
6535 return (void *)err;
6538 static struct got_object_id *
6539 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6540 int first_displayed_line, int selected_line)
6542 struct tog_blame_line *line;
6544 if (nlines <= 0)
6545 return NULL;
6547 line = &lines[first_displayed_line - 1 + selected_line - 1];
6548 if (!line->annotated)
6549 return NULL;
6551 return line->id;
6554 static struct got_object_id *
6555 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6556 int lineno)
6558 struct tog_blame_line *line;
6560 if (nlines <= 0 || lineno >= nlines)
6561 return NULL;
6563 line = &lines[lineno - 1];
6564 if (!line->annotated)
6565 return NULL;
6567 return line->id;
6570 static const struct got_error *
6571 stop_blame(struct tog_blame *blame)
6573 const struct got_error *err = NULL;
6574 int i;
6576 if (blame->thread) {
6577 int errcode;
6578 errcode = pthread_mutex_unlock(&tog_mutex);
6579 if (errcode)
6580 return got_error_set_errno(errcode,
6581 "pthread_mutex_unlock");
6582 errcode = pthread_join(blame->thread, (void **)&err);
6583 if (errcode)
6584 return got_error_set_errno(errcode, "pthread_join");
6585 errcode = pthread_mutex_lock(&tog_mutex);
6586 if (errcode)
6587 return got_error_set_errno(errcode,
6588 "pthread_mutex_lock");
6589 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6590 err = NULL;
6591 blame->thread = NULL;
6593 if (blame->thread_args.repo) {
6594 const struct got_error *close_err;
6595 close_err = got_repo_close(blame->thread_args.repo);
6596 if (err == NULL)
6597 err = close_err;
6598 blame->thread_args.repo = NULL;
6600 if (blame->f) {
6601 if (fclose(blame->f) == EOF && err == NULL)
6602 err = got_error_from_errno("fclose");
6603 blame->f = NULL;
6605 if (blame->lines) {
6606 for (i = 0; i < blame->nlines; i++)
6607 free(blame->lines[i].id);
6608 free(blame->lines);
6609 blame->lines = NULL;
6611 free(blame->cb_args.commit_id);
6612 blame->cb_args.commit_id = NULL;
6613 if (blame->pack_fds) {
6614 const struct got_error *pack_err =
6615 got_repo_pack_fds_close(blame->pack_fds);
6616 if (err == NULL)
6617 err = pack_err;
6618 blame->pack_fds = NULL;
6620 free(blame->line_offsets);
6621 blame->line_offsets = NULL;
6622 return err;
6625 static const struct got_error *
6626 cancel_blame_view(void *arg)
6628 const struct got_error *err = NULL;
6629 int *done = arg;
6630 int errcode;
6632 errcode = pthread_mutex_lock(&tog_mutex);
6633 if (errcode)
6634 return got_error_set_errno(errcode,
6635 "pthread_mutex_unlock");
6637 if (*done)
6638 err = got_error(GOT_ERR_CANCELLED);
6640 errcode = pthread_mutex_unlock(&tog_mutex);
6641 if (errcode)
6642 return got_error_set_errno(errcode,
6643 "pthread_mutex_lock");
6645 return err;
6648 static const struct got_error *
6649 run_blame(struct tog_view *view)
6651 struct tog_blame_view_state *s = &view->state.blame;
6652 struct tog_blame *blame = &s->blame;
6653 const struct got_error *err = NULL;
6654 struct got_commit_object *commit = NULL;
6655 struct got_blob_object *blob = NULL;
6656 struct got_repository *thread_repo = NULL;
6657 struct got_object_id *obj_id = NULL;
6658 int obj_type, fd = -1;
6659 int *pack_fds = NULL;
6661 err = got_object_open_as_commit(&commit, s->repo,
6662 &s->blamed_commit->id);
6663 if (err)
6664 return err;
6666 fd = got_opentempfd();
6667 if (fd == -1) {
6668 err = got_error_from_errno("got_opentempfd");
6669 goto done;
6672 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6673 if (err)
6674 goto done;
6676 err = got_object_get_type(&obj_type, s->repo, obj_id);
6677 if (err)
6678 goto done;
6680 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6681 err = got_error(GOT_ERR_OBJ_TYPE);
6682 goto done;
6685 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6686 if (err)
6687 goto done;
6688 blame->f = got_opentemp();
6689 if (blame->f == NULL) {
6690 err = got_error_from_errno("got_opentemp");
6691 goto done;
6693 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6694 &blame->line_offsets, blame->f, blob);
6695 if (err)
6696 goto done;
6697 if (blame->nlines == 0) {
6698 s->blame_complete = 1;
6699 goto done;
6702 /* Don't include \n at EOF in the blame line count. */
6703 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6704 blame->nlines--;
6706 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6707 if (blame->lines == NULL) {
6708 err = got_error_from_errno("calloc");
6709 goto done;
6712 err = got_repo_pack_fds_open(&pack_fds);
6713 if (err)
6714 goto done;
6715 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6716 pack_fds);
6717 if (err)
6718 goto done;
6720 blame->pack_fds = pack_fds;
6721 blame->cb_args.view = view;
6722 blame->cb_args.lines = blame->lines;
6723 blame->cb_args.nlines = blame->nlines;
6724 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6725 if (blame->cb_args.commit_id == NULL) {
6726 err = got_error_from_errno("got_object_id_dup");
6727 goto done;
6729 blame->cb_args.quit = &s->done;
6731 blame->thread_args.path = s->path;
6732 blame->thread_args.repo = thread_repo;
6733 blame->thread_args.cb_args = &blame->cb_args;
6734 blame->thread_args.complete = &s->blame_complete;
6735 blame->thread_args.cancel_cb = cancel_blame_view;
6736 blame->thread_args.cancel_arg = &s->done;
6737 s->blame_complete = 0;
6739 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6740 s->first_displayed_line = 1;
6741 s->last_displayed_line = view->nlines;
6742 s->selected_line = 1;
6744 s->matched_line = 0;
6746 done:
6747 if (commit)
6748 got_object_commit_close(commit);
6749 if (fd != -1 && close(fd) == -1 && err == NULL)
6750 err = got_error_from_errno("close");
6751 if (blob)
6752 got_object_blob_close(blob);
6753 free(obj_id);
6754 if (err)
6755 stop_blame(blame);
6756 return err;
6759 static const struct got_error *
6760 open_blame_view(struct tog_view *view, char *path,
6761 struct got_object_id *commit_id, struct got_repository *repo)
6763 const struct got_error *err = NULL;
6764 struct tog_blame_view_state *s = &view->state.blame;
6766 STAILQ_INIT(&s->blamed_commits);
6768 s->path = strdup(path);
6769 if (s->path == NULL)
6770 return got_error_from_errno("strdup");
6772 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6773 if (err) {
6774 free(s->path);
6775 return err;
6778 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6779 s->first_displayed_line = 1;
6780 s->last_displayed_line = view->nlines;
6781 s->selected_line = 1;
6782 s->blame_complete = 0;
6783 s->repo = repo;
6784 s->commit_id = commit_id;
6785 memset(&s->blame, 0, sizeof(s->blame));
6787 STAILQ_INIT(&s->colors);
6788 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6789 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6790 get_color_value("TOG_COLOR_COMMIT"));
6791 if (err)
6792 return err;
6795 view->show = show_blame_view;
6796 view->input = input_blame_view;
6797 view->reset = reset_blame_view;
6798 view->close = close_blame_view;
6799 view->search_start = search_start_blame_view;
6800 view->search_setup = search_setup_blame_view;
6801 view->search_next = search_next_view_match;
6803 if (using_mock_io) {
6804 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6805 int rc;
6807 rc = pthread_cond_init(&bta->blame_complete, NULL);
6808 if (rc)
6809 return got_error_set_errno(rc, "pthread_cond_init");
6812 return run_blame(view);
6815 static const struct got_error *
6816 close_blame_view(struct tog_view *view)
6818 const struct got_error *err = NULL;
6819 struct tog_blame_view_state *s = &view->state.blame;
6821 if (s->blame.thread)
6822 err = stop_blame(&s->blame);
6824 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6825 struct got_object_qid *blamed_commit;
6826 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6827 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6828 got_object_qid_free(blamed_commit);
6831 if (using_mock_io) {
6832 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6833 int rc;
6835 rc = pthread_cond_destroy(&bta->blame_complete);
6836 if (rc && err == NULL)
6837 err = got_error_set_errno(rc, "pthread_cond_destroy");
6840 free(s->path);
6841 free_colors(&s->colors);
6842 return err;
6845 static const struct got_error *
6846 search_start_blame_view(struct tog_view *view)
6848 struct tog_blame_view_state *s = &view->state.blame;
6850 s->matched_line = 0;
6851 return NULL;
6854 static void
6855 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6856 size_t *nlines, int **first, int **last, int **match, int **selected)
6858 struct tog_blame_view_state *s = &view->state.blame;
6860 *f = s->blame.f;
6861 *nlines = s->blame.nlines;
6862 *line_offsets = s->blame.line_offsets;
6863 *match = &s->matched_line;
6864 *first = &s->first_displayed_line;
6865 *last = &s->last_displayed_line;
6866 *selected = &s->selected_line;
6869 static const struct got_error *
6870 show_blame_view(struct tog_view *view)
6872 const struct got_error *err = NULL;
6873 struct tog_blame_view_state *s = &view->state.blame;
6874 int errcode;
6876 if (s->blame.thread == NULL && !s->blame_complete) {
6877 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6878 &s->blame.thread_args);
6879 if (errcode)
6880 return got_error_set_errno(errcode, "pthread_create");
6882 if (!using_mock_io)
6883 halfdelay(1); /* fast refresh while annotating */
6886 if (s->blame_complete && !using_mock_io)
6887 halfdelay(10); /* disable fast refresh */
6889 err = draw_blame(view);
6891 view_border(view);
6892 return err;
6895 static const struct got_error *
6896 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6897 struct got_repository *repo, struct got_object_id *id)
6899 struct tog_view *log_view;
6900 const struct got_error *err = NULL;
6902 *new_view = NULL;
6904 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6905 if (log_view == NULL)
6906 return got_error_from_errno("view_open");
6908 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0, NULL);
6909 if (err)
6910 view_close(log_view);
6911 else
6912 *new_view = log_view;
6914 return err;
6917 static const struct got_error *
6918 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6920 const struct got_error *err = NULL, *thread_err = NULL;
6921 struct tog_view *diff_view;
6922 struct tog_blame_view_state *s = &view->state.blame;
6923 int eos, nscroll, begin_y = 0, begin_x = 0;
6925 eos = nscroll = view->nlines - 2;
6926 if (view_is_hsplit_top(view))
6927 --eos; /* border */
6929 switch (ch) {
6930 case '0':
6931 case '$':
6932 case KEY_RIGHT:
6933 case 'l':
6934 case KEY_LEFT:
6935 case 'h':
6936 horizontal_scroll_input(view, ch);
6937 break;
6938 case 'q':
6939 s->done = 1;
6940 break;
6941 case 'g':
6942 case KEY_HOME:
6943 s->selected_line = 1;
6944 s->first_displayed_line = 1;
6945 view->count = 0;
6946 break;
6947 case 'G':
6948 case KEY_END:
6949 if (s->blame.nlines < eos) {
6950 s->selected_line = s->blame.nlines;
6951 s->first_displayed_line = 1;
6952 } else {
6953 s->selected_line = eos;
6954 s->first_displayed_line = s->blame.nlines - (eos - 1);
6956 view->count = 0;
6957 break;
6958 case 'k':
6959 case KEY_UP:
6960 case CTRL('p'):
6961 if (s->selected_line > 1)
6962 s->selected_line--;
6963 else if (s->selected_line == 1 &&
6964 s->first_displayed_line > 1)
6965 s->first_displayed_line--;
6966 else
6967 view->count = 0;
6968 break;
6969 case CTRL('u'):
6970 case 'u':
6971 nscroll /= 2;
6972 /* FALL THROUGH */
6973 case KEY_PPAGE:
6974 case CTRL('b'):
6975 case 'b':
6976 if (s->first_displayed_line == 1) {
6977 if (view->count > 1)
6978 nscroll += nscroll;
6979 s->selected_line = MAX(1, s->selected_line - nscroll);
6980 view->count = 0;
6981 break;
6983 if (s->first_displayed_line > nscroll)
6984 s->first_displayed_line -= nscroll;
6985 else
6986 s->first_displayed_line = 1;
6987 break;
6988 case 'j':
6989 case KEY_DOWN:
6990 case CTRL('n'):
6991 if (s->selected_line < eos && s->first_displayed_line +
6992 s->selected_line <= s->blame.nlines)
6993 s->selected_line++;
6994 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6995 s->first_displayed_line++;
6996 else
6997 view->count = 0;
6998 break;
6999 case 'c':
7000 case 'p': {
7001 struct got_object_id *id = NULL;
7003 view->count = 0;
7004 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7005 s->first_displayed_line, s->selected_line);
7006 if (id == NULL)
7007 break;
7008 if (ch == 'p') {
7009 struct got_commit_object *commit, *pcommit;
7010 struct got_object_qid *pid;
7011 struct got_object_id *blob_id = NULL;
7012 int obj_type;
7013 err = got_object_open_as_commit(&commit,
7014 s->repo, id);
7015 if (err)
7016 break;
7017 pid = STAILQ_FIRST(
7018 got_object_commit_get_parent_ids(commit));
7019 if (pid == NULL) {
7020 got_object_commit_close(commit);
7021 break;
7023 /* Check if path history ends here. */
7024 err = got_object_open_as_commit(&pcommit,
7025 s->repo, &pid->id);
7026 if (err)
7027 break;
7028 err = got_object_id_by_path(&blob_id, s->repo,
7029 pcommit, s->path);
7030 got_object_commit_close(pcommit);
7031 if (err) {
7032 if (err->code == GOT_ERR_NO_TREE_ENTRY)
7033 err = NULL;
7034 got_object_commit_close(commit);
7035 break;
7037 err = got_object_get_type(&obj_type, s->repo,
7038 blob_id);
7039 free(blob_id);
7040 /* Can't blame non-blob type objects. */
7041 if (obj_type != GOT_OBJ_TYPE_BLOB) {
7042 got_object_commit_close(commit);
7043 break;
7045 err = got_object_qid_alloc(&s->blamed_commit,
7046 &pid->id);
7047 got_object_commit_close(commit);
7048 } else {
7049 if (got_object_id_cmp(id,
7050 &s->blamed_commit->id) == 0)
7051 break;
7052 err = got_object_qid_alloc(&s->blamed_commit,
7053 id);
7055 if (err)
7056 break;
7057 s->done = 1;
7058 thread_err = stop_blame(&s->blame);
7059 s->done = 0;
7060 if (thread_err)
7061 break;
7062 STAILQ_INSERT_HEAD(&s->blamed_commits,
7063 s->blamed_commit, entry);
7064 err = run_blame(view);
7065 if (err)
7066 break;
7067 break;
7069 case 'C': {
7070 struct got_object_qid *first;
7072 view->count = 0;
7073 first = STAILQ_FIRST(&s->blamed_commits);
7074 if (!got_object_id_cmp(&first->id, s->commit_id))
7075 break;
7076 s->done = 1;
7077 thread_err = stop_blame(&s->blame);
7078 s->done = 0;
7079 if (thread_err)
7080 break;
7081 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
7082 got_object_qid_free(s->blamed_commit);
7083 s->blamed_commit =
7084 STAILQ_FIRST(&s->blamed_commits);
7085 err = run_blame(view);
7086 if (err)
7087 break;
7088 break;
7090 case 'L':
7091 view->count = 0;
7092 s->id_to_log = get_selected_commit_id(s->blame.lines,
7093 s->blame.nlines, s->first_displayed_line, s->selected_line);
7094 if (s->id_to_log)
7095 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7096 break;
7097 case KEY_ENTER:
7098 case '\r': {
7099 struct got_object_id *id = NULL;
7100 struct got_object_qid *pid;
7101 struct got_commit_object *commit = NULL;
7103 view->count = 0;
7104 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7105 s->first_displayed_line, s->selected_line);
7106 if (id == NULL)
7107 break;
7108 err = got_object_open_as_commit(&commit, s->repo, id);
7109 if (err)
7110 break;
7111 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7112 if (*new_view) {
7113 /* traversed from diff view, release diff resources */
7114 err = close_diff_view(*new_view);
7115 if (err)
7116 break;
7117 diff_view = *new_view;
7118 } else {
7119 if (view_is_parent_view(view))
7120 view_get_split(view, &begin_y, &begin_x);
7122 diff_view = view_open(0, 0, begin_y, begin_x,
7123 TOG_VIEW_DIFF);
7124 if (diff_view == NULL) {
7125 got_object_commit_close(commit);
7126 err = got_error_from_errno("view_open");
7127 break;
7130 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
7131 id, NULL, NULL, 3, 0, 0, view, s->repo);
7132 got_object_commit_close(commit);
7133 if (err)
7134 break;
7135 s->last_diffed_line = s->first_displayed_line - 1 +
7136 s->selected_line;
7137 if (*new_view)
7138 break; /* still open from active diff view */
7139 if (view_is_parent_view(view) &&
7140 view->mode == TOG_VIEW_SPLIT_HRZN) {
7141 err = view_init_hsplit(view, begin_y);
7142 if (err)
7143 break;
7146 view->focussed = 0;
7147 diff_view->focussed = 1;
7148 diff_view->mode = view->mode;
7149 diff_view->nlines = view->lines - begin_y;
7150 if (view_is_parent_view(view)) {
7151 view_transfer_size(diff_view, view);
7152 err = view_close_child(view);
7153 if (err)
7154 break;
7155 err = view_set_child(view, diff_view);
7156 if (err)
7157 break;
7158 view->focus_child = 1;
7159 } else
7160 *new_view = diff_view;
7161 if (err)
7162 break;
7163 break;
7165 case CTRL('d'):
7166 case 'd':
7167 nscroll /= 2;
7168 /* FALL THROUGH */
7169 case KEY_NPAGE:
7170 case CTRL('f'):
7171 case 'f':
7172 case ' ':
7173 if (s->last_displayed_line >= s->blame.nlines &&
7174 s->selected_line >= MIN(s->blame.nlines,
7175 view->nlines - 2)) {
7176 view->count = 0;
7177 break;
7179 if (s->last_displayed_line >= s->blame.nlines &&
7180 s->selected_line < view->nlines - 2) {
7181 s->selected_line +=
7182 MIN(nscroll, s->last_displayed_line -
7183 s->first_displayed_line - s->selected_line + 1);
7185 if (s->last_displayed_line + nscroll <= s->blame.nlines)
7186 s->first_displayed_line += nscroll;
7187 else
7188 s->first_displayed_line =
7189 s->blame.nlines - (view->nlines - 3);
7190 break;
7191 case KEY_RESIZE:
7192 if (s->selected_line > view->nlines - 2) {
7193 s->selected_line = MIN(s->blame.nlines,
7194 view->nlines - 2);
7196 break;
7197 default:
7198 view->count = 0;
7199 break;
7201 return thread_err ? thread_err : err;
7204 static const struct got_error *
7205 reset_blame_view(struct tog_view *view)
7207 const struct got_error *err;
7208 struct tog_blame_view_state *s = &view->state.blame;
7210 view->count = 0;
7211 s->done = 1;
7212 err = stop_blame(&s->blame);
7213 s->done = 0;
7214 if (err)
7215 return err;
7216 return run_blame(view);
7219 static const struct got_error *
7220 cmd_blame(int argc, char *argv[])
7222 const struct got_error *error;
7223 struct got_repository *repo = NULL;
7224 struct got_worktree *worktree = NULL;
7225 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7226 char *link_target = NULL;
7227 struct got_object_id *commit_id = NULL;
7228 struct got_commit_object *commit = NULL;
7229 char *keyword_idstr = NULL, *commit_id_str = NULL;
7230 int ch;
7231 struct tog_view *view = NULL;
7232 int *pack_fds = NULL;
7234 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7235 switch (ch) {
7236 case 'c':
7237 commit_id_str = optarg;
7238 break;
7239 case 'r':
7240 repo_path = realpath(optarg, NULL);
7241 if (repo_path == NULL)
7242 return got_error_from_errno2("realpath",
7243 optarg);
7244 break;
7245 default:
7246 usage_blame();
7247 /* NOTREACHED */
7251 argc -= optind;
7252 argv += optind;
7254 if (argc != 1)
7255 usage_blame();
7257 error = got_repo_pack_fds_open(&pack_fds);
7258 if (error != NULL)
7259 goto done;
7261 if (repo_path == NULL) {
7262 cwd = getcwd(NULL, 0);
7263 if (cwd == NULL)
7264 return got_error_from_errno("getcwd");
7265 error = got_worktree_open(&worktree, cwd, NULL);
7266 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7267 goto done;
7268 if (worktree)
7269 repo_path =
7270 strdup(got_worktree_get_repo_path(worktree));
7271 else
7272 repo_path = strdup(cwd);
7273 if (repo_path == NULL) {
7274 error = got_error_from_errno("strdup");
7275 goto done;
7279 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7280 if (error != NULL)
7281 goto done;
7283 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7284 worktree);
7285 if (error)
7286 goto done;
7288 init_curses();
7290 error = apply_unveil(got_repo_get_path(repo), NULL);
7291 if (error)
7292 goto done;
7294 error = tog_load_refs(repo, 0);
7295 if (error)
7296 goto done;
7298 if (commit_id_str == NULL) {
7299 struct got_reference *head_ref;
7300 error = got_ref_open(&head_ref, repo, worktree ?
7301 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7302 if (error != NULL)
7303 goto done;
7304 error = got_ref_resolve(&commit_id, repo, head_ref);
7305 got_ref_close(head_ref);
7306 } else {
7307 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
7308 repo, worktree);
7309 if (error != NULL)
7310 goto done;
7311 if (keyword_idstr != NULL)
7312 commit_id_str = keyword_idstr;
7314 error = got_repo_match_object_id(&commit_id, NULL,
7315 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7317 if (error != NULL)
7318 goto done;
7320 error = got_object_open_as_commit(&commit, repo, commit_id);
7321 if (error)
7322 goto done;
7324 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7325 commit, repo);
7326 if (error)
7327 goto done;
7329 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7330 if (view == NULL) {
7331 error = got_error_from_errno("view_open");
7332 goto done;
7334 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7335 commit_id, repo);
7336 if (error != NULL) {
7337 if (view->close == NULL)
7338 close_blame_view(view);
7339 view_close(view);
7340 goto done;
7343 if (worktree) {
7344 error = set_tog_base_commit(repo, worktree);
7345 if (error != NULL)
7346 goto done;
7348 /* Release work tree lock. */
7349 got_worktree_close(worktree);
7350 worktree = NULL;
7353 error = view_loop(view);
7355 done:
7356 free(tog_base_commit.id);
7357 free(repo_path);
7358 free(in_repo_path);
7359 free(link_target);
7360 free(cwd);
7361 free(commit_id);
7362 free(keyword_idstr);
7363 if (commit)
7364 got_object_commit_close(commit);
7365 if (worktree)
7366 got_worktree_close(worktree);
7367 if (repo) {
7368 const struct got_error *close_err = got_repo_close(repo);
7369 if (error == NULL)
7370 error = close_err;
7372 if (pack_fds) {
7373 const struct got_error *pack_err =
7374 got_repo_pack_fds_close(pack_fds);
7375 if (error == NULL)
7376 error = pack_err;
7378 tog_free_refs();
7379 return error;
7382 static const struct got_error *
7383 draw_tree_entries(struct tog_view *view, const char *parent_path)
7385 struct tog_tree_view_state *s = &view->state.tree;
7386 const struct got_error *err = NULL;
7387 struct got_tree_entry *te;
7388 wchar_t *wline;
7389 char *index = NULL;
7390 struct tog_color *tc;
7391 int width, n, nentries, scrollx, i = 1;
7392 int limit = view->nlines;
7394 s->ndisplayed = 0;
7395 if (view_is_hsplit_top(view))
7396 --limit; /* border */
7398 werase(view->window);
7400 if (limit == 0)
7401 return NULL;
7403 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7404 0, 0);
7405 if (err)
7406 return err;
7407 if (view_needs_focus_indication(view))
7408 wstandout(view->window);
7409 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7410 if (tc)
7411 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7412 waddwstr(view->window, wline);
7413 free(wline);
7414 wline = NULL;
7415 while (width++ < view->ncols)
7416 waddch(view->window, ' ');
7417 if (tc)
7418 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7419 if (view_needs_focus_indication(view))
7420 wstandend(view->window);
7421 if (--limit <= 0)
7422 return NULL;
7424 i += s->selected;
7425 if (s->first_displayed_entry) {
7426 i += got_tree_entry_get_index(s->first_displayed_entry);
7427 if (s->tree != s->root)
7428 ++i; /* account for ".." entry */
7430 nentries = got_object_tree_get_nentries(s->tree);
7431 if (asprintf(&index, "[%d/%d] %s",
7432 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7433 return got_error_from_errno("asprintf");
7434 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7435 free(index);
7436 if (err)
7437 return err;
7438 waddwstr(view->window, wline);
7439 free(wline);
7440 wline = NULL;
7441 if (width < view->ncols - 1)
7442 waddch(view->window, '\n');
7443 if (--limit <= 0)
7444 return NULL;
7445 waddch(view->window, '\n');
7446 if (--limit <= 0)
7447 return NULL;
7449 if (s->first_displayed_entry == NULL) {
7450 te = got_object_tree_get_first_entry(s->tree);
7451 if (s->selected == 0) {
7452 if (view->focussed)
7453 wstandout(view->window);
7454 s->selected_entry = NULL;
7456 waddstr(view->window, " ..\n"); /* parent directory */
7457 if (s->selected == 0 && view->focussed)
7458 wstandend(view->window);
7459 s->ndisplayed++;
7460 if (--limit <= 0)
7461 return NULL;
7462 n = 1;
7463 } else {
7464 n = 0;
7465 te = s->first_displayed_entry;
7468 view->maxx = 0;
7469 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7470 char *line = NULL, *id_str = NULL, *link_target = NULL;
7471 const char *modestr = "";
7472 mode_t mode;
7474 te = got_object_tree_get_entry(s->tree, i);
7475 mode = got_tree_entry_get_mode(te);
7477 if (s->show_ids) {
7478 err = got_object_id_str(&id_str,
7479 got_tree_entry_get_id(te));
7480 if (err)
7481 return got_error_from_errno(
7482 "got_object_id_str");
7484 if (got_object_tree_entry_is_submodule(te))
7485 modestr = "$";
7486 else if (S_ISLNK(mode)) {
7487 int i;
7489 err = got_tree_entry_get_symlink_target(&link_target,
7490 te, s->repo);
7491 if (err) {
7492 free(id_str);
7493 return err;
7495 for (i = 0; link_target[i] != '\0'; i++) {
7496 if (!isprint((unsigned char)link_target[i]))
7497 link_target[i] = '?';
7499 modestr = "@";
7501 else if (S_ISDIR(mode))
7502 modestr = "/";
7503 else if (mode & S_IXUSR)
7504 modestr = "*";
7505 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7506 got_tree_entry_get_name(te), modestr,
7507 link_target ? " -> ": "",
7508 link_target ? link_target : "") == -1) {
7509 free(id_str);
7510 free(link_target);
7511 return got_error_from_errno("asprintf");
7513 free(id_str);
7514 free(link_target);
7516 /* use full line width to determine view->maxx */
7517 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7518 if (err) {
7519 free(line);
7520 break;
7522 view->maxx = MAX(view->maxx, width);
7523 free(wline);
7524 wline = NULL;
7526 err = format_line(&wline, &width, &scrollx, line, view->x,
7527 view->ncols, 0, 0);
7528 if (err) {
7529 free(line);
7530 break;
7532 if (n == s->selected) {
7533 if (view->focussed)
7534 wstandout(view->window);
7535 s->selected_entry = te;
7537 tc = match_color(&s->colors, line);
7538 if (tc)
7539 wattr_on(view->window,
7540 COLOR_PAIR(tc->colorpair), NULL);
7541 waddwstr(view->window, &wline[scrollx]);
7542 if (tc)
7543 wattr_off(view->window,
7544 COLOR_PAIR(tc->colorpair), NULL);
7545 if (width < view->ncols)
7546 waddch(view->window, '\n');
7547 if (n == s->selected && view->focussed)
7548 wstandend(view->window);
7549 free(line);
7550 free(wline);
7551 wline = NULL;
7552 n++;
7553 s->ndisplayed++;
7554 s->last_displayed_entry = te;
7555 if (--limit <= 0)
7556 break;
7559 return err;
7562 static void
7563 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7565 struct got_tree_entry *te;
7566 int isroot = s->tree == s->root;
7567 int i = 0;
7569 if (s->first_displayed_entry == NULL)
7570 return;
7572 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7573 while (i++ < maxscroll) {
7574 if (te == NULL) {
7575 if (!isroot)
7576 s->first_displayed_entry = NULL;
7577 break;
7579 s->first_displayed_entry = te;
7580 te = got_tree_entry_get_prev(s->tree, te);
7584 static const struct got_error *
7585 tree_scroll_down(struct tog_view *view, int maxscroll)
7587 struct tog_tree_view_state *s = &view->state.tree;
7588 struct got_tree_entry *next, *last;
7589 int n = 0;
7591 if (s->first_displayed_entry)
7592 next = got_tree_entry_get_next(s->tree,
7593 s->first_displayed_entry);
7594 else
7595 next = got_object_tree_get_first_entry(s->tree);
7597 last = s->last_displayed_entry;
7598 while (next && n++ < maxscroll) {
7599 if (last) {
7600 s->last_displayed_entry = last;
7601 last = got_tree_entry_get_next(s->tree, last);
7603 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7604 s->first_displayed_entry = next;
7605 next = got_tree_entry_get_next(s->tree, next);
7609 return NULL;
7612 static const struct got_error *
7613 tree_entry_path(char **path, struct tog_parent_trees *parents,
7614 struct got_tree_entry *te)
7616 const struct got_error *err = NULL;
7617 struct tog_parent_tree *pt;
7618 size_t len = 2; /* for leading slash and NUL */
7620 TAILQ_FOREACH(pt, parents, entry)
7621 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7622 + 1 /* slash */;
7623 if (te)
7624 len += strlen(got_tree_entry_get_name(te));
7626 *path = calloc(1, len);
7627 if (path == NULL)
7628 return got_error_from_errno("calloc");
7630 (*path)[0] = '/';
7631 pt = TAILQ_LAST(parents, tog_parent_trees);
7632 while (pt) {
7633 const char *name = got_tree_entry_get_name(pt->selected_entry);
7634 if (strlcat(*path, name, len) >= len) {
7635 err = got_error(GOT_ERR_NO_SPACE);
7636 goto done;
7638 if (strlcat(*path, "/", len) >= len) {
7639 err = got_error(GOT_ERR_NO_SPACE);
7640 goto done;
7642 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7644 if (te) {
7645 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7646 err = got_error(GOT_ERR_NO_SPACE);
7647 goto done;
7650 done:
7651 if (err) {
7652 free(*path);
7653 *path = NULL;
7655 return err;
7658 static const struct got_error *
7659 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7660 struct got_tree_entry *te, struct tog_parent_trees *parents,
7661 struct got_object_id *commit_id, struct got_repository *repo)
7663 const struct got_error *err = NULL;
7664 char *path;
7665 struct tog_view *blame_view;
7667 *new_view = NULL;
7669 err = tree_entry_path(&path, parents, te);
7670 if (err)
7671 return err;
7673 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7674 if (blame_view == NULL) {
7675 err = got_error_from_errno("view_open");
7676 goto done;
7679 err = open_blame_view(blame_view, path, commit_id, repo);
7680 if (err) {
7681 if (err->code == GOT_ERR_CANCELLED)
7682 err = NULL;
7683 view_close(blame_view);
7684 } else
7685 *new_view = blame_view;
7686 done:
7687 free(path);
7688 return err;
7691 static const struct got_error *
7692 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7693 struct tog_tree_view_state *s)
7695 struct tog_view *log_view;
7696 const struct got_error *err = NULL;
7697 char *path;
7699 *new_view = NULL;
7701 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7702 if (log_view == NULL)
7703 return got_error_from_errno("view_open");
7705 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7706 if (err)
7707 return err;
7709 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7710 path, 0, NULL);
7711 if (err)
7712 view_close(log_view);
7713 else
7714 *new_view = log_view;
7715 free(path);
7716 return err;
7719 static const struct got_error *
7720 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7721 const char *head_ref_name, struct got_repository *repo)
7723 const struct got_error *err = NULL;
7724 char *commit_id_str = NULL;
7725 struct tog_tree_view_state *s = &view->state.tree;
7726 struct got_commit_object *commit = NULL;
7728 TAILQ_INIT(&s->parents);
7729 STAILQ_INIT(&s->colors);
7731 s->commit_id = got_object_id_dup(commit_id);
7732 if (s->commit_id == NULL) {
7733 err = got_error_from_errno("got_object_id_dup");
7734 goto done;
7737 err = got_object_open_as_commit(&commit, repo, commit_id);
7738 if (err)
7739 goto done;
7742 * The root is opened here and will be closed when the view is closed.
7743 * Any visited subtrees and their path-wise parents are opened and
7744 * closed on demand.
7746 err = got_object_open_as_tree(&s->root, repo,
7747 got_object_commit_get_tree_id(commit));
7748 if (err)
7749 goto done;
7750 s->tree = s->root;
7752 err = got_object_id_str(&commit_id_str, commit_id);
7753 if (err != NULL)
7754 goto done;
7756 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7757 err = got_error_from_errno("asprintf");
7758 goto done;
7761 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7762 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7763 if (head_ref_name) {
7764 s->head_ref_name = strdup(head_ref_name);
7765 if (s->head_ref_name == NULL) {
7766 err = got_error_from_errno("strdup");
7767 goto done;
7770 s->repo = repo;
7772 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7773 err = add_color(&s->colors, "\\$$",
7774 TOG_COLOR_TREE_SUBMODULE,
7775 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7776 if (err)
7777 goto done;
7778 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7779 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7780 if (err)
7781 goto done;
7782 err = add_color(&s->colors, "/$",
7783 TOG_COLOR_TREE_DIRECTORY,
7784 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7785 if (err)
7786 goto done;
7788 err = add_color(&s->colors, "\\*$",
7789 TOG_COLOR_TREE_EXECUTABLE,
7790 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7791 if (err)
7792 goto done;
7794 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7795 get_color_value("TOG_COLOR_COMMIT"));
7796 if (err)
7797 goto done;
7800 view->show = show_tree_view;
7801 view->input = input_tree_view;
7802 view->close = close_tree_view;
7803 view->search_start = search_start_tree_view;
7804 view->search_next = search_next_tree_view;
7805 done:
7806 free(commit_id_str);
7807 if (commit)
7808 got_object_commit_close(commit);
7809 if (err) {
7810 if (view->close == NULL)
7811 close_tree_view(view);
7812 view_close(view);
7814 return err;
7817 static const struct got_error *
7818 close_tree_view(struct tog_view *view)
7820 struct tog_tree_view_state *s = &view->state.tree;
7822 free_colors(&s->colors);
7823 free(s->tree_label);
7824 s->tree_label = NULL;
7825 free(s->commit_id);
7826 s->commit_id = NULL;
7827 free(s->head_ref_name);
7828 s->head_ref_name = NULL;
7829 while (!TAILQ_EMPTY(&s->parents)) {
7830 struct tog_parent_tree *parent;
7831 parent = TAILQ_FIRST(&s->parents);
7832 TAILQ_REMOVE(&s->parents, parent, entry);
7833 if (parent->tree != s->root)
7834 got_object_tree_close(parent->tree);
7835 free(parent);
7838 if (s->tree != NULL && s->tree != s->root)
7839 got_object_tree_close(s->tree);
7840 if (s->root)
7841 got_object_tree_close(s->root);
7842 return NULL;
7845 static const struct got_error *
7846 search_start_tree_view(struct tog_view *view)
7848 struct tog_tree_view_state *s = &view->state.tree;
7850 s->matched_entry = NULL;
7851 return NULL;
7854 static int
7855 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7857 regmatch_t regmatch;
7859 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7860 0) == 0;
7863 static const struct got_error *
7864 search_next_tree_view(struct tog_view *view)
7866 struct tog_tree_view_state *s = &view->state.tree;
7867 struct got_tree_entry *te = NULL;
7869 if (!view->searching) {
7870 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7871 return NULL;
7874 if (s->matched_entry) {
7875 if (view->searching == TOG_SEARCH_FORWARD) {
7876 if (s->selected_entry)
7877 te = got_tree_entry_get_next(s->tree,
7878 s->selected_entry);
7879 else
7880 te = got_object_tree_get_first_entry(s->tree);
7881 } else {
7882 if (s->selected_entry == NULL)
7883 te = got_object_tree_get_last_entry(s->tree);
7884 else
7885 te = got_tree_entry_get_prev(s->tree,
7886 s->selected_entry);
7888 } else {
7889 if (s->selected_entry)
7890 te = s->selected_entry;
7891 else if (view->searching == TOG_SEARCH_FORWARD)
7892 te = got_object_tree_get_first_entry(s->tree);
7893 else
7894 te = got_object_tree_get_last_entry(s->tree);
7897 while (1) {
7898 if (te == NULL) {
7899 if (s->matched_entry == NULL) {
7900 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7901 return NULL;
7903 if (view->searching == TOG_SEARCH_FORWARD)
7904 te = got_object_tree_get_first_entry(s->tree);
7905 else
7906 te = got_object_tree_get_last_entry(s->tree);
7909 if (match_tree_entry(te, &view->regex)) {
7910 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7911 s->matched_entry = te;
7912 break;
7915 if (view->searching == TOG_SEARCH_FORWARD)
7916 te = got_tree_entry_get_next(s->tree, te);
7917 else
7918 te = got_tree_entry_get_prev(s->tree, te);
7921 if (s->matched_entry) {
7922 s->first_displayed_entry = s->matched_entry;
7923 s->selected = 0;
7926 return NULL;
7929 static const struct got_error *
7930 show_tree_view(struct tog_view *view)
7932 const struct got_error *err = NULL;
7933 struct tog_tree_view_state *s = &view->state.tree;
7934 char *parent_path;
7936 err = tree_entry_path(&parent_path, &s->parents, NULL);
7937 if (err)
7938 return err;
7940 err = draw_tree_entries(view, parent_path);
7941 free(parent_path);
7943 view_border(view);
7944 return err;
7947 static const struct got_error *
7948 tree_goto_line(struct tog_view *view, int nlines)
7950 const struct got_error *err = NULL;
7951 struct tog_tree_view_state *s = &view->state.tree;
7952 struct got_tree_entry **fte, **lte, **ste;
7953 int g, last, first = 1, i = 1;
7954 int root = s->tree == s->root;
7955 int off = root ? 1 : 2;
7957 g = view->gline;
7958 view->gline = 0;
7960 if (g == 0)
7961 g = 1;
7962 else if (g > got_object_tree_get_nentries(s->tree))
7963 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7965 fte = &s->first_displayed_entry;
7966 lte = &s->last_displayed_entry;
7967 ste = &s->selected_entry;
7969 if (*fte != NULL) {
7970 first = got_tree_entry_get_index(*fte);
7971 first += off; /* account for ".." */
7973 last = got_tree_entry_get_index(*lte);
7974 last += off;
7976 if (g >= first && g <= last && g - first < nlines) {
7977 s->selected = g - first;
7978 return NULL; /* gline is on the current page */
7981 if (*ste != NULL) {
7982 i = got_tree_entry_get_index(*ste);
7983 i += off;
7986 if (i < g) {
7987 err = tree_scroll_down(view, g - i);
7988 if (err)
7989 return err;
7990 if (got_tree_entry_get_index(*lte) >=
7991 got_object_tree_get_nentries(s->tree) - 1 &&
7992 first + s->selected < g &&
7993 s->selected < s->ndisplayed - 1) {
7994 first = got_tree_entry_get_index(*fte);
7995 first += off;
7996 s->selected = g - first;
7998 } else if (i > g)
7999 tree_scroll_up(s, i - g);
8001 if (g < nlines &&
8002 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
8003 s->selected = g - 1;
8005 return NULL;
8008 static const struct got_error *
8009 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
8011 const struct got_error *err = NULL;
8012 struct tog_tree_view_state *s = &view->state.tree;
8013 struct got_tree_entry *te;
8014 int n, nscroll = view->nlines - 3;
8016 if (view->gline)
8017 return tree_goto_line(view, nscroll);
8019 switch (ch) {
8020 case '0':
8021 case '$':
8022 case KEY_RIGHT:
8023 case 'l':
8024 case KEY_LEFT:
8025 case 'h':
8026 horizontal_scroll_input(view, ch);
8027 break;
8028 case 'i':
8029 s->show_ids = !s->show_ids;
8030 view->count = 0;
8031 break;
8032 case 'L':
8033 view->count = 0;
8034 if (!s->selected_entry)
8035 break;
8036 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8037 break;
8038 case 'R':
8039 view->count = 0;
8040 err = view_request_new(new_view, view, TOG_VIEW_REF);
8041 break;
8042 case 'g':
8043 case '=':
8044 case KEY_HOME:
8045 s->selected = 0;
8046 view->count = 0;
8047 if (s->tree == s->root)
8048 s->first_displayed_entry =
8049 got_object_tree_get_first_entry(s->tree);
8050 else
8051 s->first_displayed_entry = NULL;
8052 break;
8053 case 'G':
8054 case '*':
8055 case KEY_END: {
8056 int eos = view->nlines - 3;
8058 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8059 --eos; /* border */
8060 s->selected = 0;
8061 view->count = 0;
8062 te = got_object_tree_get_last_entry(s->tree);
8063 for (n = 0; n < eos; n++) {
8064 if (te == NULL) {
8065 if (s->tree != s->root) {
8066 s->first_displayed_entry = NULL;
8067 n++;
8069 break;
8071 s->first_displayed_entry = te;
8072 te = got_tree_entry_get_prev(s->tree, te);
8074 if (n > 0)
8075 s->selected = n - 1;
8076 break;
8078 case 'k':
8079 case KEY_UP:
8080 case CTRL('p'):
8081 if (s->selected > 0) {
8082 s->selected--;
8083 break;
8085 tree_scroll_up(s, 1);
8086 if (s->selected_entry == NULL ||
8087 (s->tree == s->root && s->selected_entry ==
8088 got_object_tree_get_first_entry(s->tree)))
8089 view->count = 0;
8090 break;
8091 case CTRL('u'):
8092 case 'u':
8093 nscroll /= 2;
8094 /* FALL THROUGH */
8095 case KEY_PPAGE:
8096 case CTRL('b'):
8097 case 'b':
8098 if (s->tree == s->root) {
8099 if (got_object_tree_get_first_entry(s->tree) ==
8100 s->first_displayed_entry)
8101 s->selected -= MIN(s->selected, nscroll);
8102 } else {
8103 if (s->first_displayed_entry == NULL)
8104 s->selected -= MIN(s->selected, nscroll);
8106 tree_scroll_up(s, MAX(0, nscroll));
8107 if (s->selected_entry == NULL ||
8108 (s->tree == s->root && s->selected_entry ==
8109 got_object_tree_get_first_entry(s->tree)))
8110 view->count = 0;
8111 break;
8112 case 'j':
8113 case KEY_DOWN:
8114 case CTRL('n'):
8115 if (s->selected < s->ndisplayed - 1) {
8116 s->selected++;
8117 break;
8119 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8120 == NULL) {
8121 /* can't scroll any further */
8122 view->count = 0;
8123 break;
8125 tree_scroll_down(view, 1);
8126 break;
8127 case CTRL('d'):
8128 case 'd':
8129 nscroll /= 2;
8130 /* FALL THROUGH */
8131 case KEY_NPAGE:
8132 case CTRL('f'):
8133 case 'f':
8134 case ' ':
8135 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8136 == NULL) {
8137 /* can't scroll any further; move cursor down */
8138 if (s->selected < s->ndisplayed - 1)
8139 s->selected += MIN(nscroll,
8140 s->ndisplayed - s->selected - 1);
8141 else
8142 view->count = 0;
8143 break;
8145 tree_scroll_down(view, nscroll);
8146 break;
8147 case KEY_ENTER:
8148 case '\r':
8149 case KEY_BACKSPACE:
8150 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
8151 struct tog_parent_tree *parent;
8152 /* user selected '..' */
8153 if (s->tree == s->root) {
8154 view->count = 0;
8155 break;
8157 parent = TAILQ_FIRST(&s->parents);
8158 TAILQ_REMOVE(&s->parents, parent,
8159 entry);
8160 got_object_tree_close(s->tree);
8161 s->tree = parent->tree;
8162 s->first_displayed_entry =
8163 parent->first_displayed_entry;
8164 s->selected_entry =
8165 parent->selected_entry;
8166 s->selected = parent->selected;
8167 if (s->selected > view->nlines - 3) {
8168 err = offset_selection_down(view);
8169 if (err)
8170 break;
8172 free(parent);
8173 } else if (S_ISDIR(got_tree_entry_get_mode(
8174 s->selected_entry))) {
8175 struct got_tree_object *subtree;
8176 view->count = 0;
8177 err = got_object_open_as_tree(&subtree, s->repo,
8178 got_tree_entry_get_id(s->selected_entry));
8179 if (err)
8180 break;
8181 err = tree_view_visit_subtree(s, subtree);
8182 if (err) {
8183 got_object_tree_close(subtree);
8184 break;
8186 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
8187 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
8188 break;
8189 case KEY_RESIZE:
8190 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
8191 s->selected = view->nlines - 4;
8192 view->count = 0;
8193 break;
8194 default:
8195 view->count = 0;
8196 break;
8199 return err;
8202 __dead static void
8203 usage_tree(void)
8205 endwin();
8206 fprintf(stderr,
8207 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
8208 getprogname());
8209 exit(1);
8212 static const struct got_error *
8213 cmd_tree(int argc, char *argv[])
8215 const struct got_error *error;
8216 struct got_repository *repo = NULL;
8217 struct got_worktree *worktree = NULL;
8218 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8219 struct got_object_id *commit_id = NULL;
8220 struct got_commit_object *commit = NULL;
8221 const char *commit_id_arg = NULL;
8222 char *keyword_idstr = NULL, *label = NULL;
8223 struct got_reference *ref = NULL;
8224 const char *head_ref_name = NULL;
8225 int ch;
8226 struct tog_view *view;
8227 int *pack_fds = NULL;
8229 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
8230 switch (ch) {
8231 case 'c':
8232 commit_id_arg = optarg;
8233 break;
8234 case 'r':
8235 repo_path = realpath(optarg, NULL);
8236 if (repo_path == NULL)
8237 return got_error_from_errno2("realpath",
8238 optarg);
8239 break;
8240 default:
8241 usage_tree();
8242 /* NOTREACHED */
8246 argc -= optind;
8247 argv += optind;
8249 if (argc > 1)
8250 usage_tree();
8252 error = got_repo_pack_fds_open(&pack_fds);
8253 if (error != NULL)
8254 goto done;
8256 if (repo_path == NULL) {
8257 cwd = getcwd(NULL, 0);
8258 if (cwd == NULL)
8259 return got_error_from_errno("getcwd");
8260 error = got_worktree_open(&worktree, cwd, NULL);
8261 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8262 goto done;
8263 if (worktree)
8264 repo_path =
8265 strdup(got_worktree_get_repo_path(worktree));
8266 else
8267 repo_path = strdup(cwd);
8268 if (repo_path == NULL) {
8269 error = got_error_from_errno("strdup");
8270 goto done;
8274 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8275 if (error != NULL)
8276 goto done;
8278 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8279 repo, worktree);
8280 if (error)
8281 goto done;
8283 init_curses();
8285 error = apply_unveil(got_repo_get_path(repo), NULL);
8286 if (error)
8287 goto done;
8289 error = tog_load_refs(repo, 0);
8290 if (error)
8291 goto done;
8293 if (commit_id_arg == NULL) {
8294 error = got_repo_match_object_id(&commit_id, &label,
8295 worktree ? got_worktree_get_head_ref_name(worktree) :
8296 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8297 if (error)
8298 goto done;
8299 head_ref_name = label;
8300 } else {
8301 error = got_keyword_to_idstr(&keyword_idstr, commit_id_arg,
8302 repo, worktree);
8303 if (error != NULL)
8304 goto done;
8305 if (keyword_idstr != NULL)
8306 commit_id_arg = keyword_idstr;
8308 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8309 if (error == NULL)
8310 head_ref_name = got_ref_get_name(ref);
8311 else if (error->code != GOT_ERR_NOT_REF)
8312 goto done;
8313 error = got_repo_match_object_id(&commit_id, NULL,
8314 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8315 if (error)
8316 goto done;
8319 error = got_object_open_as_commit(&commit, repo, commit_id);
8320 if (error)
8321 goto done;
8323 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8324 if (view == NULL) {
8325 error = got_error_from_errno("view_open");
8326 goto done;
8328 error = open_tree_view(view, commit_id, head_ref_name, repo);
8329 if (error)
8330 goto done;
8331 if (!got_path_is_root_dir(in_repo_path)) {
8332 error = tree_view_walk_path(&view->state.tree, commit,
8333 in_repo_path);
8334 if (error)
8335 goto done;
8338 if (worktree) {
8339 error = set_tog_base_commit(repo, worktree);
8340 if (error != NULL)
8341 goto done;
8343 /* Release work tree lock. */
8344 got_worktree_close(worktree);
8345 worktree = NULL;
8348 error = view_loop(view);
8350 done:
8351 free(tog_base_commit.id);
8352 free(keyword_idstr);
8353 free(repo_path);
8354 free(cwd);
8355 free(commit_id);
8356 free(label);
8357 if (ref)
8358 got_ref_close(ref);
8359 if (worktree != NULL)
8360 got_worktree_close(worktree);
8361 if (repo) {
8362 const struct got_error *close_err = got_repo_close(repo);
8363 if (error == NULL)
8364 error = close_err;
8366 if (pack_fds) {
8367 const struct got_error *pack_err =
8368 got_repo_pack_fds_close(pack_fds);
8369 if (error == NULL)
8370 error = pack_err;
8372 tog_free_refs();
8373 return error;
8376 static const struct got_error *
8377 ref_view_load_refs(struct tog_ref_view_state *s)
8379 struct got_reflist_entry *sre;
8380 struct tog_reflist_entry *re;
8382 s->nrefs = 0;
8383 TAILQ_FOREACH(sre, &tog_refs, entry) {
8384 if (strncmp(got_ref_get_name(sre->ref),
8385 "refs/got/", 9) == 0 &&
8386 strncmp(got_ref_get_name(sre->ref),
8387 "refs/got/backup/", 16) != 0)
8388 continue;
8390 re = malloc(sizeof(*re));
8391 if (re == NULL)
8392 return got_error_from_errno("malloc");
8394 re->ref = got_ref_dup(sre->ref);
8395 if (re->ref == NULL)
8396 return got_error_from_errno("got_ref_dup");
8397 re->idx = s->nrefs++;
8398 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8401 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8402 return NULL;
8405 static void
8406 ref_view_free_refs(struct tog_ref_view_state *s)
8408 struct tog_reflist_entry *re;
8410 while (!TAILQ_EMPTY(&s->refs)) {
8411 re = TAILQ_FIRST(&s->refs);
8412 TAILQ_REMOVE(&s->refs, re, entry);
8413 got_ref_close(re->ref);
8414 free(re);
8418 static const struct got_error *
8419 open_ref_view(struct tog_view *view, struct got_repository *repo)
8421 const struct got_error *err = NULL;
8422 struct tog_ref_view_state *s = &view->state.ref;
8424 s->selected_entry = 0;
8425 s->repo = repo;
8427 TAILQ_INIT(&s->refs);
8428 STAILQ_INIT(&s->colors);
8430 err = ref_view_load_refs(s);
8431 if (err)
8432 goto done;
8434 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8435 err = add_color(&s->colors, "^refs/heads/",
8436 TOG_COLOR_REFS_HEADS,
8437 get_color_value("TOG_COLOR_REFS_HEADS"));
8438 if (err)
8439 goto done;
8441 err = add_color(&s->colors, "^refs/tags/",
8442 TOG_COLOR_REFS_TAGS,
8443 get_color_value("TOG_COLOR_REFS_TAGS"));
8444 if (err)
8445 goto done;
8447 err = add_color(&s->colors, "^refs/remotes/",
8448 TOG_COLOR_REFS_REMOTES,
8449 get_color_value("TOG_COLOR_REFS_REMOTES"));
8450 if (err)
8451 goto done;
8453 err = add_color(&s->colors, "^refs/got/backup/",
8454 TOG_COLOR_REFS_BACKUP,
8455 get_color_value("TOG_COLOR_REFS_BACKUP"));
8456 if (err)
8457 goto done;
8460 view->show = show_ref_view;
8461 view->input = input_ref_view;
8462 view->close = close_ref_view;
8463 view->search_start = search_start_ref_view;
8464 view->search_next = search_next_ref_view;
8465 done:
8466 if (err) {
8467 if (view->close == NULL)
8468 close_ref_view(view);
8469 view_close(view);
8471 return err;
8474 static const struct got_error *
8475 close_ref_view(struct tog_view *view)
8477 struct tog_ref_view_state *s = &view->state.ref;
8479 ref_view_free_refs(s);
8480 free_colors(&s->colors);
8482 return NULL;
8485 static const struct got_error *
8486 resolve_reflist_entry(struct got_object_id **commit_id,
8487 struct tog_reflist_entry *re, struct got_repository *repo)
8489 const struct got_error *err = NULL;
8490 struct got_object_id *obj_id;
8491 struct got_tag_object *tag = NULL;
8492 int obj_type;
8494 *commit_id = NULL;
8496 err = got_ref_resolve(&obj_id, repo, re->ref);
8497 if (err)
8498 return err;
8500 err = got_object_get_type(&obj_type, repo, obj_id);
8501 if (err)
8502 goto done;
8504 switch (obj_type) {
8505 case GOT_OBJ_TYPE_COMMIT:
8506 *commit_id = obj_id;
8507 break;
8508 case GOT_OBJ_TYPE_TAG:
8509 err = got_object_open_as_tag(&tag, repo, obj_id);
8510 if (err)
8511 goto done;
8512 free(obj_id);
8513 err = got_object_get_type(&obj_type, repo,
8514 got_object_tag_get_object_id(tag));
8515 if (err)
8516 goto done;
8517 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8518 err = got_error(GOT_ERR_OBJ_TYPE);
8519 goto done;
8521 *commit_id = got_object_id_dup(
8522 got_object_tag_get_object_id(tag));
8523 if (*commit_id == NULL) {
8524 err = got_error_from_errno("got_object_id_dup");
8525 goto done;
8527 break;
8528 default:
8529 err = got_error(GOT_ERR_OBJ_TYPE);
8530 break;
8533 done:
8534 if (tag)
8535 got_object_tag_close(tag);
8536 if (err) {
8537 free(*commit_id);
8538 *commit_id = NULL;
8540 return err;
8543 static const struct got_error *
8544 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8545 struct tog_reflist_entry *re, struct got_repository *repo)
8547 struct tog_view *log_view;
8548 const struct got_error *err = NULL;
8549 struct got_object_id *commit_id = NULL;
8551 *new_view = NULL;
8553 err = resolve_reflist_entry(&commit_id, re, repo);
8554 if (err) {
8555 if (err->code != GOT_ERR_OBJ_TYPE)
8556 return err;
8557 else
8558 return NULL;
8561 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8562 if (log_view == NULL) {
8563 err = got_error_from_errno("view_open");
8564 goto done;
8567 err = open_log_view(log_view, commit_id, repo,
8568 got_ref_get_name(re->ref), "", 0, NULL);
8569 done:
8570 if (err)
8571 view_close(log_view);
8572 else
8573 *new_view = log_view;
8574 free(commit_id);
8575 return err;
8578 static void
8579 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8581 struct tog_reflist_entry *re;
8582 int i = 0;
8584 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8585 return;
8587 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8588 while (i++ < maxscroll) {
8589 if (re == NULL)
8590 break;
8591 s->first_displayed_entry = re;
8592 re = TAILQ_PREV(re, tog_reflist_head, entry);
8596 static const struct got_error *
8597 ref_scroll_down(struct tog_view *view, int maxscroll)
8599 struct tog_ref_view_state *s = &view->state.ref;
8600 struct tog_reflist_entry *next, *last;
8601 int n = 0;
8603 if (s->first_displayed_entry)
8604 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8605 else
8606 next = TAILQ_FIRST(&s->refs);
8608 last = s->last_displayed_entry;
8609 while (next && n++ < maxscroll) {
8610 if (last) {
8611 s->last_displayed_entry = last;
8612 last = TAILQ_NEXT(last, entry);
8614 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8615 s->first_displayed_entry = next;
8616 next = TAILQ_NEXT(next, entry);
8620 return NULL;
8623 static const struct got_error *
8624 search_start_ref_view(struct tog_view *view)
8626 struct tog_ref_view_state *s = &view->state.ref;
8628 s->matched_entry = NULL;
8629 return NULL;
8632 static int
8633 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8635 regmatch_t regmatch;
8637 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8638 0) == 0;
8641 static const struct got_error *
8642 search_next_ref_view(struct tog_view *view)
8644 struct tog_ref_view_state *s = &view->state.ref;
8645 struct tog_reflist_entry *re = NULL;
8647 if (!view->searching) {
8648 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8649 return NULL;
8652 if (s->matched_entry) {
8653 if (view->searching == TOG_SEARCH_FORWARD) {
8654 if (s->selected_entry)
8655 re = TAILQ_NEXT(s->selected_entry, entry);
8656 else
8657 re = TAILQ_PREV(s->selected_entry,
8658 tog_reflist_head, entry);
8659 } else {
8660 if (s->selected_entry == NULL)
8661 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8662 else
8663 re = TAILQ_PREV(s->selected_entry,
8664 tog_reflist_head, entry);
8666 } else {
8667 if (s->selected_entry)
8668 re = s->selected_entry;
8669 else if (view->searching == TOG_SEARCH_FORWARD)
8670 re = TAILQ_FIRST(&s->refs);
8671 else
8672 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8675 while (1) {
8676 if (re == NULL) {
8677 if (s->matched_entry == NULL) {
8678 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8679 return NULL;
8681 if (view->searching == TOG_SEARCH_FORWARD)
8682 re = TAILQ_FIRST(&s->refs);
8683 else
8684 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8687 if (match_reflist_entry(re, &view->regex)) {
8688 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8689 s->matched_entry = re;
8690 break;
8693 if (view->searching == TOG_SEARCH_FORWARD)
8694 re = TAILQ_NEXT(re, entry);
8695 else
8696 re = TAILQ_PREV(re, tog_reflist_head, entry);
8699 if (s->matched_entry) {
8700 s->first_displayed_entry = s->matched_entry;
8701 s->selected = 0;
8704 return NULL;
8707 static const struct got_error *
8708 show_ref_view(struct tog_view *view)
8710 const struct got_error *err = NULL;
8711 struct tog_ref_view_state *s = &view->state.ref;
8712 struct tog_reflist_entry *re;
8713 char *line = NULL;
8714 wchar_t *wline;
8715 struct tog_color *tc;
8716 int width, n, scrollx;
8717 int limit = view->nlines;
8719 werase(view->window);
8721 s->ndisplayed = 0;
8722 if (view_is_hsplit_top(view))
8723 --limit; /* border */
8725 if (limit == 0)
8726 return NULL;
8728 re = s->first_displayed_entry;
8730 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8731 s->nrefs) == -1)
8732 return got_error_from_errno("asprintf");
8734 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8735 if (err) {
8736 free(line);
8737 return err;
8739 if (view_needs_focus_indication(view))
8740 wstandout(view->window);
8741 waddwstr(view->window, wline);
8742 while (width++ < view->ncols)
8743 waddch(view->window, ' ');
8744 if (view_needs_focus_indication(view))
8745 wstandend(view->window);
8746 free(wline);
8747 wline = NULL;
8748 free(line);
8749 line = NULL;
8750 if (--limit <= 0)
8751 return NULL;
8753 n = 0;
8754 view->maxx = 0;
8755 while (re && limit > 0) {
8756 char *line = NULL;
8757 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8759 if (s->show_date) {
8760 struct got_commit_object *ci;
8761 struct got_tag_object *tag;
8762 struct got_object_id *id;
8763 struct tm tm;
8764 time_t t;
8766 err = got_ref_resolve(&id, s->repo, re->ref);
8767 if (err)
8768 return err;
8769 err = got_object_open_as_tag(&tag, s->repo, id);
8770 if (err) {
8771 if (err->code != GOT_ERR_OBJ_TYPE) {
8772 free(id);
8773 return err;
8775 err = got_object_open_as_commit(&ci, s->repo,
8776 id);
8777 if (err) {
8778 free(id);
8779 return err;
8781 t = got_object_commit_get_committer_time(ci);
8782 got_object_commit_close(ci);
8783 } else {
8784 t = got_object_tag_get_tagger_time(tag);
8785 got_object_tag_close(tag);
8787 free(id);
8788 if (gmtime_r(&t, &tm) == NULL)
8789 return got_error_from_errno("gmtime_r");
8790 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8791 return got_error(GOT_ERR_NO_SPACE);
8793 if (got_ref_is_symbolic(re->ref)) {
8794 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8795 ymd : "", got_ref_get_name(re->ref),
8796 got_ref_get_symref_target(re->ref)) == -1)
8797 return got_error_from_errno("asprintf");
8798 } else if (s->show_ids) {
8799 struct got_object_id *id;
8800 char *id_str;
8801 err = got_ref_resolve(&id, s->repo, re->ref);
8802 if (err)
8803 return err;
8804 err = got_object_id_str(&id_str, id);
8805 if (err) {
8806 free(id);
8807 return err;
8809 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8810 got_ref_get_name(re->ref), id_str) == -1) {
8811 err = got_error_from_errno("asprintf");
8812 free(id);
8813 free(id_str);
8814 return err;
8816 free(id);
8817 free(id_str);
8818 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8819 got_ref_get_name(re->ref)) == -1)
8820 return got_error_from_errno("asprintf");
8822 /* use full line width to determine view->maxx */
8823 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8824 if (err) {
8825 free(line);
8826 return err;
8828 view->maxx = MAX(view->maxx, width);
8829 free(wline);
8830 wline = NULL;
8832 err = format_line(&wline, &width, &scrollx, line, view->x,
8833 view->ncols, 0, 0);
8834 if (err) {
8835 free(line);
8836 return err;
8838 if (n == s->selected) {
8839 if (view->focussed)
8840 wstandout(view->window);
8841 s->selected_entry = re;
8843 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8844 if (tc)
8845 wattr_on(view->window,
8846 COLOR_PAIR(tc->colorpair), NULL);
8847 waddwstr(view->window, &wline[scrollx]);
8848 if (tc)
8849 wattr_off(view->window,
8850 COLOR_PAIR(tc->colorpair), NULL);
8851 if (width < view->ncols)
8852 waddch(view->window, '\n');
8853 if (n == s->selected && view->focussed)
8854 wstandend(view->window);
8855 free(line);
8856 free(wline);
8857 wline = NULL;
8858 n++;
8859 s->ndisplayed++;
8860 s->last_displayed_entry = re;
8862 limit--;
8863 re = TAILQ_NEXT(re, entry);
8866 view_border(view);
8867 return err;
8870 static const struct got_error *
8871 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8872 struct tog_reflist_entry *re, struct got_repository *repo)
8874 const struct got_error *err = NULL;
8875 struct got_object_id *commit_id = NULL;
8876 struct tog_view *tree_view;
8878 *new_view = NULL;
8880 err = resolve_reflist_entry(&commit_id, re, repo);
8881 if (err) {
8882 if (err->code != GOT_ERR_OBJ_TYPE)
8883 return err;
8884 else
8885 return NULL;
8889 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8890 if (tree_view == NULL) {
8891 err = got_error_from_errno("view_open");
8892 goto done;
8895 err = open_tree_view(tree_view, commit_id,
8896 got_ref_get_name(re->ref), repo);
8897 if (err)
8898 goto done;
8900 *new_view = tree_view;
8901 done:
8902 free(commit_id);
8903 return err;
8906 static const struct got_error *
8907 ref_goto_line(struct tog_view *view, int nlines)
8909 const struct got_error *err = NULL;
8910 struct tog_ref_view_state *s = &view->state.ref;
8911 int g, idx = s->selected_entry->idx;
8913 g = view->gline;
8914 view->gline = 0;
8916 if (g == 0)
8917 g = 1;
8918 else if (g > s->nrefs)
8919 g = s->nrefs;
8921 if (g >= s->first_displayed_entry->idx + 1 &&
8922 g <= s->last_displayed_entry->idx + 1 &&
8923 g - s->first_displayed_entry->idx - 1 < nlines) {
8924 s->selected = g - s->first_displayed_entry->idx - 1;
8925 return NULL;
8928 if (idx + 1 < g) {
8929 err = ref_scroll_down(view, g - idx - 1);
8930 if (err)
8931 return err;
8932 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8933 s->first_displayed_entry->idx + s->selected < g &&
8934 s->selected < s->ndisplayed - 1)
8935 s->selected = g - s->first_displayed_entry->idx - 1;
8936 } else if (idx + 1 > g)
8937 ref_scroll_up(s, idx - g + 1);
8939 if (g < nlines && s->first_displayed_entry->idx == 0)
8940 s->selected = g - 1;
8942 return NULL;
8946 static const struct got_error *
8947 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8949 const struct got_error *err = NULL;
8950 struct tog_ref_view_state *s = &view->state.ref;
8951 struct tog_reflist_entry *re;
8952 int n, nscroll = view->nlines - 1;
8954 if (view->gline)
8955 return ref_goto_line(view, nscroll);
8957 switch (ch) {
8958 case '0':
8959 case '$':
8960 case KEY_RIGHT:
8961 case 'l':
8962 case KEY_LEFT:
8963 case 'h':
8964 horizontal_scroll_input(view, ch);
8965 break;
8966 case 'i':
8967 s->show_ids = !s->show_ids;
8968 view->count = 0;
8969 break;
8970 case 'm':
8971 s->show_date = !s->show_date;
8972 view->count = 0;
8973 break;
8974 case 'o':
8975 s->sort_by_date = !s->sort_by_date;
8976 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8977 view->count = 0;
8978 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8979 got_ref_cmp_by_commit_timestamp_descending :
8980 tog_ref_cmp_by_name, s->repo);
8981 if (err)
8982 break;
8983 got_reflist_object_id_map_free(tog_refs_idmap);
8984 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8985 &tog_refs, s->repo);
8986 if (err)
8987 break;
8988 ref_view_free_refs(s);
8989 err = ref_view_load_refs(s);
8990 break;
8991 case KEY_ENTER:
8992 case '\r':
8993 view->count = 0;
8994 if (!s->selected_entry)
8995 break;
8996 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8997 break;
8998 case 'T':
8999 view->count = 0;
9000 if (!s->selected_entry)
9001 break;
9002 err = view_request_new(new_view, view, TOG_VIEW_TREE);
9003 break;
9004 case 'g':
9005 case '=':
9006 case KEY_HOME:
9007 s->selected = 0;
9008 view->count = 0;
9009 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
9010 break;
9011 case 'G':
9012 case '*':
9013 case KEY_END: {
9014 int eos = view->nlines - 1;
9016 if (view->mode == TOG_VIEW_SPLIT_HRZN)
9017 --eos; /* border */
9018 s->selected = 0;
9019 view->count = 0;
9020 re = TAILQ_LAST(&s->refs, tog_reflist_head);
9021 for (n = 0; n < eos; n++) {
9022 if (re == NULL)
9023 break;
9024 s->first_displayed_entry = re;
9025 re = TAILQ_PREV(re, tog_reflist_head, entry);
9027 if (n > 0)
9028 s->selected = n - 1;
9029 break;
9031 case 'k':
9032 case KEY_UP:
9033 case CTRL('p'):
9034 if (s->selected > 0) {
9035 s->selected--;
9036 break;
9038 ref_scroll_up(s, 1);
9039 if (s->selected_entry == TAILQ_FIRST(&s->refs))
9040 view->count = 0;
9041 break;
9042 case CTRL('u'):
9043 case 'u':
9044 nscroll /= 2;
9045 /* FALL THROUGH */
9046 case KEY_PPAGE:
9047 case CTRL('b'):
9048 case 'b':
9049 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
9050 s->selected -= MIN(nscroll, s->selected);
9051 ref_scroll_up(s, MAX(0, nscroll));
9052 if (s->selected_entry == TAILQ_FIRST(&s->refs))
9053 view->count = 0;
9054 break;
9055 case 'j':
9056 case KEY_DOWN:
9057 case CTRL('n'):
9058 if (s->selected < s->ndisplayed - 1) {
9059 s->selected++;
9060 break;
9062 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
9063 /* can't scroll any further */
9064 view->count = 0;
9065 break;
9067 ref_scroll_down(view, 1);
9068 break;
9069 case CTRL('d'):
9070 case 'd':
9071 nscroll /= 2;
9072 /* FALL THROUGH */
9073 case KEY_NPAGE:
9074 case CTRL('f'):
9075 case 'f':
9076 case ' ':
9077 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
9078 /* can't scroll any further; move cursor down */
9079 if (s->selected < s->ndisplayed - 1)
9080 s->selected += MIN(nscroll,
9081 s->ndisplayed - s->selected - 1);
9082 if (view->count > 1 && s->selected < s->ndisplayed - 1)
9083 s->selected += s->ndisplayed - s->selected - 1;
9084 view->count = 0;
9085 break;
9087 ref_scroll_down(view, nscroll);
9088 break;
9089 case CTRL('l'):
9090 view->count = 0;
9091 tog_free_refs();
9092 err = tog_load_refs(s->repo, s->sort_by_date);
9093 if (err)
9094 break;
9095 ref_view_free_refs(s);
9096 err = ref_view_load_refs(s);
9097 break;
9098 case KEY_RESIZE:
9099 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
9100 s->selected = view->nlines - 2;
9101 break;
9102 default:
9103 view->count = 0;
9104 break;
9107 return err;
9110 __dead static void
9111 usage_ref(void)
9113 endwin();
9114 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
9115 getprogname());
9116 exit(1);
9119 static const struct got_error *
9120 cmd_ref(int argc, char *argv[])
9122 const struct got_error *error;
9123 struct got_repository *repo = NULL;
9124 struct got_worktree *worktree = NULL;
9125 char *cwd = NULL, *repo_path = NULL;
9126 int ch;
9127 struct tog_view *view;
9128 int *pack_fds = NULL;
9130 while ((ch = getopt(argc, argv, "r:")) != -1) {
9131 switch (ch) {
9132 case 'r':
9133 repo_path = realpath(optarg, NULL);
9134 if (repo_path == NULL)
9135 return got_error_from_errno2("realpath",
9136 optarg);
9137 break;
9138 default:
9139 usage_ref();
9140 /* NOTREACHED */
9144 argc -= optind;
9145 argv += optind;
9147 if (argc > 1)
9148 usage_ref();
9150 error = got_repo_pack_fds_open(&pack_fds);
9151 if (error != NULL)
9152 goto done;
9154 if (repo_path == NULL) {
9155 cwd = getcwd(NULL, 0);
9156 if (cwd == NULL)
9157 return got_error_from_errno("getcwd");
9158 error = got_worktree_open(&worktree, cwd, NULL);
9159 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9160 goto done;
9161 if (worktree)
9162 repo_path =
9163 strdup(got_worktree_get_repo_path(worktree));
9164 else
9165 repo_path = strdup(cwd);
9166 if (repo_path == NULL) {
9167 error = got_error_from_errno("strdup");
9168 goto done;
9172 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9173 if (error != NULL)
9174 goto done;
9176 init_curses();
9178 error = apply_unveil(got_repo_get_path(repo), NULL);
9179 if (error)
9180 goto done;
9182 error = tog_load_refs(repo, 0);
9183 if (error)
9184 goto done;
9186 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
9187 if (view == NULL) {
9188 error = got_error_from_errno("view_open");
9189 goto done;
9192 error = open_ref_view(view, repo);
9193 if (error)
9194 goto done;
9196 if (worktree) {
9197 error = set_tog_base_commit(repo, worktree);
9198 if (error != NULL)
9199 goto done;
9201 /* Release work tree lock. */
9202 got_worktree_close(worktree);
9203 worktree = NULL;
9206 error = view_loop(view);
9208 done:
9209 free(tog_base_commit.id);
9210 free(repo_path);
9211 free(cwd);
9212 if (worktree != NULL)
9213 got_worktree_close(worktree);
9214 if (repo) {
9215 const struct got_error *close_err = got_repo_close(repo);
9216 if (close_err)
9217 error = close_err;
9219 if (pack_fds) {
9220 const struct got_error *pack_err =
9221 got_repo_pack_fds_close(pack_fds);
9222 if (error == NULL)
9223 error = pack_err;
9225 tog_free_refs();
9226 return error;
9229 static const struct got_error*
9230 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
9231 const char *str)
9233 size_t len;
9235 if (win == NULL)
9236 win = stdscr;
9238 len = strlen(str);
9239 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
9241 if (focus)
9242 wstandout(win);
9243 if (mvwprintw(win, y, x, "%s", str) == ERR)
9244 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
9245 if (focus)
9246 wstandend(win);
9248 return NULL;
9251 static const struct got_error *
9252 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
9254 off_t *p;
9256 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
9257 if (p == NULL) {
9258 free(*line_offsets);
9259 *line_offsets = NULL;
9260 return got_error_from_errno("reallocarray");
9263 *line_offsets = p;
9264 (*line_offsets)[*nlines] = off;
9265 ++(*nlines);
9266 return NULL;
9269 static const struct got_error *
9270 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
9272 *ret = 0;
9274 for (;n > 0; --n, ++km) {
9275 char *t0, *t, *k;
9276 size_t len = 1;
9278 if (km->keys == NULL)
9279 continue;
9281 t = t0 = strdup(km->keys);
9282 if (t0 == NULL)
9283 return got_error_from_errno("strdup");
9285 len += strlen(t);
9286 while ((k = strsep(&t, " ")) != NULL)
9287 len += strlen(k) > 1 ? 2 : 0;
9288 free(t0);
9289 *ret = MAX(*ret, len);
9292 return NULL;
9296 * Write keymap section headers, keys, and key info in km to f.
9297 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9298 * wrap control and symbolic keys in guillemets, else use <>.
9300 static const struct got_error *
9301 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9303 int n, len = width;
9305 if (km->keys) {
9306 static const char *u8_glyph[] = {
9307 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9308 "\xe2\x80\xba" /* U+203A (utf8 >) */
9310 char *t0, *t, *k;
9311 int cs, s, first = 1;
9313 cs = got_locale_is_utf8();
9315 t = t0 = strdup(km->keys);
9316 if (t0 == NULL)
9317 return got_error_from_errno("strdup");
9319 len = strlen(km->keys);
9320 while ((k = strsep(&t, " ")) != NULL) {
9321 s = strlen(k) > 1; /* control or symbolic key */
9322 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9323 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9324 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9325 if (n < 0) {
9326 free(t0);
9327 return got_error_from_errno("fprintf");
9329 first = 0;
9330 len += s ? 2 : 0;
9331 *off += n;
9333 free(t0);
9335 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9336 if (n < 0)
9337 return got_error_from_errno("fprintf");
9338 *off += n;
9340 return NULL;
9343 static const struct got_error *
9344 format_help(struct tog_help_view_state *s)
9346 const struct got_error *err = NULL;
9347 off_t off = 0;
9348 int i, max, n, show = s->all;
9349 static const struct tog_key_map km[] = {
9350 #define KEYMAP_(info, type) { NULL, (info), type }
9351 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9352 GENERATE_HELP
9353 #undef KEYMAP_
9354 #undef KEY_
9357 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9358 if (err)
9359 return err;
9361 n = nitems(km);
9362 err = max_key_str(&max, km, n);
9363 if (err)
9364 return err;
9366 for (i = 0; i < n; ++i) {
9367 if (km[i].keys == NULL) {
9368 show = s->all;
9369 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9370 km[i].type == s->type || s->all)
9371 show = 1;
9373 if (show) {
9374 err = format_help_line(&off, s->f, &km[i], max);
9375 if (err)
9376 return err;
9377 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9378 if (err)
9379 return err;
9382 fputc('\n', s->f);
9383 ++off;
9384 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9385 return err;
9388 static const struct got_error *
9389 create_help(struct tog_help_view_state *s)
9391 FILE *f;
9392 const struct got_error *err;
9394 free(s->line_offsets);
9395 s->line_offsets = NULL;
9396 s->nlines = 0;
9398 f = got_opentemp();
9399 if (f == NULL)
9400 return got_error_from_errno("got_opentemp");
9401 s->f = f;
9403 err = format_help(s);
9404 if (err)
9405 return err;
9407 if (s->f && fflush(s->f) != 0)
9408 return got_error_from_errno("fflush");
9410 return NULL;
9413 static const struct got_error *
9414 search_start_help_view(struct tog_view *view)
9416 view->state.help.matched_line = 0;
9417 return NULL;
9420 static void
9421 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9422 size_t *nlines, int **first, int **last, int **match, int **selected)
9424 struct tog_help_view_state *s = &view->state.help;
9426 *f = s->f;
9427 *nlines = s->nlines;
9428 *line_offsets = s->line_offsets;
9429 *match = &s->matched_line;
9430 *first = &s->first_displayed_line;
9431 *last = &s->last_displayed_line;
9432 *selected = &s->selected_line;
9435 static const struct got_error *
9436 show_help_view(struct tog_view *view)
9438 struct tog_help_view_state *s = &view->state.help;
9439 const struct got_error *err;
9440 regmatch_t *regmatch = &view->regmatch;
9441 wchar_t *wline;
9442 char *line;
9443 ssize_t linelen;
9444 size_t linesz = 0;
9445 int width, nprinted = 0, rc = 0;
9446 int eos = view->nlines;
9448 if (view_is_hsplit_top(view))
9449 --eos; /* account for border */
9451 s->lineno = 0;
9452 rewind(s->f);
9453 werase(view->window);
9455 if (view->gline > s->nlines - 1)
9456 view->gline = s->nlines - 1;
9458 err = win_draw_center(view->window, 0, 0, view->ncols,
9459 view_needs_focus_indication(view),
9460 "tog help (press q to return to tog)");
9461 if (err)
9462 return err;
9463 if (eos <= 1)
9464 return NULL;
9465 waddstr(view->window, "\n\n");
9466 eos -= 2;
9468 s->eof = 0;
9469 view->maxx = 0;
9470 line = NULL;
9471 while (eos > 0 && nprinted < eos) {
9472 attr_t attr = 0;
9474 linelen = getline(&line, &linesz, s->f);
9475 if (linelen == -1) {
9476 if (!feof(s->f)) {
9477 free(line);
9478 return got_ferror(s->f, GOT_ERR_IO);
9480 s->eof = 1;
9481 break;
9483 if (++s->lineno < s->first_displayed_line)
9484 continue;
9485 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9486 continue;
9487 if (s->lineno == view->hiline)
9488 attr = A_STANDOUT;
9490 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9491 view->x ? 1 : 0);
9492 if (err) {
9493 free(line);
9494 return err;
9496 view->maxx = MAX(view->maxx, width);
9497 free(wline);
9498 wline = NULL;
9500 if (attr)
9501 wattron(view->window, attr);
9502 if (s->first_displayed_line + nprinted == s->matched_line &&
9503 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9504 err = add_matched_line(&width, line, view->ncols - 1, 0,
9505 view->window, view->x, regmatch);
9506 if (err) {
9507 free(line);
9508 return err;
9510 } else {
9511 int skip;
9513 err = format_line(&wline, &width, &skip, line,
9514 view->x, view->ncols, 0, view->x ? 1 : 0);
9515 if (err) {
9516 free(line);
9517 return err;
9519 waddwstr(view->window, &wline[skip]);
9520 free(wline);
9521 wline = NULL;
9523 if (s->lineno == view->hiline) {
9524 while (width++ < view->ncols)
9525 waddch(view->window, ' ');
9526 } else {
9527 if (width < view->ncols)
9528 waddch(view->window, '\n');
9530 if (attr)
9531 wattroff(view->window, attr);
9532 if (++nprinted == 1)
9533 s->first_displayed_line = s->lineno;
9535 free(line);
9536 if (nprinted > 0)
9537 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9538 else
9539 s->last_displayed_line = s->first_displayed_line;
9541 view_border(view);
9543 if (s->eof) {
9544 rc = waddnstr(view->window,
9545 "See the tog(1) manual page for full documentation",
9546 view->ncols - 1);
9547 if (rc == ERR)
9548 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9549 } else {
9550 wmove(view->window, view->nlines - 1, 0);
9551 wclrtoeol(view->window);
9552 wstandout(view->window);
9553 rc = waddnstr(view->window, "scroll down for more...",
9554 view->ncols - 1);
9555 if (rc == ERR)
9556 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9557 if (getcurx(view->window) < view->ncols - 6) {
9558 rc = wprintw(view->window, "[%.0f%%]",
9559 100.00 * s->last_displayed_line / s->nlines);
9560 if (rc == ERR)
9561 return got_error_msg(GOT_ERR_IO, "wprintw");
9563 wstandend(view->window);
9566 return NULL;
9569 static const struct got_error *
9570 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9572 struct tog_help_view_state *s = &view->state.help;
9573 const struct got_error *err = NULL;
9574 char *line = NULL;
9575 ssize_t linelen;
9576 size_t linesz = 0;
9577 int eos, nscroll;
9579 eos = nscroll = view->nlines;
9580 if (view_is_hsplit_top(view))
9581 --eos; /* border */
9583 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9585 switch (ch) {
9586 case '0':
9587 case '$':
9588 case KEY_RIGHT:
9589 case 'l':
9590 case KEY_LEFT:
9591 case 'h':
9592 horizontal_scroll_input(view, ch);
9593 break;
9594 case 'g':
9595 case KEY_HOME:
9596 s->first_displayed_line = 1;
9597 view->count = 0;
9598 break;
9599 case 'G':
9600 case KEY_END:
9601 view->count = 0;
9602 if (s->eof)
9603 break;
9604 s->first_displayed_line = (s->nlines - eos) + 3;
9605 s->eof = 1;
9606 break;
9607 case 'k':
9608 case KEY_UP:
9609 if (s->first_displayed_line > 1)
9610 --s->first_displayed_line;
9611 else
9612 view->count = 0;
9613 break;
9614 case CTRL('u'):
9615 case 'u':
9616 nscroll /= 2;
9617 /* FALL THROUGH */
9618 case KEY_PPAGE:
9619 case CTRL('b'):
9620 case 'b':
9621 if (s->first_displayed_line == 1) {
9622 view->count = 0;
9623 break;
9625 while (--nscroll > 0 && s->first_displayed_line > 1)
9626 s->first_displayed_line--;
9627 break;
9628 case 'j':
9629 case KEY_DOWN:
9630 case CTRL('n'):
9631 if (!s->eof)
9632 ++s->first_displayed_line;
9633 else
9634 view->count = 0;
9635 break;
9636 case CTRL('d'):
9637 case 'd':
9638 nscroll /= 2;
9639 /* FALL THROUGH */
9640 case KEY_NPAGE:
9641 case CTRL('f'):
9642 case 'f':
9643 case ' ':
9644 if (s->eof) {
9645 view->count = 0;
9646 break;
9648 while (!s->eof && --nscroll > 0) {
9649 linelen = getline(&line, &linesz, s->f);
9650 s->first_displayed_line++;
9651 if (linelen == -1) {
9652 if (feof(s->f))
9653 s->eof = 1;
9654 else
9655 err = got_ferror(s->f, GOT_ERR_IO);
9656 break;
9659 free(line);
9660 break;
9661 default:
9662 view->count = 0;
9663 break;
9666 return err;
9669 static const struct got_error *
9670 close_help_view(struct tog_view *view)
9672 struct tog_help_view_state *s = &view->state.help;
9674 free(s->line_offsets);
9675 s->line_offsets = NULL;
9676 if (fclose(s->f) == EOF)
9677 return got_error_from_errno("fclose");
9679 return NULL;
9682 static const struct got_error *
9683 reset_help_view(struct tog_view *view)
9685 struct tog_help_view_state *s = &view->state.help;
9688 if (s->f && fclose(s->f) == EOF)
9689 return got_error_from_errno("fclose");
9691 wclear(view->window);
9692 view->count = 0;
9693 view->x = 0;
9694 s->all = !s->all;
9695 s->first_displayed_line = 1;
9696 s->last_displayed_line = view->nlines;
9697 s->matched_line = 0;
9699 return create_help(s);
9702 static const struct got_error *
9703 open_help_view(struct tog_view *view, struct tog_view *parent)
9705 const struct got_error *err = NULL;
9706 struct tog_help_view_state *s = &view->state.help;
9708 s->type = (enum tog_keymap_type)parent->type;
9709 s->first_displayed_line = 1;
9710 s->last_displayed_line = view->nlines;
9711 s->selected_line = 1;
9713 view->show = show_help_view;
9714 view->input = input_help_view;
9715 view->reset = reset_help_view;
9716 view->close = close_help_view;
9717 view->search_start = search_start_help_view;
9718 view->search_setup = search_setup_help_view;
9719 view->search_next = search_next_view_match;
9721 err = create_help(s);
9722 return err;
9725 static const struct got_error *
9726 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9727 enum tog_view_type request, int y, int x)
9729 const struct got_error *err = NULL;
9731 *new_view = NULL;
9733 switch (request) {
9734 case TOG_VIEW_DIFF:
9735 if (view->type == TOG_VIEW_LOG) {
9736 struct tog_log_view_state *s = &view->state.log;
9738 err = open_diff_view_for_commit(new_view, y, x,
9739 s->selected_entry->commit, s->selected_entry->id,
9740 view, s->repo);
9741 } else
9742 return got_error_msg(GOT_ERR_NOT_IMPL,
9743 "parent/child view pair not supported");
9744 break;
9745 case TOG_VIEW_BLAME:
9746 if (view->type == TOG_VIEW_TREE) {
9747 struct tog_tree_view_state *s = &view->state.tree;
9749 err = blame_tree_entry(new_view, y, x,
9750 s->selected_entry, &s->parents, s->commit_id,
9751 s->repo);
9752 } else
9753 return got_error_msg(GOT_ERR_NOT_IMPL,
9754 "parent/child view pair not supported");
9755 break;
9756 case TOG_VIEW_LOG:
9757 if (view->type == TOG_VIEW_BLAME)
9758 err = log_annotated_line(new_view, y, x,
9759 view->state.blame.repo, view->state.blame.id_to_log);
9760 else if (view->type == TOG_VIEW_TREE)
9761 err = log_selected_tree_entry(new_view, y, x,
9762 &view->state.tree);
9763 else if (view->type == TOG_VIEW_REF)
9764 err = log_ref_entry(new_view, y, x,
9765 view->state.ref.selected_entry,
9766 view->state.ref.repo);
9767 else
9768 return got_error_msg(GOT_ERR_NOT_IMPL,
9769 "parent/child view pair not supported");
9770 break;
9771 case TOG_VIEW_TREE:
9772 if (view->type == TOG_VIEW_LOG)
9773 err = browse_commit_tree(new_view, y, x,
9774 view->state.log.selected_entry,
9775 view->state.log.in_repo_path,
9776 view->state.log.head_ref_name,
9777 view->state.log.repo);
9778 else if (view->type == TOG_VIEW_REF)
9779 err = browse_ref_tree(new_view, y, x,
9780 view->state.ref.selected_entry,
9781 view->state.ref.repo);
9782 else
9783 return got_error_msg(GOT_ERR_NOT_IMPL,
9784 "parent/child view pair not supported");
9785 break;
9786 case TOG_VIEW_REF:
9787 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9788 if (*new_view == NULL)
9789 return got_error_from_errno("view_open");
9790 if (view->type == TOG_VIEW_LOG)
9791 err = open_ref_view(*new_view, view->state.log.repo);
9792 else if (view->type == TOG_VIEW_TREE)
9793 err = open_ref_view(*new_view, view->state.tree.repo);
9794 else
9795 err = got_error_msg(GOT_ERR_NOT_IMPL,
9796 "parent/child view pair not supported");
9797 if (err)
9798 view_close(*new_view);
9799 break;
9800 case TOG_VIEW_HELP:
9801 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9802 if (*new_view == NULL)
9803 return got_error_from_errno("view_open");
9804 err = open_help_view(*new_view, view);
9805 if (err)
9806 view_close(*new_view);
9807 break;
9808 default:
9809 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9812 return err;
9816 * If view was scrolled down to move the selected line into view when opening a
9817 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9819 static void
9820 offset_selection_up(struct tog_view *view)
9822 switch (view->type) {
9823 case TOG_VIEW_BLAME: {
9824 struct tog_blame_view_state *s = &view->state.blame;
9825 if (s->first_displayed_line == 1) {
9826 s->selected_line = MAX(s->selected_line - view->offset,
9827 1);
9828 break;
9830 if (s->first_displayed_line > view->offset)
9831 s->first_displayed_line -= view->offset;
9832 else
9833 s->first_displayed_line = 1;
9834 s->selected_line += view->offset;
9835 break;
9837 case TOG_VIEW_LOG:
9838 log_scroll_up(&view->state.log, view->offset);
9839 view->state.log.selected += view->offset;
9840 break;
9841 case TOG_VIEW_REF:
9842 ref_scroll_up(&view->state.ref, view->offset);
9843 view->state.ref.selected += view->offset;
9844 break;
9845 case TOG_VIEW_TREE:
9846 tree_scroll_up(&view->state.tree, view->offset);
9847 view->state.tree.selected += view->offset;
9848 break;
9849 default:
9850 break;
9853 view->offset = 0;
9857 * If the selected line is in the section of screen covered by the bottom split,
9858 * scroll down offset lines to move it into view and index its new position.
9860 static const struct got_error *
9861 offset_selection_down(struct tog_view *view)
9863 const struct got_error *err = NULL;
9864 const struct got_error *(*scrolld)(struct tog_view *, int);
9865 int *selected = NULL;
9866 int header, offset;
9868 switch (view->type) {
9869 case TOG_VIEW_BLAME: {
9870 struct tog_blame_view_state *s = &view->state.blame;
9871 header = 3;
9872 scrolld = NULL;
9873 if (s->selected_line > view->nlines - header) {
9874 offset = abs(view->nlines - s->selected_line - header);
9875 s->first_displayed_line += offset;
9876 s->selected_line -= offset;
9877 view->offset = offset;
9879 break;
9881 case TOG_VIEW_LOG: {
9882 struct tog_log_view_state *s = &view->state.log;
9883 scrolld = &log_scroll_down;
9884 header = view_is_parent_view(view) ? 3 : 2;
9885 selected = &s->selected;
9886 break;
9888 case TOG_VIEW_REF: {
9889 struct tog_ref_view_state *s = &view->state.ref;
9890 scrolld = &ref_scroll_down;
9891 header = 3;
9892 selected = &s->selected;
9893 break;
9895 case TOG_VIEW_TREE: {
9896 struct tog_tree_view_state *s = &view->state.tree;
9897 scrolld = &tree_scroll_down;
9898 header = 5;
9899 selected = &s->selected;
9900 break;
9902 default:
9903 selected = NULL;
9904 scrolld = NULL;
9905 header = 0;
9906 break;
9909 if (selected && *selected > view->nlines - header) {
9910 offset = abs(view->nlines - *selected - header);
9911 view->offset = offset;
9912 if (scrolld && offset) {
9913 err = scrolld(view, offset);
9914 *selected -= offset;
9918 return err;
9921 static void
9922 list_commands(FILE *fp)
9924 size_t i;
9926 fprintf(fp, "commands:");
9927 for (i = 0; i < nitems(tog_commands); i++) {
9928 const struct tog_cmd *cmd = &tog_commands[i];
9929 fprintf(fp, " %s", cmd->name);
9931 fputc('\n', fp);
9934 __dead static void
9935 usage(int hflag, int status)
9937 FILE *fp = (status == 0) ? stdout : stderr;
9939 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9940 getprogname());
9941 if (hflag) {
9942 fprintf(fp, "lazy usage: %s path\n", getprogname());
9943 list_commands(fp);
9945 exit(status);
9948 static char **
9949 make_argv(int argc, ...)
9951 va_list ap;
9952 char **argv;
9953 int i;
9955 va_start(ap, argc);
9957 argv = calloc(argc, sizeof(char *));
9958 if (argv == NULL)
9959 err(1, "calloc");
9960 for (i = 0; i < argc; i++) {
9961 argv[i] = strdup(va_arg(ap, char *));
9962 if (argv[i] == NULL)
9963 err(1, "strdup");
9966 va_end(ap);
9967 return argv;
9971 * Try to convert 'tog path' into a 'tog log path' command.
9972 * The user could simply have mistyped the command rather than knowingly
9973 * provided a path. So check whether argv[0] can in fact be resolved
9974 * to a path in the HEAD commit and print a special error if not.
9975 * This hack is for mpi@ <3
9977 static const struct got_error *
9978 tog_log_with_path(int argc, char *argv[])
9980 const struct got_error *error = NULL, *close_err;
9981 const struct tog_cmd *cmd = NULL;
9982 struct got_repository *repo = NULL;
9983 struct got_worktree *worktree = NULL;
9984 struct got_object_id *commit_id = NULL, *id = NULL;
9985 struct got_commit_object *commit = NULL;
9986 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9987 char *commit_id_str = NULL, **cmd_argv = NULL;
9988 int *pack_fds = NULL;
9990 cwd = getcwd(NULL, 0);
9991 if (cwd == NULL)
9992 return got_error_from_errno("getcwd");
9994 error = got_repo_pack_fds_open(&pack_fds);
9995 if (error != NULL)
9996 goto done;
9998 error = got_worktree_open(&worktree, cwd, NULL);
9999 if (error && error->code != GOT_ERR_NOT_WORKTREE)
10000 goto done;
10002 if (worktree)
10003 repo_path = strdup(got_worktree_get_repo_path(worktree));
10004 else
10005 repo_path = strdup(cwd);
10006 if (repo_path == NULL) {
10007 error = got_error_from_errno("strdup");
10008 goto done;
10011 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
10012 if (error != NULL)
10013 goto done;
10015 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
10016 repo, worktree);
10017 if (error)
10018 goto done;
10020 error = tog_load_refs(repo, 0);
10021 if (error)
10022 goto done;
10023 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
10024 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
10025 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
10026 if (error)
10027 goto done;
10029 if (worktree) {
10030 got_worktree_close(worktree);
10031 worktree = NULL;
10034 error = got_object_open_as_commit(&commit, repo, commit_id);
10035 if (error)
10036 goto done;
10038 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
10039 if (error) {
10040 if (error->code != GOT_ERR_NO_TREE_ENTRY)
10041 goto done;
10042 fprintf(stderr, "%s: '%s' is no known command or path\n",
10043 getprogname(), argv[0]);
10044 usage(1, 1);
10045 /* not reached */
10048 error = got_object_id_str(&commit_id_str, commit_id);
10049 if (error)
10050 goto done;
10052 cmd = &tog_commands[0]; /* log */
10053 argc = 4;
10054 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
10055 error = cmd->cmd_main(argc, cmd_argv);
10056 done:
10057 if (repo) {
10058 close_err = got_repo_close(repo);
10059 if (error == NULL)
10060 error = close_err;
10062 if (commit)
10063 got_object_commit_close(commit);
10064 if (worktree)
10065 got_worktree_close(worktree);
10066 if (pack_fds) {
10067 const struct got_error *pack_err =
10068 got_repo_pack_fds_close(pack_fds);
10069 if (error == NULL)
10070 error = pack_err;
10072 free(id);
10073 free(commit_id_str);
10074 free(commit_id);
10075 free(cwd);
10076 free(repo_path);
10077 free(in_repo_path);
10078 if (cmd_argv) {
10079 int i;
10080 for (i = 0; i < argc; i++)
10081 free(cmd_argv[i]);
10082 free(cmd_argv);
10084 tog_free_refs();
10085 return error;
10088 int
10089 main(int argc, char *argv[])
10091 const struct got_error *io_err, *error = NULL;
10092 const struct tog_cmd *cmd = NULL;
10093 int ch, hflag = 0, Vflag = 0;
10094 char **cmd_argv = NULL;
10095 static const struct option longopts[] = {
10096 { "version", no_argument, NULL, 'V' },
10097 { NULL, 0, NULL, 0}
10099 char *diff_algo_str = NULL;
10100 const char *test_script_path;
10102 setlocale(LC_CTYPE, "");
10105 * Override default signal handlers before starting ncurses.
10106 * This should prevent ncurses from installing its own
10107 * broken cleanup() signal handler.
10109 signal(SIGWINCH, tog_sigwinch);
10110 signal(SIGPIPE, tog_sigpipe);
10111 signal(SIGCONT, tog_sigcont);
10112 signal(SIGINT, tog_sigint);
10113 signal(SIGTERM, tog_sigterm);
10116 * Test mode init must happen before pledge() because "tty" will
10117 * not allow TTY-related ioctls to occur via regular files.
10119 test_script_path = getenv("TOG_TEST_SCRIPT");
10120 if (test_script_path != NULL) {
10121 error = init_mock_term(test_script_path);
10122 if (error) {
10123 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10124 return 1;
10126 } else if (!isatty(STDIN_FILENO))
10127 errx(1, "standard input is not a tty");
10129 #if !defined(PROFILE)
10130 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
10131 NULL) == -1)
10132 err(1, "pledge");
10133 #endif
10135 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
10136 switch (ch) {
10137 case 'h':
10138 hflag = 1;
10139 break;
10140 case 'V':
10141 Vflag = 1;
10142 break;
10143 default:
10144 usage(hflag, 1);
10145 /* NOTREACHED */
10149 argc -= optind;
10150 argv += optind;
10151 optind = 1;
10152 optreset = 1;
10154 if (Vflag) {
10155 got_version_print_str();
10156 return 0;
10159 if (argc == 0) {
10160 if (hflag)
10161 usage(hflag, 0);
10162 /* Build an argument vector which runs a default command. */
10163 cmd = &tog_commands[0];
10164 argc = 1;
10165 cmd_argv = make_argv(argc, cmd->name);
10166 } else {
10167 size_t i;
10169 /* Did the user specify a command? */
10170 for (i = 0; i < nitems(tog_commands); i++) {
10171 if (strncmp(tog_commands[i].name, argv[0],
10172 strlen(argv[0])) == 0) {
10173 cmd = &tog_commands[i];
10174 break;
10179 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
10180 if (diff_algo_str) {
10181 if (strcasecmp(diff_algo_str, "patience") == 0)
10182 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
10183 if (strcasecmp(diff_algo_str, "myers") == 0)
10184 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
10187 tog_base_commit.idx = -1;
10188 tog_base_commit.marker = GOT_WORKTREE_STATE_UNKNOWN;
10190 if (cmd == NULL) {
10191 if (argc != 1)
10192 usage(0, 1);
10193 /* No command specified; try log with a path */
10194 error = tog_log_with_path(argc, argv);
10195 } else {
10196 if (hflag)
10197 cmd->cmd_usage();
10198 else
10199 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
10202 if (using_mock_io) {
10203 io_err = tog_io_close();
10204 if (error == NULL)
10205 error = io_err;
10207 endwin();
10208 if (cmd_argv) {
10209 int i;
10210 for (i = 0; i < argc; i++)
10211 free(cmd_argv[i]);
10212 free(cmd_argv);
10215 if (error && error->code != GOT_ERR_CANCELLED &&
10216 error->code != GOT_ERR_EOF &&
10217 error->code != GOT_ERR_PRIVSEP_EXIT &&
10218 error->code != GOT_ERR_PRIVSEP_PIPE &&
10219 !(error->code == GOT_ERR_ERRNO && errno == EINTR)) {
10220 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10221 return 1;
10223 return 0;