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 int wait_for_ui;
632 } tog_io;
633 static int using_mock_io;
635 #define TOG_KEY_SCRDUMP SHRT_MIN
637 /*
638 * We implement two types of views: parent views and child views.
640 * The 'Tab' key switches focus between a parent view and its child view.
641 * Child views are shown side-by-side to their parent view, provided
642 * there is enough screen estate.
644 * When a new view is opened from within a parent view, this new view
645 * becomes a child view of the parent view, replacing any existing child.
647 * When a new view is opened from within a child view, this new view
648 * becomes a parent view which will obscure the views below until the
649 * user quits the new parent view by typing 'q'.
651 * This list of views contains parent views only.
652 * Child views are only pointed to by their parent view.
653 */
654 TAILQ_HEAD(tog_view_list_head, tog_view);
656 struct tog_view {
657 TAILQ_ENTRY(tog_view) entry;
658 WINDOW *window;
659 PANEL *panel;
660 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
661 int resized_y, resized_x; /* begin_y/x based on user resizing */
662 int maxx, x; /* max column and current start column */
663 int lines, cols; /* copies of LINES and COLS */
664 int nscrolled, offset; /* lines scrolled and hsplit line offset */
665 int gline, hiline; /* navigate to and highlight this nG line */
666 int ch, count; /* current keymap and count prefix */
667 int resized; /* set when in a resize event */
668 int focussed; /* Only set on one parent or child view at a time. */
669 int dying;
670 struct tog_view *parent;
671 struct tog_view *child;
673 /*
674 * This flag is initially set on parent views when a new child view
675 * is created. It gets toggled when the 'Tab' key switches focus
676 * between parent and child.
677 * The flag indicates whether focus should be passed on to our child
678 * view if this parent view gets picked for focus after another parent
679 * view was closed. This prevents child views from losing focus in such
680 * situations.
681 */
682 int focus_child;
684 enum tog_view_mode mode;
685 /* type-specific state */
686 enum tog_view_type type;
687 union {
688 struct tog_diff_view_state diff;
689 struct tog_log_view_state log;
690 struct tog_blame_view_state blame;
691 struct tog_tree_view_state tree;
692 struct tog_ref_view_state ref;
693 struct tog_help_view_state help;
694 } state;
696 const struct got_error *(*show)(struct tog_view *);
697 const struct got_error *(*input)(struct tog_view **,
698 struct tog_view *, int);
699 const struct got_error *(*reset)(struct tog_view *);
700 const struct got_error *(*resize)(struct tog_view *, int);
701 const struct got_error *(*close)(struct tog_view *);
703 const struct got_error *(*search_start)(struct tog_view *);
704 const struct got_error *(*search_next)(struct tog_view *);
705 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
706 int **, int **, int **, int **);
707 int search_started;
708 int searching;
709 #define TOG_SEARCH_FORWARD 1
710 #define TOG_SEARCH_BACKWARD 2
711 int search_next_done;
712 #define TOG_SEARCH_HAVE_MORE 1
713 #define TOG_SEARCH_NO_MORE 2
714 #define TOG_SEARCH_HAVE_NONE 3
715 regex_t regex;
716 regmatch_t regmatch;
717 const char *action;
718 };
720 static const struct got_error *open_diff_view(struct tog_view *,
721 struct got_object_id *, struct got_object_id *,
722 const char *, const char *, int, int, int, struct tog_view *,
723 struct got_repository *);
724 static const struct got_error *show_diff_view(struct tog_view *);
725 static const struct got_error *input_diff_view(struct tog_view **,
726 struct tog_view *, int);
727 static const struct got_error *reset_diff_view(struct tog_view *);
728 static const struct got_error* close_diff_view(struct tog_view *);
729 static const struct got_error *search_start_diff_view(struct tog_view *);
730 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
731 size_t *, int **, int **, int **, int **);
732 static const struct got_error *search_next_view_match(struct tog_view *);
734 static const struct got_error *open_log_view(struct tog_view *,
735 struct got_object_id *, struct got_repository *,
736 const char *, const char *, int, struct got_worktree *);
737 static const struct got_error * show_log_view(struct tog_view *);
738 static const struct got_error *input_log_view(struct tog_view **,
739 struct tog_view *, int);
740 static const struct got_error *resize_log_view(struct tog_view *, int);
741 static const struct got_error *close_log_view(struct tog_view *);
742 static const struct got_error *search_start_log_view(struct tog_view *);
743 static const struct got_error *search_next_log_view(struct tog_view *);
745 static const struct got_error *open_blame_view(struct tog_view *, char *,
746 struct got_object_id *, struct got_repository *);
747 static const struct got_error *show_blame_view(struct tog_view *);
748 static const struct got_error *input_blame_view(struct tog_view **,
749 struct tog_view *, int);
750 static const struct got_error *reset_blame_view(struct tog_view *);
751 static const struct got_error *close_blame_view(struct tog_view *);
752 static const struct got_error *search_start_blame_view(struct tog_view *);
753 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
754 size_t *, int **, int **, int **, int **);
756 static const struct got_error *open_tree_view(struct tog_view *,
757 struct got_object_id *, const char *, struct got_repository *);
758 static const struct got_error *show_tree_view(struct tog_view *);
759 static const struct got_error *input_tree_view(struct tog_view **,
760 struct tog_view *, int);
761 static const struct got_error *close_tree_view(struct tog_view *);
762 static const struct got_error *search_start_tree_view(struct tog_view *);
763 static const struct got_error *search_next_tree_view(struct tog_view *);
765 static const struct got_error *open_ref_view(struct tog_view *,
766 struct got_repository *);
767 static const struct got_error *show_ref_view(struct tog_view *);
768 static const struct got_error *input_ref_view(struct tog_view **,
769 struct tog_view *, int);
770 static const struct got_error *close_ref_view(struct tog_view *);
771 static const struct got_error *search_start_ref_view(struct tog_view *);
772 static const struct got_error *search_next_ref_view(struct tog_view *);
774 static const struct got_error *open_help_view(struct tog_view *,
775 struct tog_view *);
776 static const struct got_error *show_help_view(struct tog_view *);
777 static const struct got_error *input_help_view(struct tog_view **,
778 struct tog_view *, int);
779 static const struct got_error *reset_help_view(struct tog_view *);
780 static const struct got_error* close_help_view(struct tog_view *);
781 static const struct got_error *search_start_help_view(struct tog_view *);
782 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
783 size_t *, int **, int **, int **, int **);
785 static volatile sig_atomic_t tog_sigwinch_received;
786 static volatile sig_atomic_t tog_sigpipe_received;
787 static volatile sig_atomic_t tog_sigcont_received;
788 static volatile sig_atomic_t tog_sigint_received;
789 static volatile sig_atomic_t tog_sigterm_received;
791 static void
792 tog_sigwinch(int signo)
794 tog_sigwinch_received = 1;
797 static void
798 tog_sigpipe(int signo)
800 tog_sigpipe_received = 1;
803 static void
804 tog_sigcont(int signo)
806 tog_sigcont_received = 1;
809 static void
810 tog_sigint(int signo)
812 tog_sigint_received = 1;
815 static void
816 tog_sigterm(int signo)
818 tog_sigterm_received = 1;
821 static int
822 tog_fatal_signal_received(void)
824 return (tog_sigpipe_received ||
825 tog_sigint_received || tog_sigterm_received);
828 static const struct got_error *
829 view_close(struct tog_view *view)
831 const struct got_error *err = NULL, *child_err = NULL;
833 if (view->child) {
834 child_err = view_close(view->child);
835 view->child = NULL;
837 if (view->close)
838 err = view->close(view);
839 if (view->panel)
840 del_panel(view->panel);
841 if (view->window)
842 delwin(view->window);
843 free(view);
844 return err ? err : child_err;
847 static struct tog_view *
848 view_open(int nlines, int ncols, int begin_y, int begin_x,
849 enum tog_view_type type)
851 struct tog_view *view = calloc(1, sizeof(*view));
853 if (view == NULL)
854 return NULL;
856 view->type = type;
857 view->lines = LINES;
858 view->cols = COLS;
859 view->nlines = nlines ? nlines : LINES - begin_y;
860 view->ncols = ncols ? ncols : COLS - begin_x;
861 view->begin_y = begin_y;
862 view->begin_x = begin_x;
863 view->window = newwin(nlines, ncols, begin_y, begin_x);
864 if (view->window == NULL) {
865 view_close(view);
866 return NULL;
868 view->panel = new_panel(view->window);
869 if (view->panel == NULL ||
870 set_panel_userptr(view->panel, view) != OK) {
871 view_close(view);
872 return NULL;
875 keypad(view->window, TRUE);
876 return view;
879 static int
880 view_split_begin_x(int begin_x)
882 if (begin_x > 0 || COLS < 120)
883 return 0;
884 return (COLS - MAX(COLS / 2, 80));
887 /* XXX Stub till we decide what to do. */
888 static int
889 view_split_begin_y(int lines)
891 return lines * HSPLIT_SCALE;
894 static const struct got_error *view_resize(struct tog_view *);
896 static const struct got_error *
897 view_splitscreen(struct tog_view *view)
899 const struct got_error *err = NULL;
901 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
902 if (view->resized_y && view->resized_y < view->lines)
903 view->begin_y = view->resized_y;
904 else
905 view->begin_y = view_split_begin_y(view->nlines);
906 view->begin_x = 0;
907 } else if (!view->resized) {
908 if (view->resized_x && view->resized_x < view->cols - 1 &&
909 view->cols > 119)
910 view->begin_x = view->resized_x;
911 else
912 view->begin_x = view_split_begin_x(0);
913 view->begin_y = 0;
915 view->nlines = LINES - view->begin_y;
916 view->ncols = COLS - view->begin_x;
917 view->lines = LINES;
918 view->cols = COLS;
919 err = view_resize(view);
920 if (err)
921 return err;
923 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
924 view->parent->nlines = view->begin_y;
926 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
927 return got_error_from_errno("mvwin");
929 return NULL;
932 static const struct got_error *
933 view_fullscreen(struct tog_view *view)
935 const struct got_error *err = NULL;
937 view->begin_x = 0;
938 view->begin_y = view->resized ? view->begin_y : 0;
939 view->nlines = view->resized ? view->nlines : LINES;
940 view->ncols = COLS;
941 view->lines = LINES;
942 view->cols = COLS;
943 err = view_resize(view);
944 if (err)
945 return err;
947 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
948 return got_error_from_errno("mvwin");
950 return NULL;
953 static int
954 view_is_parent_view(struct tog_view *view)
956 return view->parent == NULL;
959 static int
960 view_is_splitscreen(struct tog_view *view)
962 return view->begin_x > 0 || view->begin_y > 0;
965 static int
966 view_is_fullscreen(struct tog_view *view)
968 return view->nlines == LINES && view->ncols == COLS;
971 static int
972 view_is_hsplit_top(struct tog_view *view)
974 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
975 view_is_splitscreen(view->child);
978 static void
979 view_border(struct tog_view *view)
981 PANEL *panel;
982 const struct tog_view *view_above;
984 if (view->parent)
985 return view_border(view->parent);
987 panel = panel_above(view->panel);
988 if (panel == NULL)
989 return;
991 view_above = panel_userptr(panel);
992 if (view->mode == TOG_VIEW_SPLIT_HRZN)
993 mvwhline(view->window, view_above->begin_y - 1,
994 view->begin_x, ACS_HLINE, view->ncols);
995 else
996 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
997 ACS_VLINE, view->nlines);
1000 static const struct got_error *view_init_hsplit(struct tog_view *, int);
1001 static const struct got_error *request_log_commits(struct tog_view *);
1002 static const struct got_error *offset_selection_down(struct tog_view *);
1003 static void offset_selection_up(struct tog_view *);
1004 static void view_get_split(struct tog_view *, int *, int *);
1006 static const struct got_error *
1007 view_resize(struct tog_view *view)
1009 const struct got_error *err = NULL;
1010 int dif, nlines, ncols;
1012 dif = LINES - view->lines; /* line difference */
1014 if (view->lines > LINES)
1015 nlines = view->nlines - (view->lines - LINES);
1016 else
1017 nlines = view->nlines + (LINES - view->lines);
1018 if (view->cols > COLS)
1019 ncols = view->ncols - (view->cols - COLS);
1020 else
1021 ncols = view->ncols + (COLS - view->cols);
1023 if (view->child) {
1024 int hs = view->child->begin_y;
1026 if (!view_is_fullscreen(view))
1027 view->child->begin_x = view_split_begin_x(view->begin_x);
1028 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1029 view->child->begin_x == 0) {
1030 ncols = COLS;
1032 view_fullscreen(view->child);
1033 if (view->child->focussed)
1034 show_panel(view->child->panel);
1035 else
1036 show_panel(view->panel);
1037 } else {
1038 ncols = view->child->begin_x;
1040 view_splitscreen(view->child);
1041 show_panel(view->child->panel);
1044 * XXX This is ugly and needs to be moved into the above
1045 * logic but "works" for now and my attempts at moving it
1046 * break either 'tab' or 'F' key maps in horizontal splits.
1048 if (hs) {
1049 err = view_splitscreen(view->child);
1050 if (err)
1051 return err;
1052 if (dif < 0) { /* top split decreased */
1053 err = offset_selection_down(view);
1054 if (err)
1055 return err;
1057 view_border(view);
1058 update_panels();
1059 doupdate();
1060 show_panel(view->child->panel);
1061 nlines = view->nlines;
1063 } else if (view->parent == NULL)
1064 ncols = COLS;
1066 if (view->resize && dif > 0) {
1067 err = view->resize(view, dif);
1068 if (err)
1069 return err;
1072 if (wresize(view->window, nlines, ncols) == ERR)
1073 return got_error_from_errno("wresize");
1074 if (replace_panel(view->panel, view->window) == ERR)
1075 return got_error_from_errno("replace_panel");
1076 wclear(view->window);
1078 view->nlines = nlines;
1079 view->ncols = ncols;
1080 view->lines = LINES;
1081 view->cols = COLS;
1083 return NULL;
1086 static const struct got_error *
1087 resize_log_view(struct tog_view *view, int increase)
1089 struct tog_log_view_state *s = &view->state.log;
1090 const struct got_error *err = NULL;
1091 int n = 0;
1093 if (s->selected_entry)
1094 n = s->selected_entry->idx + view->lines - s->selected;
1097 * Request commits to account for the increased
1098 * height so we have enough to populate the view.
1100 if (s->commits->ncommits < n) {
1101 view->nscrolled = n - s->commits->ncommits + increase + 1;
1102 err = request_log_commits(view);
1105 return err;
1108 static void
1109 view_adjust_offset(struct tog_view *view, int n)
1111 if (n == 0)
1112 return;
1114 if (view->parent && view->parent->offset) {
1115 if (view->parent->offset + n >= 0)
1116 view->parent->offset += n;
1117 else
1118 view->parent->offset = 0;
1119 } else if (view->offset) {
1120 if (view->offset - n >= 0)
1121 view->offset -= n;
1122 else
1123 view->offset = 0;
1127 static const struct got_error *
1128 view_resize_split(struct tog_view *view, int resize)
1130 const struct got_error *err = NULL;
1131 struct tog_view *v = NULL;
1133 if (view->parent)
1134 v = view->parent;
1135 else
1136 v = view;
1138 if (!v->child || !view_is_splitscreen(v->child))
1139 return NULL;
1141 v->resized = v->child->resized = resize; /* lock for resize event */
1143 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1144 if (v->child->resized_y)
1145 v->child->begin_y = v->child->resized_y;
1146 if (view->parent)
1147 v->child->begin_y -= resize;
1148 else
1149 v->child->begin_y += resize;
1150 if (v->child->begin_y < 3) {
1151 view->count = 0;
1152 v->child->begin_y = 3;
1153 } else if (v->child->begin_y > LINES - 1) {
1154 view->count = 0;
1155 v->child->begin_y = LINES - 1;
1157 v->ncols = COLS;
1158 v->child->ncols = COLS;
1159 view_adjust_offset(view, resize);
1160 err = view_init_hsplit(v, v->child->begin_y);
1161 if (err)
1162 return err;
1163 v->child->resized_y = v->child->begin_y;
1164 } else {
1165 if (v->child->resized_x)
1166 v->child->begin_x = v->child->resized_x;
1167 if (view->parent)
1168 v->child->begin_x -= resize;
1169 else
1170 v->child->begin_x += resize;
1171 if (v->child->begin_x < 11) {
1172 view->count = 0;
1173 v->child->begin_x = 11;
1174 } else if (v->child->begin_x > COLS - 1) {
1175 view->count = 0;
1176 v->child->begin_x = COLS - 1;
1178 v->child->resized_x = v->child->begin_x;
1181 v->child->mode = v->mode;
1182 v->child->nlines = v->lines - v->child->begin_y;
1183 v->child->ncols = v->cols - v->child->begin_x;
1184 v->focus_child = 1;
1186 err = view_fullscreen(v);
1187 if (err)
1188 return err;
1189 err = view_splitscreen(v->child);
1190 if (err)
1191 return err;
1193 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1194 err = offset_selection_down(v->child);
1195 if (err)
1196 return err;
1199 if (v->resize)
1200 err = v->resize(v, 0);
1201 else if (v->child->resize)
1202 err = v->child->resize(v->child, 0);
1204 v->resized = v->child->resized = 0;
1206 return err;
1209 static void
1210 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1212 struct tog_view *v = src->child ? src->child : src;
1214 dst->resized_x = v->resized_x;
1215 dst->resized_y = v->resized_y;
1218 static const struct got_error *
1219 view_close_child(struct tog_view *view)
1221 const struct got_error *err = NULL;
1223 if (view->child == NULL)
1224 return NULL;
1226 err = view_close(view->child);
1227 view->child = NULL;
1228 return err;
1231 static const struct got_error *
1232 view_set_child(struct tog_view *view, struct tog_view *child)
1234 const struct got_error *err = NULL;
1236 view->child = child;
1237 child->parent = view;
1239 err = view_resize(view);
1240 if (err)
1241 return err;
1243 if (view->child->resized_x || view->child->resized_y)
1244 err = view_resize_split(view, 0);
1246 return err;
1249 static const struct got_error *view_dispatch_request(struct tog_view **,
1250 struct tog_view *, enum tog_view_type, int, int);
1252 static const struct got_error *
1253 view_request_new(struct tog_view **requested, struct tog_view *view,
1254 enum tog_view_type request)
1256 struct tog_view *new_view = NULL;
1257 const struct got_error *err;
1258 int y = 0, x = 0;
1260 *requested = NULL;
1262 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1263 view_get_split(view, &y, &x);
1265 err = view_dispatch_request(&new_view, view, request, y, x);
1266 if (err)
1267 return err;
1269 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1270 request != TOG_VIEW_HELP) {
1271 err = view_init_hsplit(view, y);
1272 if (err)
1273 return err;
1276 view->focussed = 0;
1277 new_view->focussed = 1;
1278 new_view->mode = view->mode;
1279 new_view->nlines = request == TOG_VIEW_HELP ?
1280 view->lines : view->lines - y;
1282 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1283 view_transfer_size(new_view, view);
1284 err = view_close_child(view);
1285 if (err)
1286 return err;
1287 err = view_set_child(view, new_view);
1288 if (err)
1289 return err;
1290 view->focus_child = 1;
1291 } else
1292 *requested = new_view;
1294 return NULL;
1297 static void
1298 tog_resizeterm(void)
1300 int cols, lines;
1301 struct winsize size;
1303 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1304 cols = 80; /* Default */
1305 lines = 24;
1306 } else {
1307 cols = size.ws_col;
1308 lines = size.ws_row;
1310 resize_term(lines, cols);
1313 static const struct got_error *
1314 view_search_start(struct tog_view *view, int fast_refresh)
1316 const struct got_error *err = NULL;
1317 struct tog_view *v = view;
1318 char pattern[1024];
1319 int ret;
1321 if (view->search_started) {
1322 regfree(&view->regex);
1323 view->searching = 0;
1324 memset(&view->regmatch, 0, sizeof(view->regmatch));
1326 view->search_started = 0;
1328 if (view->nlines < 1)
1329 return NULL;
1331 if (view_is_hsplit_top(view))
1332 v = view->child;
1333 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1334 v = view->parent;
1336 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1337 wclrtoeol(v->window);
1339 nodelay(v->window, FALSE); /* block for search term input */
1340 nocbreak();
1341 echo();
1342 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1343 wrefresh(v->window);
1344 cbreak();
1345 noecho();
1346 nodelay(v->window, TRUE);
1347 if (!fast_refresh && !using_mock_io)
1348 halfdelay(10);
1349 if (ret == ERR)
1350 return NULL;
1352 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1353 err = view->search_start(view);
1354 if (err) {
1355 regfree(&view->regex);
1356 return err;
1358 view->search_started = 1;
1359 view->searching = TOG_SEARCH_FORWARD;
1360 view->search_next_done = 0;
1361 view->search_next(view);
1364 return NULL;
1367 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1368 static const struct got_error *
1369 switch_split(struct tog_view *view)
1371 const struct got_error *err = NULL;
1372 struct tog_view *v = NULL;
1374 if (view->parent)
1375 v = view->parent;
1376 else
1377 v = view;
1379 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1380 v->mode = TOG_VIEW_SPLIT_VERT;
1381 else
1382 v->mode = TOG_VIEW_SPLIT_HRZN;
1384 if (!v->child)
1385 return NULL;
1386 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1387 v->mode = TOG_VIEW_SPLIT_NONE;
1389 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1390 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1391 v->child->begin_y = v->child->resized_y;
1392 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1393 v->child->begin_x = v->child->resized_x;
1396 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1397 v->ncols = COLS;
1398 v->child->ncols = COLS;
1399 v->child->nscrolled = LINES - v->child->nlines;
1401 err = view_init_hsplit(v, v->child->begin_y);
1402 if (err)
1403 return err;
1405 v->child->mode = v->mode;
1406 v->child->nlines = v->lines - v->child->begin_y;
1407 v->focus_child = 1;
1409 err = view_fullscreen(v);
1410 if (err)
1411 return err;
1412 err = view_splitscreen(v->child);
1413 if (err)
1414 return err;
1416 if (v->mode == TOG_VIEW_SPLIT_NONE)
1417 v->mode = TOG_VIEW_SPLIT_VERT;
1418 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1419 err = offset_selection_down(v);
1420 if (err)
1421 return err;
1422 err = offset_selection_down(v->child);
1423 if (err)
1424 return err;
1425 } else {
1426 offset_selection_up(v);
1427 offset_selection_up(v->child);
1429 if (v->resize)
1430 err = v->resize(v, 0);
1431 else if (v->child->resize)
1432 err = v->child->resize(v->child, 0);
1434 return err;
1438 * Strip trailing whitespace from str starting at byte *n;
1439 * if *n < 0, use strlen(str). Return new str length in *n.
1441 static void
1442 strip_trailing_ws(char *str, int *n)
1444 size_t x = *n;
1446 if (str == NULL || *str == '\0')
1447 return;
1449 if (x < 0)
1450 x = strlen(str);
1452 while (x-- > 0 && isspace((unsigned char)str[x]))
1453 str[x] = '\0';
1455 *n = x + 1;
1459 * Extract visible substring of line y from the curses screen
1460 * and strip trailing whitespace. If vline is set, overwrite
1461 * line[vline] with '|' because the ACS_VLINE character is
1462 * written out as 'x'. Write the line to file f.
1464 static const struct got_error *
1465 view_write_line(FILE *f, int y, int vline)
1467 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1468 int r, w;
1470 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1471 if (r == ERR)
1472 return got_error_fmt(GOT_ERR_RANGE,
1473 "failed to extract line %d", y);
1476 * In some views, lines are padded with blanks to COLS width.
1477 * Strip them so we can diff without the -b flag when testing.
1479 strip_trailing_ws(line, &r);
1481 if (vline > 0)
1482 line[vline] = '|';
1484 w = fprintf(f, "%s\n", line);
1485 if (w != r + 1) /* \n */
1486 return got_ferror(f, GOT_ERR_IO);
1488 return NULL;
1492 * Capture the visible curses screen by writing each line to the
1493 * file at the path set via the TOG_SCR_DUMP environment variable.
1495 static const struct got_error *
1496 screendump(struct tog_view *view)
1498 const struct got_error *err;
1499 int i;
1501 err = got_opentemp_truncate(tog_io.sdump);
1502 if (err)
1503 return err;
1505 if ((view->child && view->child->begin_x) ||
1506 (view->parent && view->begin_x)) {
1507 int ncols = view->child ? view->ncols : view->parent->ncols;
1509 /* vertical splitscreen */
1510 for (i = 0; i < view->nlines; ++i) {
1511 err = view_write_line(tog_io.sdump, i, ncols - 1);
1512 if (err)
1513 goto done;
1515 } else {
1516 int hline = 0;
1518 /* fullscreen or horizontal splitscreen */
1519 if ((view->child && view->child->begin_y) ||
1520 (view->parent && view->begin_y)) /* hsplit */
1521 hline = view->child ?
1522 view->child->begin_y : view->begin_y;
1524 for (i = 0; i < view->lines; i++) {
1525 if (hline && i == hline - 1) {
1526 int c;
1528 /* ACS_HLINE writes out as 'q', overwrite it */
1529 for (c = 0; c < view->cols; ++c)
1530 fputc('-', tog_io.sdump);
1531 fputc('\n', tog_io.sdump);
1532 continue;
1535 err = view_write_line(tog_io.sdump, i, 0);
1536 if (err)
1537 goto done;
1541 done:
1542 return err;
1546 * Compute view->count from numeric input. Assign total to view->count and
1547 * return first non-numeric key entered.
1549 static int
1550 get_compound_key(struct tog_view *view, int c)
1552 struct tog_view *v = view;
1553 int x, n = 0;
1555 if (view_is_hsplit_top(view))
1556 v = view->child;
1557 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1558 v = view->parent;
1560 view->count = 0;
1561 cbreak(); /* block for input */
1562 nodelay(view->window, FALSE);
1563 wmove(v->window, v->nlines - 1, 0);
1564 wclrtoeol(v->window);
1565 waddch(v->window, ':');
1567 do {
1568 x = getcurx(v->window);
1569 if (x != ERR && x < view->ncols) {
1570 waddch(v->window, c);
1571 wrefresh(v->window);
1575 * Don't overflow. Max valid request should be the greatest
1576 * between the longest and total lines; cap at 10 million.
1578 if (n >= 9999999)
1579 n = 9999999;
1580 else
1581 n = n * 10 + (c - '0');
1582 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1584 if (c == 'G' || c == 'g') { /* nG key map */
1585 view->gline = view->hiline = n;
1586 n = 0;
1587 c = 0;
1590 /* Massage excessive or inapplicable values at the input handler. */
1591 view->count = n;
1593 return c;
1596 static void
1597 action_report(struct tog_view *view)
1599 struct tog_view *v = view;
1601 if (view_is_hsplit_top(view))
1602 v = view->child;
1603 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1604 v = view->parent;
1606 wmove(v->window, v->nlines - 1, 0);
1607 wclrtoeol(v->window);
1608 wprintw(v->window, ":%s", view->action);
1609 wrefresh(v->window);
1612 * Clear action status report. Only clear in blame view
1613 * once annotating is complete, otherwise it's too fast.
1615 if (view->type == TOG_VIEW_BLAME) {
1616 if (view->state.blame.blame_complete)
1617 view->action = NULL;
1618 } else
1619 view->action = NULL;
1623 * Read the next line from the test script and assign
1624 * key instruction to *ch. If at EOF, set the *done flag.
1626 static const struct got_error *
1627 tog_read_script_key(FILE *script, struct tog_view *view, int *ch, int *done)
1629 const struct got_error *err = NULL;
1630 char *line = NULL;
1631 size_t linesz = 0;
1633 if (view->count && --view->count) {
1634 *ch = view->ch;
1635 return NULL;
1636 } else
1637 *ch = -1;
1639 if (getline(&line, &linesz, script) == -1) {
1640 if (feof(script)) {
1641 *done = 1;
1642 goto done;
1643 } else {
1644 err = got_ferror(script, GOT_ERR_IO);
1645 goto done;
1649 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1650 tog_io.wait_for_ui = 1;
1651 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1652 *ch = KEY_ENTER;
1653 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1654 *ch = KEY_RIGHT;
1655 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1656 *ch = KEY_LEFT;
1657 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1658 *ch = KEY_DOWN;
1659 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1660 *ch = KEY_UP;
1661 else if (strncasecmp(line, "TAB", 3) == 0)
1662 *ch = '\t';
1663 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1664 *ch = TOG_KEY_SCRDUMP;
1665 else if (isdigit((unsigned char)*line)) {
1666 char *t = line;
1668 while (isdigit((unsigned char)*t))
1669 ++t;
1670 view->ch = *ch = *t;
1671 *t = '\0';
1672 /* ignore error, view->count is 0 if instruction is invalid */
1673 view->count = strtonum(line, 0, INT_MAX, NULL);
1674 } else
1675 *ch = *line;
1677 done:
1678 free(line);
1679 return err;
1682 static const struct got_error *
1683 view_input(struct tog_view **new, int *done, struct tog_view *view,
1684 struct tog_view_list_head *views, int fast_refresh)
1686 const struct got_error *err = NULL;
1687 struct tog_view *v;
1688 int ch, errcode;
1690 *new = NULL;
1692 if (view->action)
1693 action_report(view);
1695 /* Clear "no matches" indicator. */
1696 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1697 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1698 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1699 view->count = 0;
1702 if (view->searching && !view->search_next_done) {
1703 errcode = pthread_mutex_unlock(&tog_mutex);
1704 if (errcode)
1705 return got_error_set_errno(errcode,
1706 "pthread_mutex_unlock");
1707 sched_yield();
1708 errcode = pthread_mutex_lock(&tog_mutex);
1709 if (errcode)
1710 return got_error_set_errno(errcode,
1711 "pthread_mutex_lock");
1712 view->search_next(view);
1713 return NULL;
1716 /* Allow threads to make progress while we are waiting for input. */
1717 errcode = pthread_mutex_unlock(&tog_mutex);
1718 if (errcode)
1719 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1721 if (using_mock_io) {
1722 err = tog_read_script_key(tog_io.f, view, &ch, done);
1723 if (err) {
1724 errcode = pthread_mutex_lock(&tog_mutex);
1725 return err;
1727 } else if (view->count && --view->count) {
1728 cbreak();
1729 nodelay(view->window, TRUE);
1730 ch = wgetch(view->window);
1731 /* let C-g or backspace abort unfinished count */
1732 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1733 view->count = 0;
1734 else
1735 ch = view->ch;
1736 } else {
1737 ch = wgetch(view->window);
1738 if (ch >= '1' && ch <= '9')
1739 view->ch = ch = get_compound_key(view, ch);
1741 if (view->hiline && ch != ERR && ch != 0)
1742 view->hiline = 0; /* key pressed, clear line highlight */
1743 nodelay(view->window, TRUE);
1744 errcode = pthread_mutex_lock(&tog_mutex);
1745 if (errcode)
1746 return got_error_set_errno(errcode, "pthread_mutex_lock");
1748 if (tog_sigwinch_received || tog_sigcont_received) {
1749 tog_resizeterm();
1750 tog_sigwinch_received = 0;
1751 tog_sigcont_received = 0;
1752 TAILQ_FOREACH(v, views, entry) {
1753 err = view_resize(v);
1754 if (err)
1755 return err;
1756 err = v->input(new, v, KEY_RESIZE);
1757 if (err)
1758 return err;
1759 if (v->child) {
1760 err = view_resize(v->child);
1761 if (err)
1762 return err;
1763 err = v->child->input(new, v->child,
1764 KEY_RESIZE);
1765 if (err)
1766 return err;
1767 if (v->child->resized_x || v->child->resized_y) {
1768 err = view_resize_split(v, 0);
1769 if (err)
1770 return err;
1776 switch (ch) {
1777 case '?':
1778 case 'H':
1779 case KEY_F(1):
1780 if (view->type == TOG_VIEW_HELP)
1781 err = view->reset(view);
1782 else
1783 err = view_request_new(new, view, TOG_VIEW_HELP);
1784 break;
1785 case '\t':
1786 view->count = 0;
1787 if (view->child) {
1788 view->focussed = 0;
1789 view->child->focussed = 1;
1790 view->focus_child = 1;
1791 } else if (view->parent) {
1792 view->focussed = 0;
1793 view->parent->focussed = 1;
1794 view->parent->focus_child = 0;
1795 if (!view_is_splitscreen(view)) {
1796 if (view->parent->resize) {
1797 err = view->parent->resize(view->parent,
1798 0);
1799 if (err)
1800 return err;
1802 offset_selection_up(view->parent);
1803 err = view_fullscreen(view->parent);
1804 if (err)
1805 return err;
1808 break;
1809 case 'q':
1810 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1811 if (view->parent->resize) {
1812 /* might need more commits to fill fullscreen */
1813 err = view->parent->resize(view->parent, 0);
1814 if (err)
1815 break;
1817 offset_selection_up(view->parent);
1819 err = view->input(new, view, ch);
1820 view->dying = 1;
1821 break;
1822 case 'Q':
1823 *done = 1;
1824 break;
1825 case 'F':
1826 view->count = 0;
1827 if (view_is_parent_view(view)) {
1828 if (view->child == NULL)
1829 break;
1830 if (view_is_splitscreen(view->child)) {
1831 view->focussed = 0;
1832 view->child->focussed = 1;
1833 err = view_fullscreen(view->child);
1834 } else {
1835 err = view_splitscreen(view->child);
1836 if (!err)
1837 err = view_resize_split(view, 0);
1839 if (err)
1840 break;
1841 err = view->child->input(new, view->child,
1842 KEY_RESIZE);
1843 } else {
1844 if (view_is_splitscreen(view)) {
1845 view->parent->focussed = 0;
1846 view->focussed = 1;
1847 err = view_fullscreen(view);
1848 } else {
1849 err = view_splitscreen(view);
1850 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1851 err = view_resize(view->parent);
1852 if (!err)
1853 err = view_resize_split(view, 0);
1855 if (err)
1856 break;
1857 err = view->input(new, view, KEY_RESIZE);
1859 if (err)
1860 break;
1861 if (view->resize) {
1862 err = view->resize(view, 0);
1863 if (err)
1864 break;
1866 if (view->parent) {
1867 if (view->parent->resize) {
1868 err = view->parent->resize(view->parent, 0);
1869 if (err != NULL)
1870 break;
1872 err = offset_selection_down(view->parent);
1873 if (err != NULL)
1874 break;
1876 err = offset_selection_down(view);
1877 break;
1878 case 'S':
1879 view->count = 0;
1880 err = switch_split(view);
1881 break;
1882 case '-':
1883 err = view_resize_split(view, -1);
1884 break;
1885 case '+':
1886 err = view_resize_split(view, 1);
1887 break;
1888 case KEY_RESIZE:
1889 break;
1890 case '/':
1891 view->count = 0;
1892 if (view->search_start)
1893 view_search_start(view, fast_refresh);
1894 else
1895 err = view->input(new, view, ch);
1896 break;
1897 case 'N':
1898 case 'n':
1899 if (view->search_started && view->search_next) {
1900 view->searching = (ch == 'n' ?
1901 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1902 view->search_next_done = 0;
1903 view->search_next(view);
1904 } else
1905 err = view->input(new, view, ch);
1906 break;
1907 case 'A':
1908 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1909 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1910 view->action = "Patience diff algorithm";
1911 } else {
1912 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1913 view->action = "Myers diff algorithm";
1915 TAILQ_FOREACH(v, views, entry) {
1916 if (v->reset) {
1917 err = v->reset(v);
1918 if (err)
1919 return err;
1921 if (v->child && v->child->reset) {
1922 err = v->child->reset(v->child);
1923 if (err)
1924 return err;
1927 break;
1928 case TOG_KEY_SCRDUMP:
1929 err = screendump(view);
1930 break;
1931 default:
1932 err = view->input(new, view, ch);
1933 break;
1936 return err;
1939 static int
1940 view_needs_focus_indication(struct tog_view *view)
1942 if (view_is_parent_view(view)) {
1943 if (view->child == NULL || view->child->focussed)
1944 return 0;
1945 if (!view_is_splitscreen(view->child))
1946 return 0;
1947 } else if (!view_is_splitscreen(view))
1948 return 0;
1950 return view->focussed;
1953 static const struct got_error *
1954 tog_io_close(void)
1956 const struct got_error *err = NULL;
1958 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1959 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1960 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1961 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1962 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1963 err = got_ferror(tog_io.f, GOT_ERR_IO);
1964 if (tog_io.sdump && fclose(tog_io.sdump) == EOF && err == NULL)
1965 err = got_ferror(tog_io.sdump, GOT_ERR_IO);
1967 return err;
1970 static const struct got_error *
1971 view_loop(struct tog_view *view)
1973 const struct got_error *err = NULL;
1974 struct tog_view_list_head views;
1975 struct tog_view *new_view;
1976 char *mode;
1977 int fast_refresh = 10;
1978 int done = 0, errcode;
1980 mode = getenv("TOG_VIEW_SPLIT_MODE");
1981 if (!mode || !(*mode == 'h' || *mode == 'H'))
1982 view->mode = TOG_VIEW_SPLIT_VERT;
1983 else
1984 view->mode = TOG_VIEW_SPLIT_HRZN;
1986 errcode = pthread_mutex_lock(&tog_mutex);
1987 if (errcode)
1988 return got_error_set_errno(errcode, "pthread_mutex_lock");
1990 TAILQ_INIT(&views);
1991 TAILQ_INSERT_HEAD(&views, view, entry);
1993 view->focussed = 1;
1994 err = view->show(view);
1995 if (err)
1996 return err;
1997 update_panels();
1998 doupdate();
1999 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
2000 !tog_fatal_signal_received()) {
2001 /* Refresh fast during initialization, then become slower. */
2002 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
2003 halfdelay(10); /* switch to once per second */
2005 err = view_input(&new_view, &done, view, &views, fast_refresh);
2006 if (err)
2007 break;
2009 if (view->dying && view == TAILQ_FIRST(&views) &&
2010 TAILQ_NEXT(view, entry) == NULL)
2011 done = 1;
2012 if (done) {
2013 struct tog_view *v;
2016 * When we quit, scroll the screen up a single line
2017 * so we don't lose any information.
2019 TAILQ_FOREACH(v, &views, entry) {
2020 wmove(v->window, 0, 0);
2021 wdeleteln(v->window);
2022 wnoutrefresh(v->window);
2023 if (v->child && !view_is_fullscreen(v)) {
2024 wmove(v->child->window, 0, 0);
2025 wdeleteln(v->child->window);
2026 wnoutrefresh(v->child->window);
2029 doupdate();
2032 if (view->dying) {
2033 struct tog_view *v, *prev = NULL;
2035 if (view_is_parent_view(view))
2036 prev = TAILQ_PREV(view, tog_view_list_head,
2037 entry);
2038 else if (view->parent)
2039 prev = view->parent;
2041 if (view->parent) {
2042 view->parent->child = NULL;
2043 view->parent->focus_child = 0;
2044 /* Restore fullscreen line height. */
2045 view->parent->nlines = view->parent->lines;
2046 err = view_resize(view->parent);
2047 if (err)
2048 break;
2049 /* Make resized splits persist. */
2050 view_transfer_size(view->parent, view);
2051 } else
2052 TAILQ_REMOVE(&views, view, entry);
2054 err = view_close(view);
2055 if (err)
2056 goto done;
2058 view = NULL;
2059 TAILQ_FOREACH(v, &views, entry) {
2060 if (v->focussed)
2061 break;
2063 if (view == NULL && new_view == NULL) {
2064 /* No view has focus. Try to pick one. */
2065 if (prev)
2066 view = prev;
2067 else if (!TAILQ_EMPTY(&views)) {
2068 view = TAILQ_LAST(&views,
2069 tog_view_list_head);
2071 if (view) {
2072 if (view->focus_child) {
2073 view->child->focussed = 1;
2074 view = view->child;
2075 } else
2076 view->focussed = 1;
2080 if (new_view) {
2081 struct tog_view *v, *t;
2082 /* Only allow one parent view per type. */
2083 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2084 if (v->type != new_view->type)
2085 continue;
2086 TAILQ_REMOVE(&views, v, entry);
2087 err = view_close(v);
2088 if (err)
2089 goto done;
2090 break;
2092 TAILQ_INSERT_TAIL(&views, new_view, entry);
2093 view = new_view;
2095 if (view && !done) {
2096 if (view_is_parent_view(view)) {
2097 if (view->child && view->child->focussed)
2098 view = view->child;
2099 } else {
2100 if (view->parent && view->parent->focussed)
2101 view = view->parent;
2103 show_panel(view->panel);
2104 if (view->child && view_is_splitscreen(view->child))
2105 show_panel(view->child->panel);
2106 if (view->parent && view_is_splitscreen(view)) {
2107 err = view->parent->show(view->parent);
2108 if (err)
2109 goto done;
2111 err = view->show(view);
2112 if (err)
2113 goto done;
2114 if (view->child) {
2115 err = view->child->show(view->child);
2116 if (err)
2117 goto done;
2119 update_panels();
2120 doupdate();
2123 done:
2124 while (!TAILQ_EMPTY(&views)) {
2125 const struct got_error *close_err;
2126 view = TAILQ_FIRST(&views);
2127 TAILQ_REMOVE(&views, view, entry);
2128 close_err = view_close(view);
2129 if (close_err && err == NULL)
2130 err = close_err;
2133 errcode = pthread_mutex_unlock(&tog_mutex);
2134 if (errcode && err == NULL)
2135 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2137 return err;
2140 __dead static void
2141 usage_log(void)
2143 endwin();
2144 fprintf(stderr,
2145 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2146 getprogname());
2147 exit(1);
2150 /* Create newly allocated wide-character string equivalent to a byte string. */
2151 static const struct got_error *
2152 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2154 char *vis = NULL;
2155 const struct got_error *err = NULL;
2157 *ws = NULL;
2158 *wlen = mbstowcs(NULL, s, 0);
2159 if (*wlen == (size_t)-1) {
2160 int vislen;
2161 if (errno != EILSEQ)
2162 return got_error_from_errno("mbstowcs");
2164 /* byte string invalid in current encoding; try to "fix" it */
2165 err = got_mbsavis(&vis, &vislen, s);
2166 if (err)
2167 return err;
2168 *wlen = mbstowcs(NULL, vis, 0);
2169 if (*wlen == (size_t)-1) {
2170 err = got_error_from_errno("mbstowcs"); /* give up */
2171 goto done;
2175 *ws = calloc(*wlen + 1, sizeof(**ws));
2176 if (*ws == NULL) {
2177 err = got_error_from_errno("calloc");
2178 goto done;
2181 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2182 err = got_error_from_errno("mbstowcs");
2183 done:
2184 free(vis);
2185 if (err) {
2186 free(*ws);
2187 *ws = NULL;
2188 *wlen = 0;
2190 return err;
2193 static const struct got_error *
2194 expand_tab(char **ptr, const char *src)
2196 char *dst;
2197 size_t len, n, idx = 0, sz = 0;
2199 *ptr = NULL;
2200 n = len = strlen(src);
2201 dst = malloc(n + 1);
2202 if (dst == NULL)
2203 return got_error_from_errno("malloc");
2205 while (idx < len && src[idx]) {
2206 const char c = src[idx];
2208 if (c == '\t') {
2209 size_t nb = TABSIZE - sz % TABSIZE;
2210 char *p;
2212 p = realloc(dst, n + nb);
2213 if (p == NULL) {
2214 free(dst);
2215 return got_error_from_errno("realloc");
2218 dst = p;
2219 n += nb;
2220 memset(dst + sz, ' ', nb);
2221 sz += nb;
2222 } else
2223 dst[sz++] = src[idx];
2224 ++idx;
2227 dst[sz] = '\0';
2228 *ptr = dst;
2229 return NULL;
2233 * Advance at most n columns from wline starting at offset off.
2234 * Return the index to the first character after the span operation.
2235 * Return the combined column width of all spanned wide characters in
2236 * *rcol.
2238 static int
2239 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2241 int width, i, cols = 0;
2243 if (n == 0) {
2244 *rcol = cols;
2245 return off;
2248 for (i = off; wline[i] != L'\0'; ++i) {
2249 if (wline[i] == L'\t')
2250 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2251 else
2252 width = wcwidth(wline[i]);
2254 if (width == -1) {
2255 width = 1;
2256 wline[i] = L'.';
2259 if (cols + width > n)
2260 break;
2261 cols += width;
2264 *rcol = cols;
2265 return i;
2269 * Format a line for display, ensuring that it won't overflow a width limit.
2270 * With scrolling, the width returned refers to the scrolled version of the
2271 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2273 static const struct got_error *
2274 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2275 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2277 const struct got_error *err = NULL;
2278 int cols;
2279 wchar_t *wline = NULL;
2280 char *exstr = NULL;
2281 size_t wlen;
2282 int i, scrollx;
2284 *wlinep = NULL;
2285 *widthp = 0;
2287 if (expand) {
2288 err = expand_tab(&exstr, line);
2289 if (err)
2290 return err;
2293 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2294 free(exstr);
2295 if (err)
2296 return err;
2298 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2300 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2301 wline[wlen - 1] = L'\0';
2302 wlen--;
2304 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2305 wline[wlen - 1] = L'\0';
2306 wlen--;
2309 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2310 wline[i] = L'\0';
2312 if (widthp)
2313 *widthp = cols;
2314 if (scrollxp)
2315 *scrollxp = scrollx;
2316 if (err)
2317 free(wline);
2318 else
2319 *wlinep = wline;
2320 return err;
2323 static const struct got_error*
2324 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2325 struct got_object_id *id, struct got_repository *repo)
2327 static const struct got_error *err = NULL;
2328 struct got_reflist_entry *re;
2329 char *s;
2330 const char *name;
2332 *refs_str = NULL;
2334 if (refs == NULL)
2335 return NULL;
2337 TAILQ_FOREACH(re, refs, entry) {
2338 struct got_tag_object *tag = NULL;
2339 struct got_object_id *ref_id;
2340 int cmp;
2342 name = got_ref_get_name(re->ref);
2343 if (strcmp(name, GOT_REF_HEAD) == 0)
2344 continue;
2345 if (strncmp(name, "refs/", 5) == 0)
2346 name += 5;
2347 if (strncmp(name, "got/", 4) == 0)
2348 continue;
2349 if (strncmp(name, "heads/", 6) == 0)
2350 name += 6;
2351 if (strncmp(name, "remotes/", 8) == 0) {
2352 name += 8;
2353 s = strstr(name, "/" GOT_REF_HEAD);
2354 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
2355 continue;
2357 err = got_ref_resolve(&ref_id, repo, re->ref);
2358 if (err)
2359 break;
2360 if (strncmp(name, "tags/", 5) == 0) {
2361 err = got_object_open_as_tag(&tag, repo, ref_id);
2362 if (err) {
2363 if (err->code != GOT_ERR_OBJ_TYPE) {
2364 free(ref_id);
2365 break;
2367 /* Ref points at something other than a tag. */
2368 err = NULL;
2369 tag = NULL;
2372 cmp = got_object_id_cmp(tag ?
2373 got_object_tag_get_object_id(tag) : ref_id, id);
2374 free(ref_id);
2375 if (tag)
2376 got_object_tag_close(tag);
2377 if (cmp != 0)
2378 continue;
2379 s = *refs_str;
2380 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2381 s ? ", " : "", name) == -1) {
2382 err = got_error_from_errno("asprintf");
2383 free(s);
2384 *refs_str = NULL;
2385 break;
2387 free(s);
2390 return err;
2393 static const struct got_error *
2394 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2395 int col_tab_align)
2397 char *smallerthan;
2399 smallerthan = strchr(author, '<');
2400 if (smallerthan && smallerthan[1] != '\0')
2401 author = smallerthan + 1;
2402 author[strcspn(author, "@>")] = '\0';
2403 return format_line(wauthor, author_width, NULL, author, 0, limit,
2404 col_tab_align, 0);
2407 static const struct got_error *
2408 draw_commit(struct tog_view *view, struct commit_queue_entry *entry,
2409 const size_t date_display_cols, int author_display_cols)
2411 struct tog_log_view_state *s = &view->state.log;
2412 const struct got_error *err = NULL;
2413 struct got_commit_object *commit = entry->commit;
2414 struct got_object_id *id = entry->id;
2415 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2416 char *refs_str = NULL;
2417 char *logmsg0 = NULL, *logmsg = NULL;
2418 char *author = NULL;
2419 wchar_t *wrefstr = NULL, *wlogmsg = NULL, *wauthor = NULL;
2420 int author_width, refstr_width, logmsg_width;
2421 char *newline, *line = NULL;
2422 int col, limit, scrollx, logmsg_x;
2423 const int avail = view->ncols, marker_column = author_display_cols + 1;
2424 struct tm tm;
2425 time_t committer_time;
2426 struct tog_color *tc;
2427 struct got_reflist_head *refs;
2429 if (tog_base_commit.id != NULL && tog_base_commit.idx == -1 &&
2430 got_object_id_cmp(id, tog_base_commit.id) == 0)
2431 tog_base_commit.idx = entry->idx;
2432 if (tog_io.wait_for_ui && s->thread_args.need_commit_marker) {
2433 int rc;
2435 rc = pthread_cond_wait(&s->thread_args.log_loaded, &tog_mutex);
2436 if (rc)
2437 return got_error_set_errno(rc, "pthread_cond_wait");
2440 committer_time = got_object_commit_get_committer_time(commit);
2441 if (gmtime_r(&committer_time, &tm) == NULL)
2442 return got_error_from_errno("gmtime_r");
2443 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2444 return got_error(GOT_ERR_NO_SPACE);
2446 if (avail <= date_display_cols)
2447 limit = MIN(sizeof(datebuf) - 1, avail);
2448 else
2449 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2450 tc = get_color(&s->colors, TOG_COLOR_DATE);
2451 if (tc)
2452 wattr_on(view->window,
2453 COLOR_PAIR(tc->colorpair), NULL);
2454 waddnstr(view->window, datebuf, limit);
2455 if (tc)
2456 wattr_off(view->window,
2457 COLOR_PAIR(tc->colorpair), NULL);
2458 col = limit;
2459 if (col > avail)
2460 goto done;
2462 if (avail >= 120) {
2463 char *id_str;
2464 err = got_object_id_str(&id_str, id);
2465 if (err)
2466 goto done;
2467 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2468 if (tc)
2469 wattr_on(view->window,
2470 COLOR_PAIR(tc->colorpair), NULL);
2471 wprintw(view->window, "%.8s ", id_str);
2472 if (tc)
2473 wattr_off(view->window,
2474 COLOR_PAIR(tc->colorpair), NULL);
2475 free(id_str);
2476 col += 9;
2477 if (col > avail)
2478 goto done;
2481 if (s->use_committer)
2482 author = strdup(got_object_commit_get_committer(commit));
2483 else
2484 author = strdup(got_object_commit_get_author(commit));
2485 if (author == NULL) {
2486 err = got_error_from_errno("strdup");
2487 goto done;
2489 err = format_author(&wauthor, &author_width, author, avail - col, col);
2490 if (err)
2491 goto done;
2492 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2493 if (tc)
2494 wattr_on(view->window,
2495 COLOR_PAIR(tc->colorpair), NULL);
2496 waddwstr(view->window, wauthor);
2497 col += author_width;
2498 while (col < avail && author_width < author_display_cols + 2) {
2499 if (tog_base_commit.marker != GOT_WORKTREE_STATE_UNKNOWN &&
2500 author_width == marker_column &&
2501 entry->idx == tog_base_commit.idx && !s->limit_view) {
2502 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2503 if (tc)
2504 wattr_on(view->window,
2505 COLOR_PAIR(tc->colorpair), NULL);
2506 waddch(view->window, tog_base_commit.marker);
2507 if (tc)
2508 wattr_off(view->window,
2509 COLOR_PAIR(tc->colorpair), NULL);
2510 } else
2511 waddch(view->window, ' ');
2512 col++;
2513 author_width++;
2515 if (tc)
2516 wattr_off(view->window,
2517 COLOR_PAIR(tc->colorpair), NULL);
2518 if (col > avail)
2519 goto done;
2521 err = got_object_commit_get_logmsg(&logmsg0, commit);
2522 if (err)
2523 goto done;
2524 logmsg = logmsg0;
2525 while (*logmsg == '\n')
2526 logmsg++;
2527 newline = strchr(logmsg, '\n');
2528 if (newline)
2529 *newline = '\0';
2531 limit = avail - col;
2532 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2533 limit--; /* for the border */
2535 /* Prepend reference labels to log message if possible .*/
2536 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, id);
2537 err = build_refs_str(&refs_str, refs, id, s->repo);
2538 if (err)
2539 goto done;
2540 if (refs_str) {
2541 char *rs;
2543 if (asprintf(&rs, "[%s]", refs_str) == -1) {
2544 err = got_error_from_errno("asprintf");
2545 goto done;
2547 err = format_line(&wrefstr, &refstr_width,
2548 &scrollx, rs, view->x, limit, col, 1);
2549 free(rs);
2550 if (err)
2551 goto done;
2552 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2553 if (tc)
2554 wattr_on(view->window,
2555 COLOR_PAIR(tc->colorpair), NULL);
2556 waddwstr(view->window, &wrefstr[scrollx]);
2557 if (tc)
2558 wattr_off(view->window,
2559 COLOR_PAIR(tc->colorpair), NULL);
2560 col += MAX(refstr_width, 0);
2561 if (col > avail)
2562 goto done;
2564 if (col < avail) {
2565 waddch(view->window, ' ');
2566 col++;
2569 if (refstr_width > 0)
2570 logmsg_x = 0;
2571 else {
2572 int unscrolled_refstr_width;
2573 size_t len = wcslen(wrefstr);
2576 * No need to check for -1 return value here since
2577 * unprintables have been replaced by span_wline().
2579 unscrolled_refstr_width = wcswidth(wrefstr, len);
2580 unscrolled_refstr_width += 1; /* trailing space */
2581 logmsg_x = view->x - unscrolled_refstr_width;
2584 limit = avail - col;
2585 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2586 limit--; /* for the border */
2587 } else
2588 logmsg_x = view->x;
2590 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, logmsg_x,
2591 limit, col, 1);
2592 if (err)
2593 goto done;
2594 waddwstr(view->window, &wlogmsg[scrollx]);
2595 col += MAX(logmsg_width, 0);
2596 while (col < avail) {
2597 waddch(view->window, ' ');
2598 col++;
2600 done:
2601 free(logmsg0);
2602 free(wlogmsg);
2603 free(wrefstr);
2604 free(refs_str);
2605 free(author);
2606 free(wauthor);
2607 free(line);
2608 return err;
2611 static struct commit_queue_entry *
2612 alloc_commit_queue_entry(struct got_commit_object *commit,
2613 struct got_object_id *id)
2615 struct commit_queue_entry *entry;
2616 struct got_object_id *dup;
2618 entry = calloc(1, sizeof(*entry));
2619 if (entry == NULL)
2620 return NULL;
2622 dup = got_object_id_dup(id);
2623 if (dup == NULL) {
2624 free(entry);
2625 return NULL;
2628 entry->id = dup;
2629 entry->commit = commit;
2630 return entry;
2633 static void
2634 pop_commit(struct commit_queue *commits)
2636 struct commit_queue_entry *entry;
2638 entry = TAILQ_FIRST(&commits->head);
2639 TAILQ_REMOVE(&commits->head, entry, entry);
2640 got_object_commit_close(entry->commit);
2641 commits->ncommits--;
2642 free(entry->id);
2643 free(entry);
2646 static void
2647 free_commits(struct commit_queue *commits)
2649 while (!TAILQ_EMPTY(&commits->head))
2650 pop_commit(commits);
2653 static const struct got_error *
2654 match_commit(int *have_match, struct got_object_id *id,
2655 struct got_commit_object *commit, regex_t *regex)
2657 const struct got_error *err = NULL;
2658 regmatch_t regmatch;
2659 char *id_str = NULL, *logmsg = NULL;
2661 *have_match = 0;
2663 err = got_object_id_str(&id_str, id);
2664 if (err)
2665 return err;
2667 err = got_object_commit_get_logmsg(&logmsg, commit);
2668 if (err)
2669 goto done;
2671 if (regexec(regex, got_object_commit_get_author(commit), 1,
2672 &regmatch, 0) == 0 ||
2673 regexec(regex, got_object_commit_get_committer(commit), 1,
2674 &regmatch, 0) == 0 ||
2675 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2676 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2677 *have_match = 1;
2678 done:
2679 free(id_str);
2680 free(logmsg);
2681 return err;
2684 static const struct got_error *
2685 queue_commits(struct tog_log_thread_args *a)
2687 const struct got_error *err = NULL;
2690 * We keep all commits open throughout the lifetime of the log
2691 * view in order to avoid having to re-fetch commits from disk
2692 * while updating the display.
2694 do {
2695 struct got_object_id id;
2696 struct got_commit_object *commit;
2697 struct commit_queue_entry *entry;
2698 int limit_match = 0;
2699 int errcode;
2701 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2702 NULL, NULL);
2703 if (err)
2704 break;
2706 err = got_object_open_as_commit(&commit, a->repo, &id);
2707 if (err)
2708 break;
2709 entry = alloc_commit_queue_entry(commit, &id);
2710 if (entry == NULL) {
2711 err = got_error_from_errno("alloc_commit_queue_entry");
2712 break;
2715 errcode = pthread_mutex_lock(&tog_mutex);
2716 if (errcode) {
2717 err = got_error_set_errno(errcode,
2718 "pthread_mutex_lock");
2719 break;
2722 entry->idx = a->real_commits->ncommits;
2723 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2724 a->real_commits->ncommits++;
2726 if (*a->limiting) {
2727 err = match_commit(&limit_match, &id, commit,
2728 a->limit_regex);
2729 if (err)
2730 break;
2732 if (limit_match) {
2733 struct commit_queue_entry *matched;
2735 matched = alloc_commit_queue_entry(
2736 entry->commit, entry->id);
2737 if (matched == NULL) {
2738 err = got_error_from_errno(
2739 "alloc_commit_queue_entry");
2740 break;
2742 matched->commit = entry->commit;
2743 got_object_commit_retain(entry->commit);
2745 matched->idx = a->limit_commits->ncommits;
2746 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2747 matched, entry);
2748 a->limit_commits->ncommits++;
2752 * This is how we signal log_thread() that we
2753 * have found a match, and that it should be
2754 * counted as a new entry for the view.
2756 a->limit_match = limit_match;
2759 if (*a->searching == TOG_SEARCH_FORWARD &&
2760 !*a->search_next_done) {
2761 int have_match;
2762 err = match_commit(&have_match, &id, commit, a->regex);
2763 if (err)
2764 break;
2766 if (*a->limiting) {
2767 if (limit_match && have_match)
2768 *a->search_next_done =
2769 TOG_SEARCH_HAVE_MORE;
2770 } else if (have_match)
2771 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2774 errcode = pthread_mutex_unlock(&tog_mutex);
2775 if (errcode && err == NULL)
2776 err = got_error_set_errno(errcode,
2777 "pthread_mutex_unlock");
2778 if (err)
2779 break;
2780 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2782 return err;
2785 static void
2786 select_commit(struct tog_log_view_state *s)
2788 struct commit_queue_entry *entry;
2789 int ncommits = 0;
2791 entry = s->first_displayed_entry;
2792 while (entry) {
2793 if (ncommits == s->selected) {
2794 s->selected_entry = entry;
2795 break;
2797 entry = TAILQ_NEXT(entry, entry);
2798 ncommits++;
2802 static const struct got_error *
2803 draw_commits(struct tog_view *view)
2805 const struct got_error *err = NULL;
2806 struct tog_log_view_state *s = &view->state.log;
2807 struct commit_queue_entry *entry = s->selected_entry;
2808 int limit = view->nlines;
2809 int width;
2810 int ncommits, author_cols = 4, refstr_cols;
2811 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2812 char *refs_str = NULL;
2813 wchar_t *wline;
2814 struct tog_color *tc;
2815 static const size_t date_display_cols = 12;
2816 struct got_reflist_head *refs;
2818 if (view_is_hsplit_top(view))
2819 --limit; /* account for border */
2821 if (s->selected_entry &&
2822 !(view->searching && view->search_next_done == 0)) {
2823 err = got_object_id_str(&id_str, s->selected_entry->id);
2824 if (err)
2825 return err;
2826 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2827 s->selected_entry->id);
2828 err = build_refs_str(&refs_str, refs, s->selected_entry->id,
2829 s->repo);
2830 if (err)
2831 goto done;
2834 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2835 halfdelay(10); /* disable fast refresh */
2837 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2838 if (asprintf(&ncommits_str, " [%d/%d] %s",
2839 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2840 (view->searching && !view->search_next_done) ?
2841 "searching..." : "loading...") == -1) {
2842 err = got_error_from_errno("asprintf");
2843 goto done;
2845 } else {
2846 const char *search_str = NULL;
2847 const char *limit_str = NULL;
2849 if (view->searching) {
2850 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2851 search_str = "no more matches";
2852 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2853 search_str = "no matches found";
2854 else if (!view->search_next_done)
2855 search_str = "searching...";
2858 if (s->limit_view && s->commits->ncommits == 0)
2859 limit_str = "no matches found";
2861 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2862 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2863 search_str ? search_str : (refs_str ? refs_str : ""),
2864 limit_str ? limit_str : "") == -1) {
2865 err = got_error_from_errno("asprintf");
2866 goto done;
2870 free(refs_str);
2871 refs_str = NULL;
2873 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2874 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2875 "........................................",
2876 s->in_repo_path, ncommits_str) == -1) {
2877 err = got_error_from_errno("asprintf");
2878 header = NULL;
2879 goto done;
2881 } else if (asprintf(&header, "commit %s%s",
2882 id_str ? id_str : "........................................",
2883 ncommits_str) == -1) {
2884 err = got_error_from_errno("asprintf");
2885 header = NULL;
2886 goto done;
2888 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2889 if (err)
2890 goto done;
2892 werase(view->window);
2894 if (view_needs_focus_indication(view))
2895 wstandout(view->window);
2896 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2897 if (tc)
2898 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2899 waddwstr(view->window, wline);
2900 while (width < view->ncols) {
2901 waddch(view->window, ' ');
2902 width++;
2904 if (tc)
2905 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2906 if (view_needs_focus_indication(view))
2907 wstandend(view->window);
2908 free(wline);
2909 if (limit <= 1)
2910 goto done;
2912 /* Grow author column size if necessary, and set view->maxx. */
2913 entry = s->first_displayed_entry;
2914 ncommits = 0;
2915 view->maxx = 0;
2916 while (entry) {
2917 struct got_commit_object *c = entry->commit;
2918 char *author, *eol, *msg, *msg0;
2919 wchar_t *wauthor, *wmsg;
2920 int width;
2921 if (ncommits >= limit - 1)
2922 break;
2923 if (s->use_committer)
2924 author = strdup(got_object_commit_get_committer(c));
2925 else
2926 author = strdup(got_object_commit_get_author(c));
2927 if (author == NULL) {
2928 err = got_error_from_errno("strdup");
2929 goto done;
2931 err = format_author(&wauthor, &width, author, COLS,
2932 date_display_cols);
2933 if (author_cols < width)
2934 author_cols = width;
2935 free(wauthor);
2936 free(author);
2937 if (err)
2938 goto done;
2939 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2940 entry->id);
2941 err = build_refs_str(&refs_str, refs, entry->id, s->repo);
2942 if (err)
2943 goto done;
2944 if (refs_str) {
2945 wchar_t *ws;
2946 err = format_line(&ws, &width, NULL, refs_str,
2947 0, INT_MAX, date_display_cols + author_cols, 0);
2948 free(ws);
2949 free(refs_str);
2950 refs_str = NULL;
2951 if (err)
2952 goto done;
2953 refstr_cols = width + 3; /* account for [ ] + space */
2954 } else
2955 refstr_cols = 0;
2956 err = got_object_commit_get_logmsg(&msg0, c);
2957 if (err)
2958 goto done;
2959 msg = msg0;
2960 while (*msg == '\n')
2961 ++msg;
2962 if ((eol = strchr(msg, '\n')))
2963 *eol = '\0';
2964 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2965 date_display_cols + author_cols + refstr_cols, 0);
2966 if (err)
2967 goto done;
2968 view->maxx = MAX(view->maxx, width + refstr_cols);
2969 free(msg0);
2970 free(wmsg);
2971 ncommits++;
2972 entry = TAILQ_NEXT(entry, entry);
2975 entry = s->first_displayed_entry;
2976 s->last_displayed_entry = s->first_displayed_entry;
2977 ncommits = 0;
2978 while (entry) {
2979 if (ncommits >= limit - 1)
2980 break;
2981 if (ncommits == s->selected)
2982 wstandout(view->window);
2983 err = draw_commit(view, entry, date_display_cols, author_cols);
2984 if (ncommits == s->selected)
2985 wstandend(view->window);
2986 if (err)
2987 goto done;
2988 ncommits++;
2989 s->last_displayed_entry = entry;
2990 entry = TAILQ_NEXT(entry, entry);
2993 view_border(view);
2994 done:
2995 free(id_str);
2996 free(refs_str);
2997 free(ncommits_str);
2998 free(header);
2999 return err;
3002 static void
3003 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
3005 struct commit_queue_entry *entry;
3006 int nscrolled = 0;
3008 entry = TAILQ_FIRST(&s->commits->head);
3009 if (s->first_displayed_entry == entry)
3010 return;
3012 entry = s->first_displayed_entry;
3013 while (entry && nscrolled < maxscroll) {
3014 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3015 if (entry) {
3016 s->first_displayed_entry = entry;
3017 nscrolled++;
3022 static const struct got_error *
3023 trigger_log_thread(struct tog_view *view, int wait)
3025 struct tog_log_thread_args *ta = &view->state.log.thread_args;
3026 int errcode;
3028 if (!using_mock_io)
3029 halfdelay(1); /* fast refresh while loading commits */
3031 while (!ta->log_complete && !tog_thread_error &&
3032 (ta->commits_needed > 0 || ta->load_all)) {
3033 /* Wake the log thread. */
3034 errcode = pthread_cond_signal(&ta->need_commits);
3035 if (errcode)
3036 return got_error_set_errno(errcode,
3037 "pthread_cond_signal");
3040 * The mutex will be released while the view loop waits
3041 * in wgetch(), at which time the log thread will run.
3043 if (!wait)
3044 break;
3046 /* Display progress update in log view. */
3047 show_log_view(view);
3048 update_panels();
3049 doupdate();
3051 /* Wait right here while next commit is being loaded. */
3052 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
3053 if (errcode)
3054 return got_error_set_errno(errcode,
3055 "pthread_cond_wait");
3057 /* Display progress update in log view. */
3058 show_log_view(view);
3059 update_panels();
3060 doupdate();
3063 return NULL;
3066 static const struct got_error *
3067 request_log_commits(struct tog_view *view)
3069 struct tog_log_view_state *state = &view->state.log;
3070 const struct got_error *err = NULL;
3072 if (state->thread_args.log_complete)
3073 return NULL;
3075 state->thread_args.commits_needed += view->nscrolled;
3076 err = trigger_log_thread(view, 1);
3077 view->nscrolled = 0;
3079 return err;
3082 static const struct got_error *
3083 log_scroll_down(struct tog_view *view, int maxscroll)
3085 struct tog_log_view_state *s = &view->state.log;
3086 const struct got_error *err = NULL;
3087 struct commit_queue_entry *pentry;
3088 int nscrolled = 0, ncommits_needed;
3090 if (s->last_displayed_entry == NULL)
3091 return NULL;
3093 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
3094 if (s->commits->ncommits < ncommits_needed &&
3095 !s->thread_args.log_complete) {
3097 * Ask the log thread for required amount of commits.
3099 s->thread_args.commits_needed +=
3100 ncommits_needed - s->commits->ncommits;
3101 err = trigger_log_thread(view, 1);
3102 if (err)
3103 return err;
3106 do {
3107 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
3108 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3109 break;
3111 s->last_displayed_entry = pentry ?
3112 pentry : s->last_displayed_entry;
3114 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3115 if (pentry == NULL)
3116 break;
3117 s->first_displayed_entry = pentry;
3118 } while (++nscrolled < maxscroll);
3120 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3121 view->nscrolled += nscrolled;
3122 else
3123 view->nscrolled = 0;
3125 return err;
3128 static const struct got_error *
3129 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3130 struct got_commit_object *commit, struct got_object_id *commit_id,
3131 struct tog_view *log_view, struct got_repository *repo)
3133 const struct got_error *err;
3134 struct got_object_qid *parent_id;
3135 struct tog_view *diff_view;
3137 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3138 if (diff_view == NULL)
3139 return got_error_from_errno("view_open");
3141 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3142 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3143 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3144 if (err == NULL)
3145 *new_view = diff_view;
3146 return err;
3149 static const struct got_error *
3150 tree_view_visit_subtree(struct tog_tree_view_state *s,
3151 struct got_tree_object *subtree)
3153 struct tog_parent_tree *parent;
3155 parent = calloc(1, sizeof(*parent));
3156 if (parent == NULL)
3157 return got_error_from_errno("calloc");
3159 parent->tree = s->tree;
3160 parent->first_displayed_entry = s->first_displayed_entry;
3161 parent->selected_entry = s->selected_entry;
3162 parent->selected = s->selected;
3163 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3164 s->tree = subtree;
3165 s->selected = 0;
3166 s->first_displayed_entry = NULL;
3167 return NULL;
3170 static const struct got_error *
3171 tree_view_walk_path(struct tog_tree_view_state *s,
3172 struct got_commit_object *commit, const char *path)
3174 const struct got_error *err = NULL;
3175 struct got_tree_object *tree = NULL;
3176 const char *p;
3177 char *slash, *subpath = NULL;
3179 /* Walk the path and open corresponding tree objects. */
3180 p = path;
3181 while (*p) {
3182 struct got_tree_entry *te;
3183 struct got_object_id *tree_id;
3184 char *te_name;
3186 while (p[0] == '/')
3187 p++;
3189 /* Ensure the correct subtree entry is selected. */
3190 slash = strchr(p, '/');
3191 if (slash == NULL)
3192 te_name = strdup(p);
3193 else
3194 te_name = strndup(p, slash - p);
3195 if (te_name == NULL) {
3196 err = got_error_from_errno("strndup");
3197 break;
3199 te = got_object_tree_find_entry(s->tree, te_name);
3200 if (te == NULL) {
3201 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3202 free(te_name);
3203 break;
3205 free(te_name);
3206 s->first_displayed_entry = s->selected_entry = te;
3208 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3209 break; /* jump to this file's entry */
3211 slash = strchr(p, '/');
3212 if (slash)
3213 subpath = strndup(path, slash - path);
3214 else
3215 subpath = strdup(path);
3216 if (subpath == NULL) {
3217 err = got_error_from_errno("strdup");
3218 break;
3221 err = got_object_id_by_path(&tree_id, s->repo, commit,
3222 subpath);
3223 if (err)
3224 break;
3226 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3227 free(tree_id);
3228 if (err)
3229 break;
3231 err = tree_view_visit_subtree(s, tree);
3232 if (err) {
3233 got_object_tree_close(tree);
3234 break;
3236 if (slash == NULL)
3237 break;
3238 free(subpath);
3239 subpath = NULL;
3240 p = slash;
3243 free(subpath);
3244 return err;
3247 static const struct got_error *
3248 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3249 struct commit_queue_entry *entry, const char *path,
3250 const char *head_ref_name, struct got_repository *repo)
3252 const struct got_error *err = NULL;
3253 struct tog_tree_view_state *s;
3254 struct tog_view *tree_view;
3256 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3257 if (tree_view == NULL)
3258 return got_error_from_errno("view_open");
3260 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3261 if (err)
3262 return err;
3263 s = &tree_view->state.tree;
3265 *new_view = tree_view;
3267 if (got_path_is_root_dir(path))
3268 return NULL;
3270 return tree_view_walk_path(s, entry->commit, path);
3273 static const struct got_error *
3274 block_signals_used_by_main_thread(void)
3276 sigset_t sigset;
3277 int errcode;
3279 if (sigemptyset(&sigset) == -1)
3280 return got_error_from_errno("sigemptyset");
3282 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3283 if (sigaddset(&sigset, SIGWINCH) == -1)
3284 return got_error_from_errno("sigaddset");
3285 if (sigaddset(&sigset, SIGCONT) == -1)
3286 return got_error_from_errno("sigaddset");
3287 if (sigaddset(&sigset, SIGINT) == -1)
3288 return got_error_from_errno("sigaddset");
3289 if (sigaddset(&sigset, SIGTERM) == -1)
3290 return got_error_from_errno("sigaddset");
3292 /* ncurses handles SIGTSTP */
3293 if (sigaddset(&sigset, SIGTSTP) == -1)
3294 return got_error_from_errno("sigaddset");
3296 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3297 if (errcode)
3298 return got_error_set_errno(errcode, "pthread_sigmask");
3300 return NULL;
3303 static void *
3304 log_thread(void *arg)
3306 const struct got_error *err = NULL;
3307 int errcode = 0;
3308 struct tog_log_thread_args *a = arg;
3309 int done = 0;
3312 * Sync startup with main thread such that we begin our
3313 * work once view_input() has released the mutex.
3315 errcode = pthread_mutex_lock(&tog_mutex);
3316 if (errcode) {
3317 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3318 return (void *)err;
3321 err = block_signals_used_by_main_thread();
3322 if (err) {
3323 pthread_mutex_unlock(&tog_mutex);
3324 goto done;
3327 while (!done && !err && !tog_fatal_signal_received()) {
3328 errcode = pthread_mutex_unlock(&tog_mutex);
3329 if (errcode) {
3330 err = got_error_set_errno(errcode,
3331 "pthread_mutex_unlock");
3332 goto done;
3334 err = queue_commits(a);
3335 if (err) {
3336 if (err->code != GOT_ERR_ITER_COMPLETED)
3337 goto done;
3338 err = NULL;
3339 done = 1;
3340 a->commits_needed = 0;
3341 } else if (a->commits_needed > 0 && !a->load_all) {
3342 if (*a->limiting) {
3343 if (a->limit_match)
3344 a->commits_needed--;
3345 } else
3346 a->commits_needed--;
3349 errcode = pthread_mutex_lock(&tog_mutex);
3350 if (errcode) {
3351 err = got_error_set_errno(errcode,
3352 "pthread_mutex_lock");
3353 goto done;
3354 } else if (*a->quit)
3355 done = 1;
3356 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3357 *a->first_displayed_entry =
3358 TAILQ_FIRST(&a->limit_commits->head);
3359 *a->selected_entry = *a->first_displayed_entry;
3360 } else if (*a->first_displayed_entry == NULL) {
3361 *a->first_displayed_entry =
3362 TAILQ_FIRST(&a->real_commits->head);
3363 *a->selected_entry = *a->first_displayed_entry;
3366 errcode = pthread_cond_signal(&a->commit_loaded);
3367 if (errcode) {
3368 err = got_error_set_errno(errcode,
3369 "pthread_cond_signal");
3370 pthread_mutex_unlock(&tog_mutex);
3371 goto done;
3374 if (a->commits_needed == 0 &&
3375 a->need_commit_marker && a->worktree) {
3376 errcode = pthread_mutex_unlock(&tog_mutex);
3377 if (errcode) {
3378 err = got_error_set_errno(errcode,
3379 "pthread_mutex_unlock");
3380 goto done;
3382 err = got_worktree_get_state(&tog_base_commit.marker,
3383 a->repo, a->worktree, NULL, NULL);
3384 if (err)
3385 goto done;
3386 errcode = pthread_mutex_lock(&tog_mutex);
3387 if (errcode) {
3388 err = got_error_set_errno(errcode,
3389 "pthread_mutex_lock");
3390 goto done;
3392 a->need_commit_marker = 0;
3394 * The main thread did not close this
3395 * work tree yet. Close it now.
3397 got_worktree_close(a->worktree);
3398 a->worktree = NULL;
3400 if (*a->quit)
3401 done = 1;
3404 if (done)
3405 a->commits_needed = 0;
3406 else {
3407 if (a->commits_needed == 0 && !a->load_all) {
3408 if (tog_io.wait_for_ui) {
3409 errcode = pthread_cond_signal(
3410 &a->log_loaded);
3411 if (errcode && err == NULL)
3412 err = got_error_set_errno(
3413 errcode,
3414 "pthread_cond_signal");
3417 errcode = pthread_cond_wait(&a->need_commits,
3418 &tog_mutex);
3419 if (errcode) {
3420 err = got_error_set_errno(errcode,
3421 "pthread_cond_wait");
3422 pthread_mutex_unlock(&tog_mutex);
3423 goto done;
3425 if (*a->quit)
3426 done = 1;
3430 a->log_complete = 1;
3431 if (tog_io.wait_for_ui) {
3432 errcode = pthread_cond_signal(&a->log_loaded);
3433 if (errcode && err == NULL)
3434 err = got_error_set_errno(errcode,
3435 "pthread_cond_signal");
3438 errcode = pthread_mutex_unlock(&tog_mutex);
3439 if (errcode)
3440 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3441 done:
3442 if (err) {
3443 tog_thread_error = 1;
3444 pthread_cond_signal(&a->commit_loaded);
3445 if (a->worktree) {
3446 got_worktree_close(a->worktree);
3447 a->worktree = NULL;
3450 return (void *)err;
3453 static const struct got_error *
3454 stop_log_thread(struct tog_log_view_state *s)
3456 const struct got_error *err = NULL, *thread_err = NULL;
3457 int errcode;
3459 if (s->thread) {
3460 s->quit = 1;
3461 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3462 if (errcode)
3463 return got_error_set_errno(errcode,
3464 "pthread_cond_signal");
3465 errcode = pthread_mutex_unlock(&tog_mutex);
3466 if (errcode)
3467 return got_error_set_errno(errcode,
3468 "pthread_mutex_unlock");
3469 errcode = pthread_join(s->thread, (void **)&thread_err);
3470 if (errcode)
3471 return got_error_set_errno(errcode, "pthread_join");
3472 errcode = pthread_mutex_lock(&tog_mutex);
3473 if (errcode)
3474 return got_error_set_errno(errcode,
3475 "pthread_mutex_lock");
3476 s->thread = NULL;
3479 if (s->thread_args.repo) {
3480 err = got_repo_close(s->thread_args.repo);
3481 s->thread_args.repo = NULL;
3484 if (s->thread_args.pack_fds) {
3485 const struct got_error *pack_err =
3486 got_repo_pack_fds_close(s->thread_args.pack_fds);
3487 if (err == NULL)
3488 err = pack_err;
3489 s->thread_args.pack_fds = NULL;
3492 if (s->thread_args.graph) {
3493 got_commit_graph_close(s->thread_args.graph);
3494 s->thread_args.graph = NULL;
3497 return err ? err : thread_err;
3500 static const struct got_error *
3501 close_log_view(struct tog_view *view)
3503 const struct got_error *err = NULL;
3504 struct tog_log_view_state *s = &view->state.log;
3505 int errcode;
3507 err = stop_log_thread(s);
3509 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3510 if (errcode && err == NULL)
3511 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3513 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3514 if (errcode && err == NULL)
3515 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3517 free_commits(&s->limit_commits);
3518 free_commits(&s->real_commits);
3519 free(s->in_repo_path);
3520 s->in_repo_path = NULL;
3521 free(s->start_id);
3522 s->start_id = NULL;
3523 free(s->head_ref_name);
3524 s->head_ref_name = NULL;
3525 return err;
3529 * We use two queues to implement the limit feature: first consists of
3530 * commits matching the current limit_regex; second is the real queue
3531 * of all known commits (real_commits). When the user starts limiting,
3532 * we swap queues such that all movement and displaying functionality
3533 * works with very slight change.
3535 static const struct got_error *
3536 limit_log_view(struct tog_view *view)
3538 struct tog_log_view_state *s = &view->state.log;
3539 struct commit_queue_entry *entry;
3540 struct tog_view *v = view;
3541 const struct got_error *err = NULL;
3542 char pattern[1024];
3543 int ret;
3545 if (view_is_hsplit_top(view))
3546 v = view->child;
3547 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3548 v = view->parent;
3550 /* Get the pattern */
3551 wmove(v->window, v->nlines - 1, 0);
3552 wclrtoeol(v->window);
3553 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3554 nodelay(v->window, FALSE);
3555 nocbreak();
3556 echo();
3557 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3558 cbreak();
3559 noecho();
3560 nodelay(v->window, TRUE);
3561 if (ret == ERR)
3562 return NULL;
3564 if (*pattern == '\0') {
3566 * Safety measure for the situation where the user
3567 * resets limit without previously limiting anything.
3569 if (!s->limit_view)
3570 return NULL;
3573 * User could have pressed Ctrl+L, which refreshed the
3574 * commit queues, it means we can't save previously
3575 * (before limit took place) displayed entries,
3576 * because they would point to already free'ed memory,
3577 * so we are forced to always select first entry of
3578 * the queue.
3580 s->commits = &s->real_commits;
3581 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3582 s->selected_entry = s->first_displayed_entry;
3583 s->selected = 0;
3584 s->limit_view = 0;
3586 return NULL;
3589 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3590 return NULL;
3592 s->limit_view = 1;
3594 /* Clear the screen while loading limit view */
3595 s->first_displayed_entry = NULL;
3596 s->last_displayed_entry = NULL;
3597 s->selected_entry = NULL;
3598 s->commits = &s->limit_commits;
3600 /* Prepare limit queue for new search */
3601 free_commits(&s->limit_commits);
3602 s->limit_commits.ncommits = 0;
3604 /* First process commits, which are in queue already */
3605 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3606 int have_match = 0;
3608 err = match_commit(&have_match, entry->id,
3609 entry->commit, &s->limit_regex);
3610 if (err)
3611 return err;
3613 if (have_match) {
3614 struct commit_queue_entry *matched;
3616 matched = alloc_commit_queue_entry(entry->commit,
3617 entry->id);
3618 if (matched == NULL) {
3619 err = got_error_from_errno(
3620 "alloc_commit_queue_entry");
3621 break;
3623 matched->commit = entry->commit;
3624 got_object_commit_retain(entry->commit);
3626 matched->idx = s->limit_commits.ncommits;
3627 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3628 matched, entry);
3629 s->limit_commits.ncommits++;
3633 /* Second process all the commits, until we fill the screen */
3634 if (s->limit_commits.ncommits < view->nlines - 1 &&
3635 !s->thread_args.log_complete) {
3636 s->thread_args.commits_needed +=
3637 view->nlines - s->limit_commits.ncommits - 1;
3638 err = trigger_log_thread(view, 1);
3639 if (err)
3640 return err;
3643 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3644 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3645 s->selected = 0;
3647 return NULL;
3650 static const struct got_error *
3651 search_start_log_view(struct tog_view *view)
3653 struct tog_log_view_state *s = &view->state.log;
3655 s->matched_entry = NULL;
3656 s->search_entry = NULL;
3657 return NULL;
3660 static const struct got_error *
3661 search_next_log_view(struct tog_view *view)
3663 const struct got_error *err = NULL;
3664 struct tog_log_view_state *s = &view->state.log;
3665 struct commit_queue_entry *entry;
3667 /* Display progress update in log view. */
3668 show_log_view(view);
3669 update_panels();
3670 doupdate();
3672 if (s->search_entry) {
3673 int errcode, ch;
3674 errcode = pthread_mutex_unlock(&tog_mutex);
3675 if (errcode)
3676 return got_error_set_errno(errcode,
3677 "pthread_mutex_unlock");
3678 ch = wgetch(view->window);
3679 errcode = pthread_mutex_lock(&tog_mutex);
3680 if (errcode)
3681 return got_error_set_errno(errcode,
3682 "pthread_mutex_lock");
3683 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3684 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3685 return NULL;
3687 if (view->searching == TOG_SEARCH_FORWARD)
3688 entry = TAILQ_NEXT(s->search_entry, entry);
3689 else
3690 entry = TAILQ_PREV(s->search_entry,
3691 commit_queue_head, entry);
3692 } else if (s->matched_entry) {
3694 * If the user has moved the cursor after we hit a match,
3695 * the position from where we should continue searching
3696 * might have changed.
3698 if (view->searching == TOG_SEARCH_FORWARD)
3699 entry = TAILQ_NEXT(s->selected_entry, entry);
3700 else
3701 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3702 entry);
3703 } else {
3704 entry = s->selected_entry;
3707 while (1) {
3708 int have_match = 0;
3710 if (entry == NULL) {
3711 if (s->thread_args.log_complete ||
3712 view->searching == TOG_SEARCH_BACKWARD) {
3713 view->search_next_done =
3714 (s->matched_entry == NULL ?
3715 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3716 s->search_entry = NULL;
3717 return NULL;
3720 * Poke the log thread for more commits and return,
3721 * allowing the main loop to make progress. Search
3722 * will resume at s->search_entry once we come back.
3724 s->search_entry = s->selected_entry;
3725 s->thread_args.commits_needed++;
3726 return trigger_log_thread(view, 0);
3729 err = match_commit(&have_match, entry->id, entry->commit,
3730 &view->regex);
3731 if (err)
3732 break;
3733 if (have_match) {
3734 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3735 s->matched_entry = entry;
3736 break;
3739 s->search_entry = entry;
3740 if (view->searching == TOG_SEARCH_FORWARD)
3741 entry = TAILQ_NEXT(entry, entry);
3742 else
3743 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3746 if (s->matched_entry) {
3747 int cur = s->selected_entry->idx;
3748 while (cur < s->matched_entry->idx) {
3749 err = input_log_view(NULL, view, KEY_DOWN);
3750 if (err)
3751 return err;
3752 cur++;
3754 while (cur > s->matched_entry->idx) {
3755 err = input_log_view(NULL, view, KEY_UP);
3756 if (err)
3757 return err;
3758 cur--;
3762 s->search_entry = NULL;
3764 return NULL;
3767 static const struct got_error *
3768 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3769 struct got_repository *repo, const char *head_ref_name,
3770 const char *in_repo_path, int log_branches,
3771 struct got_worktree *worktree)
3773 const struct got_error *err = NULL;
3774 struct tog_log_view_state *s = &view->state.log;
3775 struct got_repository *thread_repo = NULL;
3776 struct got_commit_graph *thread_graph = NULL;
3777 int errcode;
3779 if (in_repo_path != s->in_repo_path) {
3780 free(s->in_repo_path);
3781 s->in_repo_path = strdup(in_repo_path);
3782 if (s->in_repo_path == NULL) {
3783 err = got_error_from_errno("strdup");
3784 goto done;
3788 /* The commit queue only contains commits being displayed. */
3789 TAILQ_INIT(&s->real_commits.head);
3790 s->real_commits.ncommits = 0;
3791 s->commits = &s->real_commits;
3793 TAILQ_INIT(&s->limit_commits.head);
3794 s->limit_view = 0;
3795 s->limit_commits.ncommits = 0;
3797 s->repo = repo;
3798 if (head_ref_name) {
3799 s->head_ref_name = strdup(head_ref_name);
3800 if (s->head_ref_name == NULL) {
3801 err = got_error_from_errno("strdup");
3802 goto done;
3805 s->start_id = got_object_id_dup(start_id);
3806 if (s->start_id == NULL) {
3807 err = got_error_from_errno("got_object_id_dup");
3808 goto done;
3810 s->log_branches = log_branches;
3811 s->use_committer = 1;
3813 STAILQ_INIT(&s->colors);
3814 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3815 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3816 get_color_value("TOG_COLOR_COMMIT"));
3817 if (err)
3818 goto done;
3819 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3820 get_color_value("TOG_COLOR_AUTHOR"));
3821 if (err) {
3822 free_colors(&s->colors);
3823 goto done;
3825 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3826 get_color_value("TOG_COLOR_DATE"));
3827 if (err) {
3828 free_colors(&s->colors);
3829 goto done;
3833 view->show = show_log_view;
3834 view->input = input_log_view;
3835 view->resize = resize_log_view;
3836 view->close = close_log_view;
3837 view->search_start = search_start_log_view;
3838 view->search_next = search_next_log_view;
3840 if (s->thread_args.pack_fds == NULL) {
3841 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3842 if (err)
3843 goto done;
3845 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3846 s->thread_args.pack_fds);
3847 if (err)
3848 goto done;
3849 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3850 !s->log_branches);
3851 if (err)
3852 goto done;
3853 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3854 s->repo, NULL, NULL);
3855 if (err)
3856 goto done;
3858 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3859 if (errcode) {
3860 err = got_error_set_errno(errcode, "pthread_cond_init");
3861 goto done;
3863 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3864 if (errcode) {
3865 err = got_error_set_errno(errcode, "pthread_cond_init");
3866 goto done;
3869 if (using_mock_io) {
3870 int rc;
3872 rc = pthread_cond_init(&s->thread_args.log_loaded, NULL);
3873 if (rc)
3874 return got_error_set_errno(rc, "pthread_cond_init");
3877 s->thread_args.commits_needed = view->nlines;
3878 s->thread_args.graph = thread_graph;
3879 s->thread_args.real_commits = &s->real_commits;
3880 s->thread_args.limit_commits = &s->limit_commits;
3881 s->thread_args.in_repo_path = s->in_repo_path;
3882 s->thread_args.start_id = s->start_id;
3883 s->thread_args.repo = thread_repo;
3884 s->thread_args.log_complete = 0;
3885 s->thread_args.quit = &s->quit;
3886 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3887 s->thread_args.selected_entry = &s->selected_entry;
3888 s->thread_args.searching = &view->searching;
3889 s->thread_args.search_next_done = &view->search_next_done;
3890 s->thread_args.regex = &view->regex;
3891 s->thread_args.limiting = &s->limit_view;
3892 s->thread_args.limit_regex = &s->limit_regex;
3893 s->thread_args.limit_commits = &s->limit_commits;
3894 s->thread_args.worktree = worktree;
3895 if (worktree)
3896 s->thread_args.need_commit_marker = 1;
3897 done:
3898 if (err) {
3899 if (view->close == NULL)
3900 close_log_view(view);
3901 view_close(view);
3903 return err;
3906 static const struct got_error *
3907 show_log_view(struct tog_view *view)
3909 const struct got_error *err;
3910 struct tog_log_view_state *s = &view->state.log;
3912 if (s->thread == NULL) {
3913 int errcode = pthread_create(&s->thread, NULL, log_thread,
3914 &s->thread_args);
3915 if (errcode)
3916 return got_error_set_errno(errcode, "pthread_create");
3917 if (s->thread_args.commits_needed > 0) {
3918 err = trigger_log_thread(view, 1);
3919 if (err)
3920 return err;
3924 return draw_commits(view);
3927 static void
3928 log_move_cursor_up(struct tog_view *view, int page, int home)
3930 struct tog_log_view_state *s = &view->state.log;
3932 if (s->first_displayed_entry == NULL)
3933 return;
3934 if (s->selected_entry->idx == 0)
3935 view->count = 0;
3937 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3938 || home)
3939 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3941 if (!page && !home && s->selected > 0)
3942 --s->selected;
3943 else
3944 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3946 select_commit(s);
3947 return;
3950 static const struct got_error *
3951 log_move_cursor_down(struct tog_view *view, int page)
3953 struct tog_log_view_state *s = &view->state.log;
3954 const struct got_error *err = NULL;
3955 int eos = view->nlines - 2;
3957 if (s->first_displayed_entry == NULL)
3958 return NULL;
3960 if (s->thread_args.log_complete &&
3961 s->selected_entry->idx >= s->commits->ncommits - 1)
3962 return NULL;
3964 if (view_is_hsplit_top(view))
3965 --eos; /* border consumes the last line */
3967 if (!page) {
3968 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3969 ++s->selected;
3970 else
3971 err = log_scroll_down(view, 1);
3972 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3973 struct commit_queue_entry *entry;
3974 int n;
3976 s->selected = 0;
3977 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3978 s->last_displayed_entry = entry;
3979 for (n = 0; n <= eos; n++) {
3980 if (entry == NULL)
3981 break;
3982 s->first_displayed_entry = entry;
3983 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3985 if (n > 0)
3986 s->selected = n - 1;
3987 } else {
3988 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3989 s->thread_args.log_complete)
3990 s->selected += MIN(page,
3991 s->commits->ncommits - s->selected_entry->idx - 1);
3992 else
3993 err = log_scroll_down(view, page);
3995 if (err)
3996 return err;
3999 * We might necessarily overshoot in horizontal
4000 * splits; if so, select the last displayed commit.
4002 if (s->first_displayed_entry && s->last_displayed_entry) {
4003 s->selected = MIN(s->selected,
4004 s->last_displayed_entry->idx -
4005 s->first_displayed_entry->idx);
4008 select_commit(s);
4010 if (s->thread_args.log_complete &&
4011 s->selected_entry->idx == s->commits->ncommits - 1)
4012 view->count = 0;
4014 return NULL;
4017 static void
4018 view_get_split(struct tog_view *view, int *y, int *x)
4020 *x = 0;
4021 *y = 0;
4023 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
4024 if (view->child && view->child->resized_y)
4025 *y = view->child->resized_y;
4026 else if (view->resized_y)
4027 *y = view->resized_y;
4028 else
4029 *y = view_split_begin_y(view->lines);
4030 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
4031 if (view->child && view->child->resized_x)
4032 *x = view->child->resized_x;
4033 else if (view->resized_x)
4034 *x = view->resized_x;
4035 else
4036 *x = view_split_begin_x(view->begin_x);
4040 /* Split view horizontally at y and offset view->state->selected line. */
4041 static const struct got_error *
4042 view_init_hsplit(struct tog_view *view, int y)
4044 const struct got_error *err = NULL;
4046 view->nlines = y;
4047 view->ncols = COLS;
4048 err = view_resize(view);
4049 if (err)
4050 return err;
4052 err = offset_selection_down(view);
4054 return err;
4057 static const struct got_error *
4058 log_goto_line(struct tog_view *view, int nlines)
4060 const struct got_error *err = NULL;
4061 struct tog_log_view_state *s = &view->state.log;
4062 int g, idx = s->selected_entry->idx;
4064 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
4065 return NULL;
4067 g = view->gline;
4068 view->gline = 0;
4070 if (g >= s->first_displayed_entry->idx + 1 &&
4071 g <= s->last_displayed_entry->idx + 1 &&
4072 g - s->first_displayed_entry->idx - 1 < nlines) {
4073 s->selected = g - s->first_displayed_entry->idx - 1;
4074 select_commit(s);
4075 return NULL;
4078 if (idx + 1 < g) {
4079 err = log_move_cursor_down(view, g - idx - 1);
4080 if (!err && g > s->selected_entry->idx + 1)
4081 err = log_move_cursor_down(view,
4082 g - s->first_displayed_entry->idx - 1);
4083 if (err)
4084 return err;
4085 } else if (idx + 1 > g)
4086 log_move_cursor_up(view, idx - g + 1, 0);
4088 if (g < nlines && s->first_displayed_entry->idx == 0)
4089 s->selected = g - 1;
4091 select_commit(s);
4092 return NULL;
4096 static void
4097 horizontal_scroll_input(struct tog_view *view, int ch)
4100 switch (ch) {
4101 case KEY_LEFT:
4102 case 'h':
4103 view->x -= MIN(view->x, 2);
4104 if (view->x <= 0)
4105 view->count = 0;
4106 break;
4107 case KEY_RIGHT:
4108 case 'l':
4109 if (view->x + view->ncols / 2 < view->maxx)
4110 view->x += 2;
4111 else
4112 view->count = 0;
4113 break;
4114 case '0':
4115 view->x = 0;
4116 break;
4117 case '$':
4118 view->x = MAX(view->maxx - view->ncols / 2, 0);
4119 view->count = 0;
4120 break;
4121 default:
4122 break;
4126 static const struct got_error *
4127 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4129 const struct got_error *err = NULL;
4130 struct tog_log_view_state *s = &view->state.log;
4131 int eos, nscroll;
4133 if (s->thread_args.load_all) {
4134 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4135 s->thread_args.load_all = 0;
4136 else if (s->thread_args.log_complete) {
4137 err = log_move_cursor_down(view, s->commits->ncommits);
4138 s->thread_args.load_all = 0;
4140 if (err)
4141 return err;
4144 eos = nscroll = view->nlines - 1;
4145 if (view_is_hsplit_top(view))
4146 --eos; /* border */
4148 if (view->gline)
4149 return log_goto_line(view, eos);
4151 switch (ch) {
4152 case '&':
4153 err = limit_log_view(view);
4154 break;
4155 case 'q':
4156 s->quit = 1;
4157 break;
4158 case '0':
4159 case '$':
4160 case KEY_RIGHT:
4161 case 'l':
4162 case KEY_LEFT:
4163 case 'h':
4164 horizontal_scroll_input(view, ch);
4165 break;
4166 case 'k':
4167 case KEY_UP:
4168 case '<':
4169 case ',':
4170 case CTRL('p'):
4171 log_move_cursor_up(view, 0, 0);
4172 break;
4173 case 'g':
4174 case '=':
4175 case KEY_HOME:
4176 log_move_cursor_up(view, 0, 1);
4177 view->count = 0;
4178 break;
4179 case CTRL('u'):
4180 case 'u':
4181 nscroll /= 2;
4182 /* FALL THROUGH */
4183 case KEY_PPAGE:
4184 case CTRL('b'):
4185 case 'b':
4186 log_move_cursor_up(view, nscroll, 0);
4187 break;
4188 case 'j':
4189 case KEY_DOWN:
4190 case '>':
4191 case '.':
4192 case CTRL('n'):
4193 err = log_move_cursor_down(view, 0);
4194 break;
4195 case '@':
4196 s->use_committer = !s->use_committer;
4197 view->action = s->use_committer ?
4198 "show committer" : "show commit author";
4199 break;
4200 case 'G':
4201 case '*':
4202 case KEY_END: {
4203 /* We don't know yet how many commits, so we're forced to
4204 * traverse them all. */
4205 view->count = 0;
4206 s->thread_args.load_all = 1;
4207 if (!s->thread_args.log_complete)
4208 return trigger_log_thread(view, 0);
4209 err = log_move_cursor_down(view, s->commits->ncommits);
4210 s->thread_args.load_all = 0;
4211 break;
4213 case CTRL('d'):
4214 case 'd':
4215 nscroll /= 2;
4216 /* FALL THROUGH */
4217 case KEY_NPAGE:
4218 case CTRL('f'):
4219 case 'f':
4220 case ' ':
4221 err = log_move_cursor_down(view, nscroll);
4222 break;
4223 case KEY_RESIZE:
4224 if (s->selected > view->nlines - 2)
4225 s->selected = view->nlines - 2;
4226 if (s->selected > s->commits->ncommits - 1)
4227 s->selected = s->commits->ncommits - 1;
4228 select_commit(s);
4229 if (s->commits->ncommits < view->nlines - 1 &&
4230 !s->thread_args.log_complete) {
4231 s->thread_args.commits_needed += (view->nlines - 1) -
4232 s->commits->ncommits;
4233 err = trigger_log_thread(view, 1);
4235 break;
4236 case KEY_ENTER:
4237 case '\r':
4238 view->count = 0;
4239 if (s->selected_entry == NULL)
4240 break;
4241 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4242 break;
4243 case 'T':
4244 view->count = 0;
4245 if (s->selected_entry == NULL)
4246 break;
4247 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4248 break;
4249 case KEY_BACKSPACE:
4250 case CTRL('l'):
4251 case 'B':
4252 view->count = 0;
4253 if (ch == KEY_BACKSPACE &&
4254 got_path_is_root_dir(s->in_repo_path))
4255 break;
4256 err = stop_log_thread(s);
4257 if (err)
4258 return err;
4259 if (ch == KEY_BACKSPACE) {
4260 char *parent_path;
4261 err = got_path_dirname(&parent_path, s->in_repo_path);
4262 if (err)
4263 return err;
4264 free(s->in_repo_path);
4265 s->in_repo_path = parent_path;
4266 s->thread_args.in_repo_path = s->in_repo_path;
4267 } else if (ch == CTRL('l')) {
4268 struct got_object_id *start_id;
4269 err = got_repo_match_object_id(&start_id, NULL,
4270 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4271 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4272 if (err) {
4273 if (s->head_ref_name == NULL ||
4274 err->code != GOT_ERR_NOT_REF)
4275 return err;
4276 /* Try to cope with deleted references. */
4277 free(s->head_ref_name);
4278 s->head_ref_name = NULL;
4279 err = got_repo_match_object_id(&start_id,
4280 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4281 &tog_refs, s->repo);
4282 if (err)
4283 return err;
4285 free(s->start_id);
4286 s->start_id = start_id;
4287 s->thread_args.start_id = s->start_id;
4288 } else /* 'B' */
4289 s->log_branches = !s->log_branches;
4291 if (s->thread_args.pack_fds == NULL) {
4292 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4293 if (err)
4294 return err;
4296 err = got_repo_open(&s->thread_args.repo,
4297 got_repo_get_path(s->repo), NULL,
4298 s->thread_args.pack_fds);
4299 if (err)
4300 return err;
4301 tog_free_refs();
4302 err = tog_load_refs(s->repo, 0);
4303 if (err)
4304 return err;
4305 err = got_commit_graph_open(&s->thread_args.graph,
4306 s->in_repo_path, !s->log_branches);
4307 if (err)
4308 return err;
4309 err = got_commit_graph_iter_start(s->thread_args.graph,
4310 s->start_id, s->repo, NULL, NULL);
4311 if (err)
4312 return err;
4313 free_commits(&s->real_commits);
4314 free_commits(&s->limit_commits);
4315 s->first_displayed_entry = NULL;
4316 s->last_displayed_entry = NULL;
4317 s->selected_entry = NULL;
4318 s->selected = 0;
4319 s->thread_args.log_complete = 0;
4320 s->quit = 0;
4321 s->thread_args.commits_needed = view->lines;
4322 s->matched_entry = NULL;
4323 s->search_entry = NULL;
4324 view->offset = 0;
4325 break;
4326 case 'R':
4327 view->count = 0;
4328 err = view_request_new(new_view, view, TOG_VIEW_REF);
4329 break;
4330 default:
4331 view->count = 0;
4332 break;
4335 return err;
4338 static const struct got_error *
4339 apply_unveil(const char *repo_path, const char *worktree_path)
4341 const struct got_error *error;
4343 #ifdef PROFILE
4344 if (unveil("gmon.out", "rwc") != 0)
4345 return got_error_from_errno2("unveil", "gmon.out");
4346 #endif
4347 if (repo_path && unveil(repo_path, "r") != 0)
4348 return got_error_from_errno2("unveil", repo_path);
4350 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4351 return got_error_from_errno2("unveil", worktree_path);
4353 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4354 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4356 error = got_privsep_unveil_exec_helpers();
4357 if (error != NULL)
4358 return error;
4360 if (unveil(NULL, NULL) != 0)
4361 return got_error_from_errno("unveil");
4363 return NULL;
4366 static const struct got_error *
4367 init_mock_term(const char *test_script_path)
4369 const struct got_error *err = NULL;
4370 const char *screen_dump_path;
4371 int in;
4373 if (test_script_path == NULL || *test_script_path == '\0')
4374 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4376 tog_io.f = fopen(test_script_path, "re");
4377 if (tog_io.f == NULL) {
4378 err = got_error_from_errno_fmt("fopen: %s",
4379 test_script_path);
4380 goto done;
4383 /* test mode, we don't want any output */
4384 tog_io.cout = fopen("/dev/null", "w+");
4385 if (tog_io.cout == NULL) {
4386 err = got_error_from_errno2("fopen", "/dev/null");
4387 goto done;
4390 in = dup(fileno(tog_io.cout));
4391 if (in == -1) {
4392 err = got_error_from_errno("dup");
4393 goto done;
4395 tog_io.cin = fdopen(in, "r");
4396 if (tog_io.cin == NULL) {
4397 err = got_error_from_errno("fdopen");
4398 close(in);
4399 goto done;
4402 screen_dump_path = getenv("TOG_SCR_DUMP");
4403 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4404 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4405 tog_io.sdump = fopen(screen_dump_path, "we");
4406 if (tog_io.sdump == NULL) {
4407 err = got_error_from_errno2("fopen", screen_dump_path);
4408 goto done;
4411 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4412 err = got_error_from_errno("fseeko");
4413 goto done;
4416 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4417 err = got_error_msg(GOT_ERR_IO,
4418 "newterm: failed to initialise curses");
4420 using_mock_io = 1;
4422 done:
4423 if (err)
4424 tog_io_close();
4425 return err;
4428 static void
4429 init_curses(void)
4431 if (using_mock_io) /* In test mode we use a fake terminal */
4432 return;
4434 initscr();
4436 cbreak();
4437 halfdelay(1); /* Fast refresh while initial view is loading. */
4438 noecho();
4439 nonl();
4440 intrflush(stdscr, FALSE);
4441 keypad(stdscr, TRUE);
4442 curs_set(0);
4443 if (getenv("TOG_COLORS") != NULL) {
4444 start_color();
4445 use_default_colors();
4448 return;
4451 static const struct got_error *
4452 set_tog_base_commit(struct got_repository *repo, struct got_worktree *worktree)
4454 tog_base_commit.id = got_object_id_dup(
4455 got_worktree_get_base_commit_id(worktree));
4456 if (tog_base_commit.id == NULL)
4457 return got_error_from_errno( "got_object_id_dup");
4459 return NULL;
4462 static const struct got_error *
4463 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4464 struct got_repository *repo, struct got_worktree *worktree)
4466 const struct got_error *err = NULL;
4468 if (argc == 0) {
4469 *in_repo_path = strdup("/");
4470 if (*in_repo_path == NULL)
4471 return got_error_from_errno("strdup");
4472 return NULL;
4475 if (worktree) {
4476 const char *prefix = got_worktree_get_path_prefix(worktree);
4477 char *p;
4479 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4480 if (err)
4481 return err;
4482 if (asprintf(in_repo_path, "%s%s%s", prefix,
4483 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4484 p) == -1) {
4485 err = got_error_from_errno("asprintf");
4486 *in_repo_path = NULL;
4488 free(p);
4489 } else
4490 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4492 return err;
4495 static const struct got_error *
4496 cmd_log(int argc, char *argv[])
4498 const struct got_error *error;
4499 struct got_repository *repo = NULL;
4500 struct got_worktree *worktree = NULL;
4501 struct got_object_id *start_id = NULL;
4502 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4503 char *keyword_idstr = NULL, *start_commit = NULL, *label = NULL;
4504 struct got_reference *ref = NULL;
4505 const char *head_ref_name = NULL;
4506 int ch, log_branches = 0;
4507 struct tog_view *view;
4508 int *pack_fds = NULL;
4510 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4511 switch (ch) {
4512 case 'b':
4513 log_branches = 1;
4514 break;
4515 case 'c':
4516 start_commit = optarg;
4517 break;
4518 case 'r':
4519 repo_path = realpath(optarg, NULL);
4520 if (repo_path == NULL)
4521 return got_error_from_errno2("realpath",
4522 optarg);
4523 break;
4524 default:
4525 usage_log();
4526 /* NOTREACHED */
4530 argc -= optind;
4531 argv += optind;
4533 if (argc > 1)
4534 usage_log();
4536 error = got_repo_pack_fds_open(&pack_fds);
4537 if (error != NULL)
4538 goto done;
4540 if (repo_path == NULL) {
4541 cwd = getcwd(NULL, 0);
4542 if (cwd == NULL) {
4543 error = got_error_from_errno("getcwd");
4544 goto done;
4546 error = got_worktree_open(&worktree, cwd, NULL);
4547 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4548 goto done;
4549 if (worktree)
4550 repo_path =
4551 strdup(got_worktree_get_repo_path(worktree));
4552 else
4553 repo_path = strdup(cwd);
4554 if (repo_path == NULL) {
4555 error = got_error_from_errno("strdup");
4556 goto done;
4560 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4561 if (error != NULL)
4562 goto done;
4564 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4565 repo, worktree);
4566 if (error)
4567 goto done;
4569 init_curses();
4571 error = apply_unveil(got_repo_get_path(repo),
4572 worktree ? got_worktree_get_root_path(worktree) : NULL);
4573 if (error)
4574 goto done;
4576 /* already loaded by tog_log_with_path()? */
4577 if (TAILQ_EMPTY(&tog_refs)) {
4578 error = tog_load_refs(repo, 0);
4579 if (error)
4580 goto done;
4583 if (start_commit == NULL) {
4584 error = got_repo_match_object_id(&start_id, &label,
4585 worktree ? got_worktree_get_head_ref_name(worktree) :
4586 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4587 if (error)
4588 goto done;
4589 head_ref_name = label;
4590 } else {
4591 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4592 repo, worktree);
4593 if (error != NULL)
4594 goto done;
4595 if (keyword_idstr != NULL)
4596 start_commit = keyword_idstr;
4598 error = got_ref_open(&ref, repo, start_commit, 0);
4599 if (error == NULL)
4600 head_ref_name = got_ref_get_name(ref);
4601 else if (error->code != GOT_ERR_NOT_REF)
4602 goto done;
4603 error = got_repo_match_object_id(&start_id, NULL,
4604 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4605 if (error)
4606 goto done;
4609 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4610 if (view == NULL) {
4611 error = got_error_from_errno("view_open");
4612 goto done;
4615 if (worktree) {
4616 error = set_tog_base_commit(repo, worktree);
4617 if (error != NULL)
4618 goto done;
4621 error = open_log_view(view, start_id, repo, head_ref_name,
4622 in_repo_path, log_branches, worktree);
4623 if (error)
4624 goto done;
4626 if (worktree) {
4627 /* The work tree will be closed by the log thread. */
4628 worktree = NULL;
4631 error = view_loop(view);
4633 done:
4634 free(tog_base_commit.id);
4635 free(keyword_idstr);
4636 free(in_repo_path);
4637 free(repo_path);
4638 free(cwd);
4639 free(start_id);
4640 free(label);
4641 if (ref)
4642 got_ref_close(ref);
4643 if (repo) {
4644 const struct got_error *close_err = got_repo_close(repo);
4645 if (error == NULL)
4646 error = close_err;
4648 if (worktree)
4649 got_worktree_close(worktree);
4650 if (pack_fds) {
4651 const struct got_error *pack_err =
4652 got_repo_pack_fds_close(pack_fds);
4653 if (error == NULL)
4654 error = pack_err;
4656 tog_free_refs();
4657 return error;
4660 __dead static void
4661 usage_diff(void)
4663 endwin();
4664 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4665 "object1 object2\n", getprogname());
4666 exit(1);
4669 static int
4670 match_line(const char *line, regex_t *regex, size_t nmatch,
4671 regmatch_t *regmatch)
4673 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4676 static struct tog_color *
4677 match_color(struct tog_colors *colors, const char *line)
4679 struct tog_color *tc = NULL;
4681 STAILQ_FOREACH(tc, colors, entry) {
4682 if (match_line(line, &tc->regex, 0, NULL))
4683 return tc;
4686 return NULL;
4689 static const struct got_error *
4690 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4691 WINDOW *window, int skipcol, regmatch_t *regmatch)
4693 const struct got_error *err = NULL;
4694 char *exstr = NULL;
4695 wchar_t *wline = NULL;
4696 int rme, rms, n, width, scrollx;
4697 int width0 = 0, width1 = 0, width2 = 0;
4698 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4700 *wtotal = 0;
4702 rms = regmatch->rm_so;
4703 rme = regmatch->rm_eo;
4705 err = expand_tab(&exstr, line);
4706 if (err)
4707 return err;
4709 /* Split the line into 3 segments, according to match offsets. */
4710 seg0 = strndup(exstr, rms);
4711 if (seg0 == NULL) {
4712 err = got_error_from_errno("strndup");
4713 goto done;
4715 seg1 = strndup(exstr + rms, rme - rms);
4716 if (seg1 == NULL) {
4717 err = got_error_from_errno("strndup");
4718 goto done;
4720 seg2 = strdup(exstr + rme);
4721 if (seg2 == NULL) {
4722 err = got_error_from_errno("strndup");
4723 goto done;
4726 /* draw up to matched token if we haven't scrolled past it */
4727 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4728 col_tab_align, 1);
4729 if (err)
4730 goto done;
4731 n = MAX(width0 - skipcol, 0);
4732 if (n) {
4733 free(wline);
4734 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4735 wlimit, col_tab_align, 1);
4736 if (err)
4737 goto done;
4738 waddwstr(window, &wline[scrollx]);
4739 wlimit -= width;
4740 *wtotal += width;
4743 if (wlimit > 0) {
4744 int i = 0, w = 0;
4745 size_t wlen;
4747 free(wline);
4748 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4749 col_tab_align, 1);
4750 if (err)
4751 goto done;
4752 wlen = wcslen(wline);
4753 while (i < wlen) {
4754 width = wcwidth(wline[i]);
4755 if (width == -1) {
4756 /* should not happen, tabs are expanded */
4757 err = got_error(GOT_ERR_RANGE);
4758 goto done;
4760 if (width0 + w + width > skipcol)
4761 break;
4762 w += width;
4763 i++;
4765 /* draw (visible part of) matched token (if scrolled into it) */
4766 if (width1 - w > 0) {
4767 wattron(window, A_STANDOUT);
4768 waddwstr(window, &wline[i]);
4769 wattroff(window, A_STANDOUT);
4770 wlimit -= (width1 - w);
4771 *wtotal += (width1 - w);
4775 if (wlimit > 0) { /* draw rest of line */
4776 free(wline);
4777 if (skipcol > width0 + width1) {
4778 err = format_line(&wline, &width2, &scrollx, seg2,
4779 skipcol - (width0 + width1), wlimit,
4780 col_tab_align, 1);
4781 if (err)
4782 goto done;
4783 waddwstr(window, &wline[scrollx]);
4784 } else {
4785 err = format_line(&wline, &width2, NULL, seg2, 0,
4786 wlimit, col_tab_align, 1);
4787 if (err)
4788 goto done;
4789 waddwstr(window, wline);
4791 *wtotal += width2;
4793 done:
4794 free(wline);
4795 free(exstr);
4796 free(seg0);
4797 free(seg1);
4798 free(seg2);
4799 return err;
4802 static int
4803 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4805 FILE *f = NULL;
4806 int *eof, *first, *selected;
4808 if (view->type == TOG_VIEW_DIFF) {
4809 struct tog_diff_view_state *s = &view->state.diff;
4811 first = &s->first_displayed_line;
4812 selected = first;
4813 eof = &s->eof;
4814 f = s->f;
4815 } else if (view->type == TOG_VIEW_HELP) {
4816 struct tog_help_view_state *s = &view->state.help;
4818 first = &s->first_displayed_line;
4819 selected = first;
4820 eof = &s->eof;
4821 f = s->f;
4822 } else if (view->type == TOG_VIEW_BLAME) {
4823 struct tog_blame_view_state *s = &view->state.blame;
4825 first = &s->first_displayed_line;
4826 selected = &s->selected_line;
4827 eof = &s->eof;
4828 f = s->blame.f;
4829 } else
4830 return 0;
4832 /* Center gline in the middle of the page like vi(1). */
4833 if (*lineno < view->gline - (view->nlines - 3) / 2)
4834 return 0;
4835 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4836 rewind(f);
4837 *eof = 0;
4838 *first = 1;
4839 *lineno = 0;
4840 *nprinted = 0;
4841 return 0;
4844 *selected = view->gline <= (view->nlines - 3) / 2 ?
4845 view->gline : (view->nlines - 3) / 2 + 1;
4846 view->gline = 0;
4848 return 1;
4851 static const struct got_error *
4852 draw_file(struct tog_view *view, const char *header)
4854 struct tog_diff_view_state *s = &view->state.diff;
4855 regmatch_t *regmatch = &view->regmatch;
4856 const struct got_error *err;
4857 int nprinted = 0;
4858 char *line;
4859 size_t linesize = 0;
4860 ssize_t linelen;
4861 wchar_t *wline;
4862 int width;
4863 int max_lines = view->nlines;
4864 int nlines = s->nlines;
4865 off_t line_offset;
4867 s->lineno = s->first_displayed_line - 1;
4868 line_offset = s->lines[s->first_displayed_line - 1].offset;
4869 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4870 return got_error_from_errno("fseek");
4872 werase(view->window);
4874 if (view->gline > s->nlines - 1)
4875 view->gline = s->nlines - 1;
4877 if (header) {
4878 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4879 1 : view->gline - (view->nlines - 3) / 2 :
4880 s->lineno + s->selected_line;
4882 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4883 return got_error_from_errno("asprintf");
4884 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4885 0, 0);
4886 free(line);
4887 if (err)
4888 return err;
4890 if (view_needs_focus_indication(view))
4891 wstandout(view->window);
4892 waddwstr(view->window, wline);
4893 free(wline);
4894 wline = NULL;
4895 while (width++ < view->ncols)
4896 waddch(view->window, ' ');
4897 if (view_needs_focus_indication(view))
4898 wstandend(view->window);
4900 if (max_lines <= 1)
4901 return NULL;
4902 max_lines--;
4905 s->eof = 0;
4906 view->maxx = 0;
4907 line = NULL;
4908 while (max_lines > 0 && nprinted < max_lines) {
4909 enum got_diff_line_type linetype;
4910 attr_t attr = 0;
4912 linelen = getline(&line, &linesize, s->f);
4913 if (linelen == -1) {
4914 if (feof(s->f)) {
4915 s->eof = 1;
4916 break;
4918 free(line);
4919 return got_ferror(s->f, GOT_ERR_IO);
4922 if (++s->lineno < s->first_displayed_line)
4923 continue;
4924 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4925 continue;
4926 if (s->lineno == view->hiline)
4927 attr = A_STANDOUT;
4929 /* Set view->maxx based on full line length. */
4930 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4931 view->x ? 1 : 0);
4932 if (err) {
4933 free(line);
4934 return err;
4936 view->maxx = MAX(view->maxx, width);
4937 free(wline);
4938 wline = NULL;
4940 linetype = s->lines[s->lineno].type;
4941 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4942 linetype < GOT_DIFF_LINE_CONTEXT)
4943 attr |= COLOR_PAIR(linetype);
4944 if (attr)
4945 wattron(view->window, attr);
4946 if (s->first_displayed_line + nprinted == s->matched_line &&
4947 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4948 err = add_matched_line(&width, line, view->ncols, 0,
4949 view->window, view->x, regmatch);
4950 if (err) {
4951 free(line);
4952 return err;
4954 } else {
4955 int skip;
4956 err = format_line(&wline, &width, &skip, line,
4957 view->x, view->ncols, 0, view->x ? 1 : 0);
4958 if (err) {
4959 free(line);
4960 return err;
4962 waddwstr(view->window, &wline[skip]);
4963 free(wline);
4964 wline = NULL;
4966 if (s->lineno == view->hiline) {
4967 /* highlight full gline length */
4968 while (width++ < view->ncols)
4969 waddch(view->window, ' ');
4970 } else {
4971 if (width <= view->ncols - 1)
4972 waddch(view->window, '\n');
4974 if (attr)
4975 wattroff(view->window, attr);
4976 if (++nprinted == 1)
4977 s->first_displayed_line = s->lineno;
4979 free(line);
4980 if (nprinted >= 1)
4981 s->last_displayed_line = s->first_displayed_line +
4982 (nprinted - 1);
4983 else
4984 s->last_displayed_line = s->first_displayed_line;
4986 view_border(view);
4988 if (s->eof) {
4989 while (nprinted < view->nlines) {
4990 waddch(view->window, '\n');
4991 nprinted++;
4994 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4995 view->ncols, 0, 0);
4996 if (err) {
4997 return err;
5000 wstandout(view->window);
5001 waddwstr(view->window, wline);
5002 free(wline);
5003 wline = NULL;
5004 wstandend(view->window);
5007 return NULL;
5010 static char *
5011 get_datestr(time_t *time, char *datebuf)
5013 struct tm mytm, *tm;
5014 char *p, *s;
5016 tm = gmtime_r(time, &mytm);
5017 if (tm == NULL)
5018 return NULL;
5019 s = asctime_r(tm, datebuf);
5020 if (s == NULL)
5021 return NULL;
5022 p = strchr(s, '\n');
5023 if (p)
5024 *p = '\0';
5025 return s;
5028 static const struct got_error *
5029 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
5030 off_t off, uint8_t type)
5032 struct got_diff_line *p;
5034 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
5035 if (p == NULL)
5036 return got_error_from_errno("reallocarray");
5037 *lines = p;
5038 (*lines)[*nlines].offset = off;
5039 (*lines)[*nlines].type = type;
5040 (*nlines)++;
5042 return NULL;
5045 static const struct got_error *
5046 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
5047 struct got_diff_line *s_lines, size_t s_nlines)
5049 struct got_diff_line *p;
5050 char buf[BUFSIZ];
5051 size_t i, r;
5053 if (fseeko(src, 0L, SEEK_SET) == -1)
5054 return got_error_from_errno("fseeko");
5056 for (;;) {
5057 r = fread(buf, 1, sizeof(buf), src);
5058 if (r == 0) {
5059 if (ferror(src))
5060 return got_error_from_errno("fread");
5061 if (feof(src))
5062 break;
5064 if (fwrite(buf, 1, r, dst) != r)
5065 return got_ferror(dst, GOT_ERR_IO);
5068 if (s_nlines == 0 && *d_nlines == 0)
5069 return NULL;
5072 * If commit info was in dst, increment line offsets
5073 * of the appended diff content, but skip s_lines[0]
5074 * because offset zero is already in *d_lines.
5076 if (*d_nlines > 0) {
5077 for (i = 1; i < s_nlines; ++i)
5078 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
5080 if (s_nlines > 0) {
5081 --s_nlines;
5082 ++s_lines;
5086 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
5087 if (p == NULL) {
5088 /* d_lines is freed in close_diff_view() */
5089 return got_error_from_errno("reallocarray");
5092 *d_lines = p;
5094 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
5095 *d_nlines += s_nlines;
5097 return NULL;
5100 static const struct got_error *
5101 write_commit_info(struct got_diff_line **lines, size_t *nlines,
5102 struct got_object_id *commit_id, struct got_reflist_head *refs,
5103 struct got_repository *repo, int ignore_ws, int force_text_diff,
5104 struct got_diffstat_cb_arg *dsa, FILE *outfile)
5106 const struct got_error *err = NULL;
5107 char datebuf[26], *datestr;
5108 struct got_commit_object *commit;
5109 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
5110 time_t committer_time;
5111 const char *author, *committer;
5112 char *refs_str = NULL;
5113 struct got_pathlist_entry *pe;
5114 off_t outoff = 0;
5115 int n;
5117 err = build_refs_str(&refs_str, refs, commit_id, repo);
5118 if (err)
5119 return err;
5121 err = got_object_open_as_commit(&commit, repo, commit_id);
5122 if (err)
5123 return err;
5125 err = got_object_id_str(&id_str, commit_id);
5126 if (err) {
5127 err = got_error_from_errno("got_object_id_str");
5128 goto done;
5131 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
5132 if (err)
5133 goto done;
5135 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
5136 refs_str ? refs_str : "", refs_str ? ")" : "");
5137 if (n < 0) {
5138 err = got_error_from_errno("fprintf");
5139 goto done;
5141 outoff += n;
5142 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
5143 if (err)
5144 goto done;
5146 n = fprintf(outfile, "from: %s\n",
5147 got_object_commit_get_author(commit));
5148 if (n < 0) {
5149 err = got_error_from_errno("fprintf");
5150 goto done;
5152 outoff += n;
5153 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5154 if (err)
5155 goto done;
5157 author = got_object_commit_get_author(commit);
5158 committer = got_object_commit_get_committer(commit);
5159 if (strcmp(author, committer) != 0) {
5160 n = fprintf(outfile, "via: %s\n", committer);
5161 if (n < 0) {
5162 err = got_error_from_errno("fprintf");
5163 goto done;
5165 outoff += n;
5166 err = add_line_metadata(lines, nlines, outoff,
5167 GOT_DIFF_LINE_AUTHOR);
5168 if (err)
5169 goto done;
5171 committer_time = got_object_commit_get_committer_time(commit);
5172 datestr = get_datestr(&committer_time, datebuf);
5173 if (datestr) {
5174 n = fprintf(outfile, "date: %s UTC\n", datestr);
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,
5181 GOT_DIFF_LINE_DATE);
5182 if (err)
5183 goto done;
5185 if (got_object_commit_get_nparents(commit) > 1) {
5186 const struct got_object_id_queue *parent_ids;
5187 struct got_object_qid *qid;
5188 int pn = 1;
5189 parent_ids = got_object_commit_get_parent_ids(commit);
5190 STAILQ_FOREACH(qid, parent_ids, entry) {
5191 err = got_object_id_str(&id_str, &qid->id);
5192 if (err)
5193 goto done;
5194 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5195 if (n < 0) {
5196 err = got_error_from_errno("fprintf");
5197 goto done;
5199 outoff += n;
5200 err = add_line_metadata(lines, nlines, outoff,
5201 GOT_DIFF_LINE_META);
5202 if (err)
5203 goto done;
5204 free(id_str);
5205 id_str = NULL;
5209 err = got_object_commit_get_logmsg(&logmsg, commit);
5210 if (err)
5211 goto done;
5212 s = logmsg;
5213 while ((line = strsep(&s, "\n")) != NULL) {
5214 n = fprintf(outfile, "%s\n", line);
5215 if (n < 0) {
5216 err = got_error_from_errno("fprintf");
5217 goto done;
5219 outoff += n;
5220 err = add_line_metadata(lines, nlines, outoff,
5221 GOT_DIFF_LINE_LOGMSG);
5222 if (err)
5223 goto done;
5226 TAILQ_FOREACH(pe, dsa->paths, entry) {
5227 struct got_diff_changed_path *cp = pe->data;
5228 int pad = dsa->max_path_len - pe->path_len + 1;
5230 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5231 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5232 dsa->rm_cols + 1, cp->rm);
5233 if (n < 0) {
5234 err = got_error_from_errno("fprintf");
5235 goto done;
5237 outoff += n;
5238 err = add_line_metadata(lines, nlines, outoff,
5239 GOT_DIFF_LINE_CHANGES);
5240 if (err)
5241 goto done;
5244 fputc('\n', outfile);
5245 outoff++;
5246 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5247 if (err)
5248 goto done;
5250 n = fprintf(outfile,
5251 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5252 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5253 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5254 if (n < 0) {
5255 err = got_error_from_errno("fprintf");
5256 goto done;
5258 outoff += n;
5259 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5260 if (err)
5261 goto done;
5263 fputc('\n', outfile);
5264 outoff++;
5265 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5266 done:
5267 free(id_str);
5268 free(logmsg);
5269 free(refs_str);
5270 got_object_commit_close(commit);
5271 if (err) {
5272 free(*lines);
5273 *lines = NULL;
5274 *nlines = 0;
5276 return err;
5279 static const struct got_error *
5280 create_diff(struct tog_diff_view_state *s)
5282 const struct got_error *err = NULL;
5283 FILE *f = NULL, *tmp_diff_file = NULL;
5284 int obj_type;
5285 struct got_diff_line *lines = NULL;
5286 struct got_pathlist_head changed_paths;
5288 TAILQ_INIT(&changed_paths);
5290 free(s->lines);
5291 s->lines = malloc(sizeof(*s->lines));
5292 if (s->lines == NULL)
5293 return got_error_from_errno("malloc");
5294 s->nlines = 0;
5296 f = got_opentemp();
5297 if (f == NULL) {
5298 err = got_error_from_errno("got_opentemp");
5299 goto done;
5301 tmp_diff_file = got_opentemp();
5302 if (tmp_diff_file == NULL) {
5303 err = got_error_from_errno("got_opentemp");
5304 goto done;
5306 if (s->f && fclose(s->f) == EOF) {
5307 err = got_error_from_errno("fclose");
5308 goto done;
5310 s->f = f;
5312 if (s->id1)
5313 err = got_object_get_type(&obj_type, s->repo, s->id1);
5314 else
5315 err = got_object_get_type(&obj_type, s->repo, s->id2);
5316 if (err)
5317 goto done;
5319 switch (obj_type) {
5320 case GOT_OBJ_TYPE_BLOB:
5321 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5322 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5323 s->label1, s->label2, tog_diff_algo, s->diff_context,
5324 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5325 s->f);
5326 break;
5327 case GOT_OBJ_TYPE_TREE:
5328 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5329 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5330 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5331 s->force_text_diff, NULL, s->repo, s->f);
5332 break;
5333 case GOT_OBJ_TYPE_COMMIT: {
5334 const struct got_object_id_queue *parent_ids;
5335 struct got_object_qid *pid;
5336 struct got_commit_object *commit2;
5337 struct got_reflist_head *refs;
5338 size_t nlines = 0;
5339 struct got_diffstat_cb_arg dsa = {
5340 0, 0, 0, 0, 0, 0,
5341 &changed_paths,
5342 s->ignore_whitespace,
5343 s->force_text_diff,
5344 tog_diff_algo
5347 lines = malloc(sizeof(*lines));
5348 if (lines == NULL) {
5349 err = got_error_from_errno("malloc");
5350 goto done;
5353 /* build diff first in tmp file then append to commit info */
5354 err = got_diff_objects_as_commits(&lines, &nlines,
5355 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5356 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5357 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5358 if (err)
5359 break;
5361 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5362 if (err)
5363 goto done;
5364 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5365 /* Show commit info if we're diffing to a parent/root commit. */
5366 if (s->id1 == NULL) {
5367 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5368 refs, s->repo, s->ignore_whitespace,
5369 s->force_text_diff, &dsa, s->f);
5370 if (err)
5371 goto done;
5372 } else {
5373 parent_ids = got_object_commit_get_parent_ids(commit2);
5374 STAILQ_FOREACH(pid, parent_ids, entry) {
5375 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5376 err = write_commit_info(&s->lines,
5377 &s->nlines, s->id2, refs, s->repo,
5378 s->ignore_whitespace,
5379 s->force_text_diff, &dsa, s->f);
5380 if (err)
5381 goto done;
5382 break;
5386 got_object_commit_close(commit2);
5388 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5389 lines, nlines);
5390 break;
5392 default:
5393 err = got_error(GOT_ERR_OBJ_TYPE);
5394 break;
5396 done:
5397 free(lines);
5398 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5399 if (s->f && fflush(s->f) != 0 && err == NULL)
5400 err = got_error_from_errno("fflush");
5401 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5402 err = got_error_from_errno("fclose");
5403 return err;
5406 static void
5407 diff_view_indicate_progress(struct tog_view *view)
5409 mvwaddstr(view->window, 0, 0, "diffing...");
5410 update_panels();
5411 doupdate();
5414 static const struct got_error *
5415 search_start_diff_view(struct tog_view *view)
5417 struct tog_diff_view_state *s = &view->state.diff;
5419 s->matched_line = 0;
5420 return NULL;
5423 static void
5424 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5425 size_t *nlines, int **first, int **last, int **match, int **selected)
5427 struct tog_diff_view_state *s = &view->state.diff;
5429 *f = s->f;
5430 *nlines = s->nlines;
5431 *line_offsets = NULL;
5432 *match = &s->matched_line;
5433 *first = &s->first_displayed_line;
5434 *last = &s->last_displayed_line;
5435 *selected = &s->selected_line;
5438 static const struct got_error *
5439 search_next_view_match(struct tog_view *view)
5441 const struct got_error *err = NULL;
5442 FILE *f;
5443 int lineno;
5444 char *line = NULL;
5445 size_t linesize = 0;
5446 ssize_t linelen;
5447 off_t *line_offsets;
5448 size_t nlines = 0;
5449 int *first, *last, *match, *selected;
5451 if (!view->search_setup)
5452 return got_error_msg(GOT_ERR_NOT_IMPL,
5453 "view search not supported");
5454 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5455 &match, &selected);
5457 if (!view->searching) {
5458 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5459 return NULL;
5462 if (*match) {
5463 if (view->searching == TOG_SEARCH_FORWARD)
5464 lineno = *first + 1;
5465 else
5466 lineno = *first - 1;
5467 } else
5468 lineno = *first - 1 + *selected;
5470 while (1) {
5471 off_t offset;
5473 if (lineno <= 0 || lineno > nlines) {
5474 if (*match == 0) {
5475 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5476 break;
5479 if (view->searching == TOG_SEARCH_FORWARD)
5480 lineno = 1;
5481 else
5482 lineno = nlines;
5485 offset = view->type == TOG_VIEW_DIFF ?
5486 view->state.diff.lines[lineno - 1].offset :
5487 line_offsets[lineno - 1];
5488 if (fseeko(f, offset, SEEK_SET) != 0) {
5489 free(line);
5490 return got_error_from_errno("fseeko");
5492 linelen = getline(&line, &linesize, f);
5493 if (linelen != -1) {
5494 char *exstr;
5495 err = expand_tab(&exstr, line);
5496 if (err)
5497 break;
5498 if (match_line(exstr, &view->regex, 1,
5499 &view->regmatch)) {
5500 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5501 *match = lineno;
5502 free(exstr);
5503 break;
5505 free(exstr);
5507 if (view->searching == TOG_SEARCH_FORWARD)
5508 lineno++;
5509 else
5510 lineno--;
5512 free(line);
5514 if (*match) {
5515 *first = *match;
5516 *selected = 1;
5519 return err;
5522 static const struct got_error *
5523 close_diff_view(struct tog_view *view)
5525 const struct got_error *err = NULL;
5526 struct tog_diff_view_state *s = &view->state.diff;
5528 free(s->id1);
5529 s->id1 = NULL;
5530 free(s->id2);
5531 s->id2 = NULL;
5532 if (s->f && fclose(s->f) == EOF)
5533 err = got_error_from_errno("fclose");
5534 s->f = NULL;
5535 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5536 err = got_error_from_errno("fclose");
5537 s->f1 = NULL;
5538 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5539 err = got_error_from_errno("fclose");
5540 s->f2 = NULL;
5541 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5542 err = got_error_from_errno("close");
5543 s->fd1 = -1;
5544 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5545 err = got_error_from_errno("close");
5546 s->fd2 = -1;
5547 free(s->lines);
5548 s->lines = NULL;
5549 s->nlines = 0;
5550 return err;
5553 static const struct got_error *
5554 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5555 struct got_object_id *id2, const char *label1, const char *label2,
5556 int diff_context, int ignore_whitespace, int force_text_diff,
5557 struct tog_view *parent_view, struct got_repository *repo)
5559 const struct got_error *err;
5560 struct tog_diff_view_state *s = &view->state.diff;
5562 memset(s, 0, sizeof(*s));
5563 s->fd1 = -1;
5564 s->fd2 = -1;
5566 if (id1 != NULL && id2 != NULL) {
5567 int type1, type2;
5569 err = got_object_get_type(&type1, repo, id1);
5570 if (err)
5571 goto done;
5572 err = got_object_get_type(&type2, repo, id2);
5573 if (err)
5574 goto done;
5576 if (type1 != type2) {
5577 err = got_error(GOT_ERR_OBJ_TYPE);
5578 goto done;
5581 s->first_displayed_line = 1;
5582 s->last_displayed_line = view->nlines;
5583 s->selected_line = 1;
5584 s->repo = repo;
5585 s->id1 = id1;
5586 s->id2 = id2;
5587 s->label1 = label1;
5588 s->label2 = label2;
5590 if (id1) {
5591 s->id1 = got_object_id_dup(id1);
5592 if (s->id1 == NULL) {
5593 err = got_error_from_errno("got_object_id_dup");
5594 goto done;
5596 } else
5597 s->id1 = NULL;
5599 s->id2 = got_object_id_dup(id2);
5600 if (s->id2 == NULL) {
5601 err = got_error_from_errno("got_object_id_dup");
5602 goto done;
5605 s->f1 = got_opentemp();
5606 if (s->f1 == NULL) {
5607 err = got_error_from_errno("got_opentemp");
5608 goto done;
5611 s->f2 = got_opentemp();
5612 if (s->f2 == NULL) {
5613 err = got_error_from_errno("got_opentemp");
5614 goto done;
5617 s->fd1 = got_opentempfd();
5618 if (s->fd1 == -1) {
5619 err = got_error_from_errno("got_opentempfd");
5620 goto done;
5623 s->fd2 = got_opentempfd();
5624 if (s->fd2 == -1) {
5625 err = got_error_from_errno("got_opentempfd");
5626 goto done;
5629 s->diff_context = diff_context;
5630 s->ignore_whitespace = ignore_whitespace;
5631 s->force_text_diff = force_text_diff;
5632 s->parent_view = parent_view;
5633 s->repo = repo;
5635 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5636 int rc;
5638 rc = init_pair(GOT_DIFF_LINE_MINUS,
5639 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5640 if (rc != ERR)
5641 rc = init_pair(GOT_DIFF_LINE_PLUS,
5642 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5643 if (rc != ERR)
5644 rc = init_pair(GOT_DIFF_LINE_HUNK,
5645 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5646 if (rc != ERR)
5647 rc = init_pair(GOT_DIFF_LINE_META,
5648 get_color_value("TOG_COLOR_DIFF_META"), -1);
5649 if (rc != ERR)
5650 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5651 get_color_value("TOG_COLOR_DIFF_META"), -1);
5652 if (rc != ERR)
5653 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5654 get_color_value("TOG_COLOR_DIFF_META"), -1);
5655 if (rc != ERR)
5656 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5657 get_color_value("TOG_COLOR_DIFF_META"), -1);
5658 if (rc != ERR)
5659 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5660 get_color_value("TOG_COLOR_AUTHOR"), -1);
5661 if (rc != ERR)
5662 rc = init_pair(GOT_DIFF_LINE_DATE,
5663 get_color_value("TOG_COLOR_DATE"), -1);
5664 if (rc == ERR) {
5665 err = got_error(GOT_ERR_RANGE);
5666 goto done;
5670 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5671 view_is_splitscreen(view))
5672 show_log_view(parent_view); /* draw border */
5673 diff_view_indicate_progress(view);
5675 err = create_diff(s);
5677 view->show = show_diff_view;
5678 view->input = input_diff_view;
5679 view->reset = reset_diff_view;
5680 view->close = close_diff_view;
5681 view->search_start = search_start_diff_view;
5682 view->search_setup = search_setup_diff_view;
5683 view->search_next = search_next_view_match;
5684 done:
5685 if (err) {
5686 if (view->close == NULL)
5687 close_diff_view(view);
5688 view_close(view);
5690 return err;
5693 static const struct got_error *
5694 show_diff_view(struct tog_view *view)
5696 const struct got_error *err;
5697 struct tog_diff_view_state *s = &view->state.diff;
5698 char *id_str1 = NULL, *id_str2, *header;
5699 const char *label1, *label2;
5701 if (s->id1) {
5702 err = got_object_id_str(&id_str1, s->id1);
5703 if (err)
5704 return err;
5705 label1 = s->label1 ? s->label1 : id_str1;
5706 } else
5707 label1 = "/dev/null";
5709 err = got_object_id_str(&id_str2, s->id2);
5710 if (err)
5711 return err;
5712 label2 = s->label2 ? s->label2 : id_str2;
5714 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5715 err = got_error_from_errno("asprintf");
5716 free(id_str1);
5717 free(id_str2);
5718 return err;
5720 free(id_str1);
5721 free(id_str2);
5723 err = draw_file(view, header);
5724 free(header);
5725 return err;
5728 static const struct got_error *
5729 set_selected_commit(struct tog_diff_view_state *s,
5730 struct commit_queue_entry *entry)
5732 const struct got_error *err;
5733 const struct got_object_id_queue *parent_ids;
5734 struct got_commit_object *selected_commit;
5735 struct got_object_qid *pid;
5737 free(s->id2);
5738 s->id2 = got_object_id_dup(entry->id);
5739 if (s->id2 == NULL)
5740 return got_error_from_errno("got_object_id_dup");
5742 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5743 if (err)
5744 return err;
5745 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5746 free(s->id1);
5747 pid = STAILQ_FIRST(parent_ids);
5748 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5749 got_object_commit_close(selected_commit);
5750 return NULL;
5753 static const struct got_error *
5754 reset_diff_view(struct tog_view *view)
5756 struct tog_diff_view_state *s = &view->state.diff;
5758 view->count = 0;
5759 wclear(view->window);
5760 s->first_displayed_line = 1;
5761 s->last_displayed_line = view->nlines;
5762 s->matched_line = 0;
5763 diff_view_indicate_progress(view);
5764 return create_diff(s);
5767 static void
5768 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5770 int start, i;
5772 i = start = s->first_displayed_line - 1;
5774 while (s->lines[i].type != type) {
5775 if (i == 0)
5776 i = s->nlines - 1;
5777 if (--i == start)
5778 return; /* do nothing, requested type not in file */
5781 s->selected_line = 1;
5782 s->first_displayed_line = i;
5785 static void
5786 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5788 int start, i;
5790 i = start = s->first_displayed_line + 1;
5792 while (s->lines[i].type != type) {
5793 if (i == s->nlines - 1)
5794 i = 0;
5795 if (++i == start)
5796 return; /* do nothing, requested type not in file */
5799 s->selected_line = 1;
5800 s->first_displayed_line = i;
5803 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5804 int, int, int);
5805 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5806 int, int);
5808 static const struct got_error *
5809 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5811 const struct got_error *err = NULL;
5812 struct tog_diff_view_state *s = &view->state.diff;
5813 struct tog_log_view_state *ls;
5814 struct commit_queue_entry *old_selected_entry;
5815 char *line = NULL;
5816 size_t linesize = 0;
5817 ssize_t linelen;
5818 int i, nscroll = view->nlines - 1, up = 0;
5820 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5822 switch (ch) {
5823 case '0':
5824 case '$':
5825 case KEY_RIGHT:
5826 case 'l':
5827 case KEY_LEFT:
5828 case 'h':
5829 horizontal_scroll_input(view, ch);
5830 break;
5831 case 'a':
5832 case 'w':
5833 if (ch == 'a') {
5834 s->force_text_diff = !s->force_text_diff;
5835 view->action = s->force_text_diff ?
5836 "force ASCII text enabled" :
5837 "force ASCII text disabled";
5839 else if (ch == 'w') {
5840 s->ignore_whitespace = !s->ignore_whitespace;
5841 view->action = s->ignore_whitespace ?
5842 "ignore whitespace enabled" :
5843 "ignore whitespace disabled";
5845 err = reset_diff_view(view);
5846 break;
5847 case 'g':
5848 case KEY_HOME:
5849 s->first_displayed_line = 1;
5850 view->count = 0;
5851 break;
5852 case 'G':
5853 case KEY_END:
5854 view->count = 0;
5855 if (s->eof)
5856 break;
5858 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5859 s->eof = 1;
5860 break;
5861 case 'k':
5862 case KEY_UP:
5863 case CTRL('p'):
5864 if (s->first_displayed_line > 1)
5865 s->first_displayed_line--;
5866 else
5867 view->count = 0;
5868 break;
5869 case CTRL('u'):
5870 case 'u':
5871 nscroll /= 2;
5872 /* FALL THROUGH */
5873 case KEY_PPAGE:
5874 case CTRL('b'):
5875 case 'b':
5876 if (s->first_displayed_line == 1) {
5877 view->count = 0;
5878 break;
5880 i = 0;
5881 while (i++ < nscroll && s->first_displayed_line > 1)
5882 s->first_displayed_line--;
5883 break;
5884 case 'j':
5885 case KEY_DOWN:
5886 case CTRL('n'):
5887 if (!s->eof)
5888 s->first_displayed_line++;
5889 else
5890 view->count = 0;
5891 break;
5892 case CTRL('d'):
5893 case 'd':
5894 nscroll /= 2;
5895 /* FALL THROUGH */
5896 case KEY_NPAGE:
5897 case CTRL('f'):
5898 case 'f':
5899 case ' ':
5900 if (s->eof) {
5901 view->count = 0;
5902 break;
5904 i = 0;
5905 while (!s->eof && i++ < nscroll) {
5906 linelen = getline(&line, &linesize, s->f);
5907 s->first_displayed_line++;
5908 if (linelen == -1) {
5909 if (feof(s->f)) {
5910 s->eof = 1;
5911 } else
5912 err = got_ferror(s->f, GOT_ERR_IO);
5913 break;
5916 free(line);
5917 break;
5918 case '(':
5919 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5920 break;
5921 case ')':
5922 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5923 break;
5924 case '{':
5925 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5926 break;
5927 case '}':
5928 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5929 break;
5930 case '[':
5931 if (s->diff_context > 0) {
5932 s->diff_context--;
5933 s->matched_line = 0;
5934 diff_view_indicate_progress(view);
5935 err = create_diff(s);
5936 if (s->first_displayed_line + view->nlines - 1 >
5937 s->nlines) {
5938 s->first_displayed_line = 1;
5939 s->last_displayed_line = view->nlines;
5941 } else
5942 view->count = 0;
5943 break;
5944 case ']':
5945 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5946 s->diff_context++;
5947 s->matched_line = 0;
5948 diff_view_indicate_progress(view);
5949 err = create_diff(s);
5950 } else
5951 view->count = 0;
5952 break;
5953 case '<':
5954 case ',':
5955 case 'K':
5956 up = 1;
5957 /* FALL THROUGH */
5958 case '>':
5959 case '.':
5960 case 'J':
5961 if (s->parent_view == NULL) {
5962 view->count = 0;
5963 break;
5965 s->parent_view->count = view->count;
5967 if (s->parent_view->type == TOG_VIEW_LOG) {
5968 ls = &s->parent_view->state.log;
5969 old_selected_entry = ls->selected_entry;
5971 err = input_log_view(NULL, s->parent_view,
5972 up ? KEY_UP : KEY_DOWN);
5973 if (err)
5974 break;
5975 view->count = s->parent_view->count;
5977 if (old_selected_entry == ls->selected_entry)
5978 break;
5980 err = set_selected_commit(s, ls->selected_entry);
5981 if (err)
5982 break;
5983 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5984 struct tog_blame_view_state *bs;
5985 struct got_object_id *id, *prev_id;
5987 bs = &s->parent_view->state.blame;
5988 prev_id = get_annotation_for_line(bs->blame.lines,
5989 bs->blame.nlines, bs->last_diffed_line);
5991 err = input_blame_view(&view, s->parent_view,
5992 up ? KEY_UP : KEY_DOWN);
5993 if (err)
5994 break;
5995 view->count = s->parent_view->count;
5997 if (prev_id == NULL)
5998 break;
5999 id = get_selected_commit_id(bs->blame.lines,
6000 bs->blame.nlines, bs->first_displayed_line,
6001 bs->selected_line);
6002 if (id == NULL)
6003 break;
6005 if (!got_object_id_cmp(prev_id, id))
6006 break;
6008 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
6009 if (err)
6010 break;
6012 s->first_displayed_line = 1;
6013 s->last_displayed_line = view->nlines;
6014 s->matched_line = 0;
6015 view->x = 0;
6017 diff_view_indicate_progress(view);
6018 err = create_diff(s);
6019 break;
6020 default:
6021 view->count = 0;
6022 break;
6025 return err;
6028 static const struct got_error *
6029 cmd_diff(int argc, char *argv[])
6031 const struct got_error *error;
6032 struct got_repository *repo = NULL;
6033 struct got_worktree *worktree = NULL;
6034 struct got_object_id *id1 = NULL, *id2 = NULL;
6035 char *repo_path = NULL, *cwd = NULL;
6036 char *id_str1 = NULL, *id_str2 = NULL;
6037 char *keyword_idstr1 = NULL, *keyword_idstr2 = NULL;
6038 char *label1 = NULL, *label2 = NULL;
6039 int diff_context = 3, ignore_whitespace = 0;
6040 int ch, force_text_diff = 0;
6041 const char *errstr;
6042 struct tog_view *view;
6043 int *pack_fds = NULL;
6045 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
6046 switch (ch) {
6047 case 'a':
6048 force_text_diff = 1;
6049 break;
6050 case 'C':
6051 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
6052 &errstr);
6053 if (errstr != NULL)
6054 errx(1, "number of context lines is %s: %s",
6055 errstr, errstr);
6056 break;
6057 case 'r':
6058 repo_path = realpath(optarg, NULL);
6059 if (repo_path == NULL)
6060 return got_error_from_errno2("realpath",
6061 optarg);
6062 got_path_strip_trailing_slashes(repo_path);
6063 break;
6064 case 'w':
6065 ignore_whitespace = 1;
6066 break;
6067 default:
6068 usage_diff();
6069 /* NOTREACHED */
6073 argc -= optind;
6074 argv += optind;
6076 if (argc == 0) {
6077 usage_diff(); /* TODO show local worktree changes */
6078 } else if (argc == 2) {
6079 id_str1 = argv[0];
6080 id_str2 = argv[1];
6081 } else
6082 usage_diff();
6084 error = got_repo_pack_fds_open(&pack_fds);
6085 if (error)
6086 goto done;
6088 if (repo_path == NULL) {
6089 cwd = getcwd(NULL, 0);
6090 if (cwd == NULL)
6091 return got_error_from_errno("getcwd");
6092 error = got_worktree_open(&worktree, cwd, NULL);
6093 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6094 goto done;
6095 if (worktree)
6096 repo_path =
6097 strdup(got_worktree_get_repo_path(worktree));
6098 else
6099 repo_path = strdup(cwd);
6100 if (repo_path == NULL) {
6101 error = got_error_from_errno("strdup");
6102 goto done;
6106 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6107 if (error)
6108 goto done;
6110 init_curses();
6112 error = apply_unveil(got_repo_get_path(repo), NULL);
6113 if (error)
6114 goto done;
6116 error = tog_load_refs(repo, 0);
6117 if (error)
6118 goto done;
6120 if (id_str1 != NULL) {
6121 error = got_keyword_to_idstr(&keyword_idstr1, id_str1,
6122 repo, worktree);
6123 if (error != NULL)
6124 goto done;
6125 if (keyword_idstr1 != NULL)
6126 id_str1 = keyword_idstr1;
6128 if (id_str2 != NULL) {
6129 error = got_keyword_to_idstr(&keyword_idstr2, id_str2,
6130 repo, worktree);
6131 if (error != NULL)
6132 goto done;
6133 if (keyword_idstr2 != NULL)
6134 id_str2 = keyword_idstr2;
6137 error = got_repo_match_object_id(&id1, &label1, id_str1,
6138 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6139 if (error)
6140 goto done;
6142 error = got_repo_match_object_id(&id2, &label2, id_str2,
6143 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6144 if (error)
6145 goto done;
6147 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
6148 if (view == NULL) {
6149 error = got_error_from_errno("view_open");
6150 goto done;
6152 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
6153 ignore_whitespace, force_text_diff, NULL, repo);
6154 if (error)
6155 goto done;
6157 if (worktree) {
6158 error = set_tog_base_commit(repo, worktree);
6159 if (error != NULL)
6160 goto done;
6163 error = view_loop(view);
6165 done:
6166 free(tog_base_commit.id);
6167 free(keyword_idstr1);
6168 free(keyword_idstr2);
6169 free(label1);
6170 free(label2);
6171 free(repo_path);
6172 free(cwd);
6173 if (repo) {
6174 const struct got_error *close_err = got_repo_close(repo);
6175 if (error == NULL)
6176 error = close_err;
6178 if (worktree)
6179 got_worktree_close(worktree);
6180 if (pack_fds) {
6181 const struct got_error *pack_err =
6182 got_repo_pack_fds_close(pack_fds);
6183 if (error == NULL)
6184 error = pack_err;
6186 tog_free_refs();
6187 return error;
6190 __dead static void
6191 usage_blame(void)
6193 endwin();
6194 fprintf(stderr,
6195 "usage: %s blame [-c commit] [-r repository-path] path\n",
6196 getprogname());
6197 exit(1);
6200 struct tog_blame_line {
6201 int annotated;
6202 struct got_object_id *id;
6205 static const struct got_error *
6206 draw_blame(struct tog_view *view)
6208 struct tog_blame_view_state *s = &view->state.blame;
6209 struct tog_blame *blame = &s->blame;
6210 regmatch_t *regmatch = &view->regmatch;
6211 const struct got_error *err;
6212 int lineno = 0, nprinted = 0;
6213 char *line = NULL;
6214 size_t linesize = 0;
6215 ssize_t linelen;
6216 wchar_t *wline;
6217 int width;
6218 struct tog_blame_line *blame_line;
6219 struct got_object_id *prev_id = NULL;
6220 char *id_str;
6221 struct tog_color *tc;
6223 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6224 if (err)
6225 return err;
6227 rewind(blame->f);
6228 werase(view->window);
6230 if (asprintf(&line, "commit %s", id_str) == -1) {
6231 err = got_error_from_errno("asprintf");
6232 free(id_str);
6233 return err;
6236 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6237 free(line);
6238 line = NULL;
6239 if (err)
6240 return err;
6241 if (view_needs_focus_indication(view))
6242 wstandout(view->window);
6243 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6244 if (tc)
6245 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6246 waddwstr(view->window, wline);
6247 while (width++ < view->ncols)
6248 waddch(view->window, ' ');
6249 if (tc)
6250 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6251 if (view_needs_focus_indication(view))
6252 wstandend(view->window);
6253 free(wline);
6254 wline = NULL;
6256 if (view->gline > blame->nlines)
6257 view->gline = blame->nlines;
6259 if (tog_io.wait_for_ui) {
6260 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6261 int rc;
6263 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6264 if (rc)
6265 return got_error_set_errno(rc, "pthread_cond_wait");
6266 tog_io.wait_for_ui = 0;
6269 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6270 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6271 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6272 free(id_str);
6273 return got_error_from_errno("asprintf");
6275 free(id_str);
6276 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6277 free(line);
6278 line = NULL;
6279 if (err)
6280 return err;
6281 waddwstr(view->window, wline);
6282 free(wline);
6283 wline = NULL;
6284 if (width < view->ncols - 1)
6285 waddch(view->window, '\n');
6287 s->eof = 0;
6288 view->maxx = 0;
6289 while (nprinted < view->nlines - 2) {
6290 linelen = getline(&line, &linesize, blame->f);
6291 if (linelen == -1) {
6292 if (feof(blame->f)) {
6293 s->eof = 1;
6294 break;
6296 free(line);
6297 return got_ferror(blame->f, GOT_ERR_IO);
6299 if (++lineno < s->first_displayed_line)
6300 continue;
6301 if (view->gline && !gotoline(view, &lineno, &nprinted))
6302 continue;
6304 /* Set view->maxx based on full line length. */
6305 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6306 if (err) {
6307 free(line);
6308 return err;
6310 free(wline);
6311 wline = NULL;
6312 view->maxx = MAX(view->maxx, width);
6314 if (nprinted == s->selected_line - 1)
6315 wstandout(view->window);
6317 if (blame->nlines > 0) {
6318 blame_line = &blame->lines[lineno - 1];
6319 if (blame_line->annotated && prev_id &&
6320 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6321 !(nprinted == s->selected_line - 1)) {
6322 waddstr(view->window, " ");
6323 } else if (blame_line->annotated) {
6324 char *id_str;
6325 err = got_object_id_str(&id_str,
6326 blame_line->id);
6327 if (err) {
6328 free(line);
6329 return err;
6331 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6332 if (tc)
6333 wattr_on(view->window,
6334 COLOR_PAIR(tc->colorpair), NULL);
6335 wprintw(view->window, "%.8s", id_str);
6336 if (tc)
6337 wattr_off(view->window,
6338 COLOR_PAIR(tc->colorpair), NULL);
6339 free(id_str);
6340 prev_id = blame_line->id;
6341 } else {
6342 waddstr(view->window, "........");
6343 prev_id = NULL;
6345 } else {
6346 waddstr(view->window, "........");
6347 prev_id = NULL;
6350 if (nprinted == s->selected_line - 1)
6351 wstandend(view->window);
6352 waddstr(view->window, " ");
6354 if (view->ncols <= 9) {
6355 width = 9;
6356 } else if (s->first_displayed_line + nprinted ==
6357 s->matched_line &&
6358 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6359 err = add_matched_line(&width, line, view->ncols - 9, 9,
6360 view->window, view->x, regmatch);
6361 if (err) {
6362 free(line);
6363 return err;
6365 width += 9;
6366 } else {
6367 int skip;
6368 err = format_line(&wline, &width, &skip, line,
6369 view->x, view->ncols - 9, 9, 1);
6370 if (err) {
6371 free(line);
6372 return err;
6374 waddwstr(view->window, &wline[skip]);
6375 width += 9;
6376 free(wline);
6377 wline = NULL;
6380 if (width <= view->ncols - 1)
6381 waddch(view->window, '\n');
6382 if (++nprinted == 1)
6383 s->first_displayed_line = lineno;
6385 free(line);
6386 s->last_displayed_line = lineno;
6388 view_border(view);
6390 return NULL;
6393 static const struct got_error *
6394 blame_cb(void *arg, int nlines, int lineno,
6395 struct got_commit_object *commit, struct got_object_id *id)
6397 const struct got_error *err = NULL;
6398 struct tog_blame_cb_args *a = arg;
6399 struct tog_blame_line *line;
6400 int errcode;
6402 if (nlines != a->nlines ||
6403 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6404 return got_error(GOT_ERR_RANGE);
6406 errcode = pthread_mutex_lock(&tog_mutex);
6407 if (errcode)
6408 return got_error_set_errno(errcode, "pthread_mutex_lock");
6410 if (*a->quit) { /* user has quit the blame view */
6411 err = got_error(GOT_ERR_ITER_COMPLETED);
6412 goto done;
6415 if (lineno == -1)
6416 goto done; /* no change in this commit */
6418 line = &a->lines[lineno - 1];
6419 if (line->annotated)
6420 goto done;
6422 line->id = got_object_id_dup(id);
6423 if (line->id == NULL) {
6424 err = got_error_from_errno("got_object_id_dup");
6425 goto done;
6427 line->annotated = 1;
6428 done:
6429 errcode = pthread_mutex_unlock(&tog_mutex);
6430 if (errcode)
6431 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6432 return err;
6435 static void *
6436 blame_thread(void *arg)
6438 const struct got_error *err, *close_err;
6439 struct tog_blame_thread_args *ta = arg;
6440 struct tog_blame_cb_args *a = ta->cb_args;
6441 int errcode, fd1 = -1, fd2 = -1;
6442 FILE *f1 = NULL, *f2 = NULL;
6444 fd1 = got_opentempfd();
6445 if (fd1 == -1)
6446 return (void *)got_error_from_errno("got_opentempfd");
6448 fd2 = got_opentempfd();
6449 if (fd2 == -1) {
6450 err = got_error_from_errno("got_opentempfd");
6451 goto done;
6454 f1 = got_opentemp();
6455 if (f1 == NULL) {
6456 err = (void *)got_error_from_errno("got_opentemp");
6457 goto done;
6459 f2 = got_opentemp();
6460 if (f2 == NULL) {
6461 err = (void *)got_error_from_errno("got_opentemp");
6462 goto done;
6465 err = block_signals_used_by_main_thread();
6466 if (err)
6467 goto done;
6469 err = got_blame(ta->path, a->commit_id, ta->repo,
6470 tog_diff_algo, blame_cb, ta->cb_args,
6471 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6472 if (err && err->code == GOT_ERR_CANCELLED)
6473 err = NULL;
6475 errcode = pthread_mutex_lock(&tog_mutex);
6476 if (errcode) {
6477 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6478 goto done;
6481 close_err = got_repo_close(ta->repo);
6482 if (err == NULL)
6483 err = close_err;
6484 ta->repo = NULL;
6485 *ta->complete = 1;
6487 if (tog_io.wait_for_ui) {
6488 errcode = pthread_cond_signal(&ta->blame_complete);
6489 if (errcode && err == NULL)
6490 err = got_error_set_errno(errcode,
6491 "pthread_cond_signal");
6494 errcode = pthread_mutex_unlock(&tog_mutex);
6495 if (errcode && err == NULL)
6496 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6498 done:
6499 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6500 err = got_error_from_errno("close");
6501 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6502 err = got_error_from_errno("close");
6503 if (f1 && fclose(f1) == EOF && err == NULL)
6504 err = got_error_from_errno("fclose");
6505 if (f2 && fclose(f2) == EOF && err == NULL)
6506 err = got_error_from_errno("fclose");
6508 return (void *)err;
6511 static struct got_object_id *
6512 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6513 int first_displayed_line, int selected_line)
6515 struct tog_blame_line *line;
6517 if (nlines <= 0)
6518 return NULL;
6520 line = &lines[first_displayed_line - 1 + selected_line - 1];
6521 if (!line->annotated)
6522 return NULL;
6524 return line->id;
6527 static struct got_object_id *
6528 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6529 int lineno)
6531 struct tog_blame_line *line;
6533 if (nlines <= 0 || lineno >= nlines)
6534 return NULL;
6536 line = &lines[lineno - 1];
6537 if (!line->annotated)
6538 return NULL;
6540 return line->id;
6543 static const struct got_error *
6544 stop_blame(struct tog_blame *blame)
6546 const struct got_error *err = NULL;
6547 int i;
6549 if (blame->thread) {
6550 int errcode;
6551 errcode = pthread_mutex_unlock(&tog_mutex);
6552 if (errcode)
6553 return got_error_set_errno(errcode,
6554 "pthread_mutex_unlock");
6555 errcode = pthread_join(blame->thread, (void **)&err);
6556 if (errcode)
6557 return got_error_set_errno(errcode, "pthread_join");
6558 errcode = pthread_mutex_lock(&tog_mutex);
6559 if (errcode)
6560 return got_error_set_errno(errcode,
6561 "pthread_mutex_lock");
6562 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6563 err = NULL;
6564 blame->thread = NULL;
6566 if (blame->thread_args.repo) {
6567 const struct got_error *close_err;
6568 close_err = got_repo_close(blame->thread_args.repo);
6569 if (err == NULL)
6570 err = close_err;
6571 blame->thread_args.repo = NULL;
6573 if (blame->f) {
6574 if (fclose(blame->f) == EOF && err == NULL)
6575 err = got_error_from_errno("fclose");
6576 blame->f = NULL;
6578 if (blame->lines) {
6579 for (i = 0; i < blame->nlines; i++)
6580 free(blame->lines[i].id);
6581 free(blame->lines);
6582 blame->lines = NULL;
6584 free(blame->cb_args.commit_id);
6585 blame->cb_args.commit_id = NULL;
6586 if (blame->pack_fds) {
6587 const struct got_error *pack_err =
6588 got_repo_pack_fds_close(blame->pack_fds);
6589 if (err == NULL)
6590 err = pack_err;
6591 blame->pack_fds = NULL;
6593 free(blame->line_offsets);
6594 blame->line_offsets = NULL;
6595 return err;
6598 static const struct got_error *
6599 cancel_blame_view(void *arg)
6601 const struct got_error *err = NULL;
6602 int *done = arg;
6603 int errcode;
6605 errcode = pthread_mutex_lock(&tog_mutex);
6606 if (errcode)
6607 return got_error_set_errno(errcode,
6608 "pthread_mutex_unlock");
6610 if (*done)
6611 err = got_error(GOT_ERR_CANCELLED);
6613 errcode = pthread_mutex_unlock(&tog_mutex);
6614 if (errcode)
6615 return got_error_set_errno(errcode,
6616 "pthread_mutex_lock");
6618 return err;
6621 static const struct got_error *
6622 run_blame(struct tog_view *view)
6624 struct tog_blame_view_state *s = &view->state.blame;
6625 struct tog_blame *blame = &s->blame;
6626 const struct got_error *err = NULL;
6627 struct got_commit_object *commit = NULL;
6628 struct got_blob_object *blob = NULL;
6629 struct got_repository *thread_repo = NULL;
6630 struct got_object_id *obj_id = NULL;
6631 int obj_type, fd = -1;
6632 int *pack_fds = NULL;
6634 err = got_object_open_as_commit(&commit, s->repo,
6635 &s->blamed_commit->id);
6636 if (err)
6637 return err;
6639 fd = got_opentempfd();
6640 if (fd == -1) {
6641 err = got_error_from_errno("got_opentempfd");
6642 goto done;
6645 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6646 if (err)
6647 goto done;
6649 err = got_object_get_type(&obj_type, s->repo, obj_id);
6650 if (err)
6651 goto done;
6653 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6654 err = got_error(GOT_ERR_OBJ_TYPE);
6655 goto done;
6658 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6659 if (err)
6660 goto done;
6661 blame->f = got_opentemp();
6662 if (blame->f == NULL) {
6663 err = got_error_from_errno("got_opentemp");
6664 goto done;
6666 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6667 &blame->line_offsets, blame->f, blob);
6668 if (err)
6669 goto done;
6670 if (blame->nlines == 0) {
6671 s->blame_complete = 1;
6672 goto done;
6675 /* Don't include \n at EOF in the blame line count. */
6676 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6677 blame->nlines--;
6679 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6680 if (blame->lines == NULL) {
6681 err = got_error_from_errno("calloc");
6682 goto done;
6685 err = got_repo_pack_fds_open(&pack_fds);
6686 if (err)
6687 goto done;
6688 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6689 pack_fds);
6690 if (err)
6691 goto done;
6693 blame->pack_fds = pack_fds;
6694 blame->cb_args.view = view;
6695 blame->cb_args.lines = blame->lines;
6696 blame->cb_args.nlines = blame->nlines;
6697 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6698 if (blame->cb_args.commit_id == NULL) {
6699 err = got_error_from_errno("got_object_id_dup");
6700 goto done;
6702 blame->cb_args.quit = &s->done;
6704 blame->thread_args.path = s->path;
6705 blame->thread_args.repo = thread_repo;
6706 blame->thread_args.cb_args = &blame->cb_args;
6707 blame->thread_args.complete = &s->blame_complete;
6708 blame->thread_args.cancel_cb = cancel_blame_view;
6709 blame->thread_args.cancel_arg = &s->done;
6710 s->blame_complete = 0;
6712 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6713 s->first_displayed_line = 1;
6714 s->last_displayed_line = view->nlines;
6715 s->selected_line = 1;
6717 s->matched_line = 0;
6719 done:
6720 if (commit)
6721 got_object_commit_close(commit);
6722 if (fd != -1 && close(fd) == -1 && err == NULL)
6723 err = got_error_from_errno("close");
6724 if (blob)
6725 got_object_blob_close(blob);
6726 free(obj_id);
6727 if (err)
6728 stop_blame(blame);
6729 return err;
6732 static const struct got_error *
6733 open_blame_view(struct tog_view *view, char *path,
6734 struct got_object_id *commit_id, struct got_repository *repo)
6736 const struct got_error *err = NULL;
6737 struct tog_blame_view_state *s = &view->state.blame;
6739 STAILQ_INIT(&s->blamed_commits);
6741 s->path = strdup(path);
6742 if (s->path == NULL)
6743 return got_error_from_errno("strdup");
6745 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6746 if (err) {
6747 free(s->path);
6748 return err;
6751 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6752 s->first_displayed_line = 1;
6753 s->last_displayed_line = view->nlines;
6754 s->selected_line = 1;
6755 s->blame_complete = 0;
6756 s->repo = repo;
6757 s->commit_id = commit_id;
6758 memset(&s->blame, 0, sizeof(s->blame));
6760 STAILQ_INIT(&s->colors);
6761 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6762 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6763 get_color_value("TOG_COLOR_COMMIT"));
6764 if (err)
6765 return err;
6768 view->show = show_blame_view;
6769 view->input = input_blame_view;
6770 view->reset = reset_blame_view;
6771 view->close = close_blame_view;
6772 view->search_start = search_start_blame_view;
6773 view->search_setup = search_setup_blame_view;
6774 view->search_next = search_next_view_match;
6776 if (using_mock_io) {
6777 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6778 int rc;
6780 rc = pthread_cond_init(&bta->blame_complete, NULL);
6781 if (rc)
6782 return got_error_set_errno(rc, "pthread_cond_init");
6785 return run_blame(view);
6788 static const struct got_error *
6789 close_blame_view(struct tog_view *view)
6791 const struct got_error *err = NULL;
6792 struct tog_blame_view_state *s = &view->state.blame;
6794 if (s->blame.thread)
6795 err = stop_blame(&s->blame);
6797 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6798 struct got_object_qid *blamed_commit;
6799 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6800 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6801 got_object_qid_free(blamed_commit);
6804 if (using_mock_io) {
6805 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6806 int rc;
6808 rc = pthread_cond_destroy(&bta->blame_complete);
6809 if (rc && err == NULL)
6810 err = got_error_set_errno(rc, "pthread_cond_destroy");
6813 free(s->path);
6814 free_colors(&s->colors);
6815 return err;
6818 static const struct got_error *
6819 search_start_blame_view(struct tog_view *view)
6821 struct tog_blame_view_state *s = &view->state.blame;
6823 s->matched_line = 0;
6824 return NULL;
6827 static void
6828 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6829 size_t *nlines, int **first, int **last, int **match, int **selected)
6831 struct tog_blame_view_state *s = &view->state.blame;
6833 *f = s->blame.f;
6834 *nlines = s->blame.nlines;
6835 *line_offsets = s->blame.line_offsets;
6836 *match = &s->matched_line;
6837 *first = &s->first_displayed_line;
6838 *last = &s->last_displayed_line;
6839 *selected = &s->selected_line;
6842 static const struct got_error *
6843 show_blame_view(struct tog_view *view)
6845 const struct got_error *err = NULL;
6846 struct tog_blame_view_state *s = &view->state.blame;
6847 int errcode;
6849 if (s->blame.thread == NULL && !s->blame_complete) {
6850 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6851 &s->blame.thread_args);
6852 if (errcode)
6853 return got_error_set_errno(errcode, "pthread_create");
6855 if (!using_mock_io)
6856 halfdelay(1); /* fast refresh while annotating */
6859 if (s->blame_complete && !using_mock_io)
6860 halfdelay(10); /* disable fast refresh */
6862 err = draw_blame(view);
6864 view_border(view);
6865 return err;
6868 static const struct got_error *
6869 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6870 struct got_repository *repo, struct got_object_id *id)
6872 struct tog_view *log_view;
6873 const struct got_error *err = NULL;
6875 *new_view = NULL;
6877 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6878 if (log_view == NULL)
6879 return got_error_from_errno("view_open");
6881 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0, NULL);
6882 if (err)
6883 view_close(log_view);
6884 else
6885 *new_view = log_view;
6887 return err;
6890 static const struct got_error *
6891 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6893 const struct got_error *err = NULL, *thread_err = NULL;
6894 struct tog_view *diff_view;
6895 struct tog_blame_view_state *s = &view->state.blame;
6896 int eos, nscroll, begin_y = 0, begin_x = 0;
6898 eos = nscroll = view->nlines - 2;
6899 if (view_is_hsplit_top(view))
6900 --eos; /* border */
6902 switch (ch) {
6903 case '0':
6904 case '$':
6905 case KEY_RIGHT:
6906 case 'l':
6907 case KEY_LEFT:
6908 case 'h':
6909 horizontal_scroll_input(view, ch);
6910 break;
6911 case 'q':
6912 s->done = 1;
6913 break;
6914 case 'g':
6915 case KEY_HOME:
6916 s->selected_line = 1;
6917 s->first_displayed_line = 1;
6918 view->count = 0;
6919 break;
6920 case 'G':
6921 case KEY_END:
6922 if (s->blame.nlines < eos) {
6923 s->selected_line = s->blame.nlines;
6924 s->first_displayed_line = 1;
6925 } else {
6926 s->selected_line = eos;
6927 s->first_displayed_line = s->blame.nlines - (eos - 1);
6929 view->count = 0;
6930 break;
6931 case 'k':
6932 case KEY_UP:
6933 case CTRL('p'):
6934 if (s->selected_line > 1)
6935 s->selected_line--;
6936 else if (s->selected_line == 1 &&
6937 s->first_displayed_line > 1)
6938 s->first_displayed_line--;
6939 else
6940 view->count = 0;
6941 break;
6942 case CTRL('u'):
6943 case 'u':
6944 nscroll /= 2;
6945 /* FALL THROUGH */
6946 case KEY_PPAGE:
6947 case CTRL('b'):
6948 case 'b':
6949 if (s->first_displayed_line == 1) {
6950 if (view->count > 1)
6951 nscroll += nscroll;
6952 s->selected_line = MAX(1, s->selected_line - nscroll);
6953 view->count = 0;
6954 break;
6956 if (s->first_displayed_line > nscroll)
6957 s->first_displayed_line -= nscroll;
6958 else
6959 s->first_displayed_line = 1;
6960 break;
6961 case 'j':
6962 case KEY_DOWN:
6963 case CTRL('n'):
6964 if (s->selected_line < eos && s->first_displayed_line +
6965 s->selected_line <= s->blame.nlines)
6966 s->selected_line++;
6967 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6968 s->first_displayed_line++;
6969 else
6970 view->count = 0;
6971 break;
6972 case 'c':
6973 case 'p': {
6974 struct got_object_id *id = NULL;
6976 view->count = 0;
6977 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6978 s->first_displayed_line, s->selected_line);
6979 if (id == NULL)
6980 break;
6981 if (ch == 'p') {
6982 struct got_commit_object *commit, *pcommit;
6983 struct got_object_qid *pid;
6984 struct got_object_id *blob_id = NULL;
6985 int obj_type;
6986 err = got_object_open_as_commit(&commit,
6987 s->repo, id);
6988 if (err)
6989 break;
6990 pid = STAILQ_FIRST(
6991 got_object_commit_get_parent_ids(commit));
6992 if (pid == NULL) {
6993 got_object_commit_close(commit);
6994 break;
6996 /* Check if path history ends here. */
6997 err = got_object_open_as_commit(&pcommit,
6998 s->repo, &pid->id);
6999 if (err)
7000 break;
7001 err = got_object_id_by_path(&blob_id, s->repo,
7002 pcommit, s->path);
7003 got_object_commit_close(pcommit);
7004 if (err) {
7005 if (err->code == GOT_ERR_NO_TREE_ENTRY)
7006 err = NULL;
7007 got_object_commit_close(commit);
7008 break;
7010 err = got_object_get_type(&obj_type, s->repo,
7011 blob_id);
7012 free(blob_id);
7013 /* Can't blame non-blob type objects. */
7014 if (obj_type != GOT_OBJ_TYPE_BLOB) {
7015 got_object_commit_close(commit);
7016 break;
7018 err = got_object_qid_alloc(&s->blamed_commit,
7019 &pid->id);
7020 got_object_commit_close(commit);
7021 } else {
7022 if (got_object_id_cmp(id,
7023 &s->blamed_commit->id) == 0)
7024 break;
7025 err = got_object_qid_alloc(&s->blamed_commit,
7026 id);
7028 if (err)
7029 break;
7030 s->done = 1;
7031 thread_err = stop_blame(&s->blame);
7032 s->done = 0;
7033 if (thread_err)
7034 break;
7035 STAILQ_INSERT_HEAD(&s->blamed_commits,
7036 s->blamed_commit, entry);
7037 err = run_blame(view);
7038 if (err)
7039 break;
7040 break;
7042 case 'C': {
7043 struct got_object_qid *first;
7045 view->count = 0;
7046 first = STAILQ_FIRST(&s->blamed_commits);
7047 if (!got_object_id_cmp(&first->id, s->commit_id))
7048 break;
7049 s->done = 1;
7050 thread_err = stop_blame(&s->blame);
7051 s->done = 0;
7052 if (thread_err)
7053 break;
7054 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
7055 got_object_qid_free(s->blamed_commit);
7056 s->blamed_commit =
7057 STAILQ_FIRST(&s->blamed_commits);
7058 err = run_blame(view);
7059 if (err)
7060 break;
7061 break;
7063 case 'L':
7064 view->count = 0;
7065 s->id_to_log = get_selected_commit_id(s->blame.lines,
7066 s->blame.nlines, s->first_displayed_line, s->selected_line);
7067 if (s->id_to_log)
7068 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7069 break;
7070 case KEY_ENTER:
7071 case '\r': {
7072 struct got_object_id *id = NULL;
7073 struct got_object_qid *pid;
7074 struct got_commit_object *commit = NULL;
7076 view->count = 0;
7077 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7078 s->first_displayed_line, s->selected_line);
7079 if (id == NULL)
7080 break;
7081 err = got_object_open_as_commit(&commit, s->repo, id);
7082 if (err)
7083 break;
7084 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7085 if (*new_view) {
7086 /* traversed from diff view, release diff resources */
7087 err = close_diff_view(*new_view);
7088 if (err)
7089 break;
7090 diff_view = *new_view;
7091 } else {
7092 if (view_is_parent_view(view))
7093 view_get_split(view, &begin_y, &begin_x);
7095 diff_view = view_open(0, 0, begin_y, begin_x,
7096 TOG_VIEW_DIFF);
7097 if (diff_view == NULL) {
7098 got_object_commit_close(commit);
7099 err = got_error_from_errno("view_open");
7100 break;
7103 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
7104 id, NULL, NULL, 3, 0, 0, view, s->repo);
7105 got_object_commit_close(commit);
7106 if (err)
7107 break;
7108 s->last_diffed_line = s->first_displayed_line - 1 +
7109 s->selected_line;
7110 if (*new_view)
7111 break; /* still open from active diff view */
7112 if (view_is_parent_view(view) &&
7113 view->mode == TOG_VIEW_SPLIT_HRZN) {
7114 err = view_init_hsplit(view, begin_y);
7115 if (err)
7116 break;
7119 view->focussed = 0;
7120 diff_view->focussed = 1;
7121 diff_view->mode = view->mode;
7122 diff_view->nlines = view->lines - begin_y;
7123 if (view_is_parent_view(view)) {
7124 view_transfer_size(diff_view, view);
7125 err = view_close_child(view);
7126 if (err)
7127 break;
7128 err = view_set_child(view, diff_view);
7129 if (err)
7130 break;
7131 view->focus_child = 1;
7132 } else
7133 *new_view = diff_view;
7134 if (err)
7135 break;
7136 break;
7138 case CTRL('d'):
7139 case 'd':
7140 nscroll /= 2;
7141 /* FALL THROUGH */
7142 case KEY_NPAGE:
7143 case CTRL('f'):
7144 case 'f':
7145 case ' ':
7146 if (s->last_displayed_line >= s->blame.nlines &&
7147 s->selected_line >= MIN(s->blame.nlines,
7148 view->nlines - 2)) {
7149 view->count = 0;
7150 break;
7152 if (s->last_displayed_line >= s->blame.nlines &&
7153 s->selected_line < view->nlines - 2) {
7154 s->selected_line +=
7155 MIN(nscroll, s->last_displayed_line -
7156 s->first_displayed_line - s->selected_line + 1);
7158 if (s->last_displayed_line + nscroll <= s->blame.nlines)
7159 s->first_displayed_line += nscroll;
7160 else
7161 s->first_displayed_line =
7162 s->blame.nlines - (view->nlines - 3);
7163 break;
7164 case KEY_RESIZE:
7165 if (s->selected_line > view->nlines - 2) {
7166 s->selected_line = MIN(s->blame.nlines,
7167 view->nlines - 2);
7169 break;
7170 default:
7171 view->count = 0;
7172 break;
7174 return thread_err ? thread_err : err;
7177 static const struct got_error *
7178 reset_blame_view(struct tog_view *view)
7180 const struct got_error *err;
7181 struct tog_blame_view_state *s = &view->state.blame;
7183 view->count = 0;
7184 s->done = 1;
7185 err = stop_blame(&s->blame);
7186 s->done = 0;
7187 if (err)
7188 return err;
7189 return run_blame(view);
7192 static const struct got_error *
7193 cmd_blame(int argc, char *argv[])
7195 const struct got_error *error;
7196 struct got_repository *repo = NULL;
7197 struct got_worktree *worktree = NULL;
7198 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7199 char *link_target = NULL;
7200 struct got_object_id *commit_id = NULL;
7201 struct got_commit_object *commit = NULL;
7202 char *keyword_idstr = NULL, *commit_id_str = NULL;
7203 int ch;
7204 struct tog_view *view = NULL;
7205 int *pack_fds = NULL;
7207 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7208 switch (ch) {
7209 case 'c':
7210 commit_id_str = optarg;
7211 break;
7212 case 'r':
7213 repo_path = realpath(optarg, NULL);
7214 if (repo_path == NULL)
7215 return got_error_from_errno2("realpath",
7216 optarg);
7217 break;
7218 default:
7219 usage_blame();
7220 /* NOTREACHED */
7224 argc -= optind;
7225 argv += optind;
7227 if (argc != 1)
7228 usage_blame();
7230 error = got_repo_pack_fds_open(&pack_fds);
7231 if (error != NULL)
7232 goto done;
7234 if (repo_path == NULL) {
7235 cwd = getcwd(NULL, 0);
7236 if (cwd == NULL)
7237 return got_error_from_errno("getcwd");
7238 error = got_worktree_open(&worktree, cwd, NULL);
7239 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7240 goto done;
7241 if (worktree)
7242 repo_path =
7243 strdup(got_worktree_get_repo_path(worktree));
7244 else
7245 repo_path = strdup(cwd);
7246 if (repo_path == NULL) {
7247 error = got_error_from_errno("strdup");
7248 goto done;
7252 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7253 if (error != NULL)
7254 goto done;
7256 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7257 worktree);
7258 if (error)
7259 goto done;
7261 init_curses();
7263 error = apply_unveil(got_repo_get_path(repo), NULL);
7264 if (error)
7265 goto done;
7267 error = tog_load_refs(repo, 0);
7268 if (error)
7269 goto done;
7271 if (commit_id_str == NULL) {
7272 struct got_reference *head_ref;
7273 error = got_ref_open(&head_ref, repo, worktree ?
7274 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7275 if (error != NULL)
7276 goto done;
7277 error = got_ref_resolve(&commit_id, repo, head_ref);
7278 got_ref_close(head_ref);
7279 } else {
7280 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
7281 repo, worktree);
7282 if (error != NULL)
7283 goto done;
7284 if (keyword_idstr != NULL)
7285 commit_id_str = keyword_idstr;
7287 error = got_repo_match_object_id(&commit_id, NULL,
7288 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7290 if (error != NULL)
7291 goto done;
7293 error = got_object_open_as_commit(&commit, repo, commit_id);
7294 if (error)
7295 goto done;
7297 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7298 commit, repo);
7299 if (error)
7300 goto done;
7302 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7303 if (view == NULL) {
7304 error = got_error_from_errno("view_open");
7305 goto done;
7307 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7308 commit_id, repo);
7309 if (error != NULL) {
7310 if (view->close == NULL)
7311 close_blame_view(view);
7312 view_close(view);
7313 goto done;
7316 if (worktree) {
7317 error = set_tog_base_commit(repo, worktree);
7318 if (error != NULL)
7319 goto done;
7321 /* Release work tree lock. */
7322 got_worktree_close(worktree);
7323 worktree = NULL;
7326 error = view_loop(view);
7328 done:
7329 free(tog_base_commit.id);
7330 free(repo_path);
7331 free(in_repo_path);
7332 free(link_target);
7333 free(cwd);
7334 free(commit_id);
7335 free(keyword_idstr);
7336 if (commit)
7337 got_object_commit_close(commit);
7338 if (worktree)
7339 got_worktree_close(worktree);
7340 if (repo) {
7341 const struct got_error *close_err = got_repo_close(repo);
7342 if (error == NULL)
7343 error = close_err;
7345 if (pack_fds) {
7346 const struct got_error *pack_err =
7347 got_repo_pack_fds_close(pack_fds);
7348 if (error == NULL)
7349 error = pack_err;
7351 tog_free_refs();
7352 return error;
7355 static const struct got_error *
7356 draw_tree_entries(struct tog_view *view, const char *parent_path)
7358 struct tog_tree_view_state *s = &view->state.tree;
7359 const struct got_error *err = NULL;
7360 struct got_tree_entry *te;
7361 wchar_t *wline;
7362 char *index = NULL;
7363 struct tog_color *tc;
7364 int width, n, nentries, scrollx, i = 1;
7365 int limit = view->nlines;
7367 s->ndisplayed = 0;
7368 if (view_is_hsplit_top(view))
7369 --limit; /* border */
7371 werase(view->window);
7373 if (limit == 0)
7374 return NULL;
7376 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7377 0, 0);
7378 if (err)
7379 return err;
7380 if (view_needs_focus_indication(view))
7381 wstandout(view->window);
7382 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7383 if (tc)
7384 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7385 waddwstr(view->window, wline);
7386 free(wline);
7387 wline = NULL;
7388 while (width++ < view->ncols)
7389 waddch(view->window, ' ');
7390 if (tc)
7391 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7392 if (view_needs_focus_indication(view))
7393 wstandend(view->window);
7394 if (--limit <= 0)
7395 return NULL;
7397 i += s->selected;
7398 if (s->first_displayed_entry) {
7399 i += got_tree_entry_get_index(s->first_displayed_entry);
7400 if (s->tree != s->root)
7401 ++i; /* account for ".." entry */
7403 nentries = got_object_tree_get_nentries(s->tree);
7404 if (asprintf(&index, "[%d/%d] %s",
7405 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7406 return got_error_from_errno("asprintf");
7407 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7408 free(index);
7409 if (err)
7410 return err;
7411 waddwstr(view->window, wline);
7412 free(wline);
7413 wline = NULL;
7414 if (width < view->ncols - 1)
7415 waddch(view->window, '\n');
7416 if (--limit <= 0)
7417 return NULL;
7418 waddch(view->window, '\n');
7419 if (--limit <= 0)
7420 return NULL;
7422 if (s->first_displayed_entry == NULL) {
7423 te = got_object_tree_get_first_entry(s->tree);
7424 if (s->selected == 0) {
7425 if (view->focussed)
7426 wstandout(view->window);
7427 s->selected_entry = NULL;
7429 waddstr(view->window, " ..\n"); /* parent directory */
7430 if (s->selected == 0 && view->focussed)
7431 wstandend(view->window);
7432 s->ndisplayed++;
7433 if (--limit <= 0)
7434 return NULL;
7435 n = 1;
7436 } else {
7437 n = 0;
7438 te = s->first_displayed_entry;
7441 view->maxx = 0;
7442 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7443 char *line = NULL, *id_str = NULL, *link_target = NULL;
7444 const char *modestr = "";
7445 mode_t mode;
7447 te = got_object_tree_get_entry(s->tree, i);
7448 mode = got_tree_entry_get_mode(te);
7450 if (s->show_ids) {
7451 err = got_object_id_str(&id_str,
7452 got_tree_entry_get_id(te));
7453 if (err)
7454 return got_error_from_errno(
7455 "got_object_id_str");
7457 if (got_object_tree_entry_is_submodule(te))
7458 modestr = "$";
7459 else if (S_ISLNK(mode)) {
7460 int i;
7462 err = got_tree_entry_get_symlink_target(&link_target,
7463 te, s->repo);
7464 if (err) {
7465 free(id_str);
7466 return err;
7468 for (i = 0; link_target[i] != '\0'; i++) {
7469 if (!isprint((unsigned char)link_target[i]))
7470 link_target[i] = '?';
7472 modestr = "@";
7474 else if (S_ISDIR(mode))
7475 modestr = "/";
7476 else if (mode & S_IXUSR)
7477 modestr = "*";
7478 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7479 got_tree_entry_get_name(te), modestr,
7480 link_target ? " -> ": "",
7481 link_target ? link_target : "") == -1) {
7482 free(id_str);
7483 free(link_target);
7484 return got_error_from_errno("asprintf");
7486 free(id_str);
7487 free(link_target);
7489 /* use full line width to determine view->maxx */
7490 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7491 if (err) {
7492 free(line);
7493 break;
7495 view->maxx = MAX(view->maxx, width);
7496 free(wline);
7497 wline = NULL;
7499 err = format_line(&wline, &width, &scrollx, line, view->x,
7500 view->ncols, 0, 0);
7501 if (err) {
7502 free(line);
7503 break;
7505 if (n == s->selected) {
7506 if (view->focussed)
7507 wstandout(view->window);
7508 s->selected_entry = te;
7510 tc = match_color(&s->colors, line);
7511 if (tc)
7512 wattr_on(view->window,
7513 COLOR_PAIR(tc->colorpair), NULL);
7514 waddwstr(view->window, &wline[scrollx]);
7515 if (tc)
7516 wattr_off(view->window,
7517 COLOR_PAIR(tc->colorpair), NULL);
7518 if (width < view->ncols)
7519 waddch(view->window, '\n');
7520 if (n == s->selected && view->focussed)
7521 wstandend(view->window);
7522 free(line);
7523 free(wline);
7524 wline = NULL;
7525 n++;
7526 s->ndisplayed++;
7527 s->last_displayed_entry = te;
7528 if (--limit <= 0)
7529 break;
7532 return err;
7535 static void
7536 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7538 struct got_tree_entry *te;
7539 int isroot = s->tree == s->root;
7540 int i = 0;
7542 if (s->first_displayed_entry == NULL)
7543 return;
7545 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7546 while (i++ < maxscroll) {
7547 if (te == NULL) {
7548 if (!isroot)
7549 s->first_displayed_entry = NULL;
7550 break;
7552 s->first_displayed_entry = te;
7553 te = got_tree_entry_get_prev(s->tree, te);
7557 static const struct got_error *
7558 tree_scroll_down(struct tog_view *view, int maxscroll)
7560 struct tog_tree_view_state *s = &view->state.tree;
7561 struct got_tree_entry *next, *last;
7562 int n = 0;
7564 if (s->first_displayed_entry)
7565 next = got_tree_entry_get_next(s->tree,
7566 s->first_displayed_entry);
7567 else
7568 next = got_object_tree_get_first_entry(s->tree);
7570 last = s->last_displayed_entry;
7571 while (next && n++ < maxscroll) {
7572 if (last) {
7573 s->last_displayed_entry = last;
7574 last = got_tree_entry_get_next(s->tree, last);
7576 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7577 s->first_displayed_entry = next;
7578 next = got_tree_entry_get_next(s->tree, next);
7582 return NULL;
7585 static const struct got_error *
7586 tree_entry_path(char **path, struct tog_parent_trees *parents,
7587 struct got_tree_entry *te)
7589 const struct got_error *err = NULL;
7590 struct tog_parent_tree *pt;
7591 size_t len = 2; /* for leading slash and NUL */
7593 TAILQ_FOREACH(pt, parents, entry)
7594 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7595 + 1 /* slash */;
7596 if (te)
7597 len += strlen(got_tree_entry_get_name(te));
7599 *path = calloc(1, len);
7600 if (path == NULL)
7601 return got_error_from_errno("calloc");
7603 (*path)[0] = '/';
7604 pt = TAILQ_LAST(parents, tog_parent_trees);
7605 while (pt) {
7606 const char *name = got_tree_entry_get_name(pt->selected_entry);
7607 if (strlcat(*path, name, len) >= len) {
7608 err = got_error(GOT_ERR_NO_SPACE);
7609 goto done;
7611 if (strlcat(*path, "/", len) >= len) {
7612 err = got_error(GOT_ERR_NO_SPACE);
7613 goto done;
7615 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7617 if (te) {
7618 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7619 err = got_error(GOT_ERR_NO_SPACE);
7620 goto done;
7623 done:
7624 if (err) {
7625 free(*path);
7626 *path = NULL;
7628 return err;
7631 static const struct got_error *
7632 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7633 struct got_tree_entry *te, struct tog_parent_trees *parents,
7634 struct got_object_id *commit_id, struct got_repository *repo)
7636 const struct got_error *err = NULL;
7637 char *path;
7638 struct tog_view *blame_view;
7640 *new_view = NULL;
7642 err = tree_entry_path(&path, parents, te);
7643 if (err)
7644 return err;
7646 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7647 if (blame_view == NULL) {
7648 err = got_error_from_errno("view_open");
7649 goto done;
7652 err = open_blame_view(blame_view, path, commit_id, repo);
7653 if (err) {
7654 if (err->code == GOT_ERR_CANCELLED)
7655 err = NULL;
7656 view_close(blame_view);
7657 } else
7658 *new_view = blame_view;
7659 done:
7660 free(path);
7661 return err;
7664 static const struct got_error *
7665 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7666 struct tog_tree_view_state *s)
7668 struct tog_view *log_view;
7669 const struct got_error *err = NULL;
7670 char *path;
7672 *new_view = NULL;
7674 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7675 if (log_view == NULL)
7676 return got_error_from_errno("view_open");
7678 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7679 if (err)
7680 return err;
7682 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7683 path, 0, NULL);
7684 if (err)
7685 view_close(log_view);
7686 else
7687 *new_view = log_view;
7688 free(path);
7689 return err;
7692 static const struct got_error *
7693 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7694 const char *head_ref_name, struct got_repository *repo)
7696 const struct got_error *err = NULL;
7697 char *commit_id_str = NULL;
7698 struct tog_tree_view_state *s = &view->state.tree;
7699 struct got_commit_object *commit = NULL;
7701 TAILQ_INIT(&s->parents);
7702 STAILQ_INIT(&s->colors);
7704 s->commit_id = got_object_id_dup(commit_id);
7705 if (s->commit_id == NULL) {
7706 err = got_error_from_errno("got_object_id_dup");
7707 goto done;
7710 err = got_object_open_as_commit(&commit, repo, commit_id);
7711 if (err)
7712 goto done;
7715 * The root is opened here and will be closed when the view is closed.
7716 * Any visited subtrees and their path-wise parents are opened and
7717 * closed on demand.
7719 err = got_object_open_as_tree(&s->root, repo,
7720 got_object_commit_get_tree_id(commit));
7721 if (err)
7722 goto done;
7723 s->tree = s->root;
7725 err = got_object_id_str(&commit_id_str, commit_id);
7726 if (err != NULL)
7727 goto done;
7729 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7730 err = got_error_from_errno("asprintf");
7731 goto done;
7734 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7735 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7736 if (head_ref_name) {
7737 s->head_ref_name = strdup(head_ref_name);
7738 if (s->head_ref_name == NULL) {
7739 err = got_error_from_errno("strdup");
7740 goto done;
7743 s->repo = repo;
7745 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7746 err = add_color(&s->colors, "\\$$",
7747 TOG_COLOR_TREE_SUBMODULE,
7748 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7749 if (err)
7750 goto done;
7751 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7752 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7753 if (err)
7754 goto done;
7755 err = add_color(&s->colors, "/$",
7756 TOG_COLOR_TREE_DIRECTORY,
7757 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7758 if (err)
7759 goto done;
7761 err = add_color(&s->colors, "\\*$",
7762 TOG_COLOR_TREE_EXECUTABLE,
7763 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7764 if (err)
7765 goto done;
7767 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7768 get_color_value("TOG_COLOR_COMMIT"));
7769 if (err)
7770 goto done;
7773 view->show = show_tree_view;
7774 view->input = input_tree_view;
7775 view->close = close_tree_view;
7776 view->search_start = search_start_tree_view;
7777 view->search_next = search_next_tree_view;
7778 done:
7779 free(commit_id_str);
7780 if (commit)
7781 got_object_commit_close(commit);
7782 if (err) {
7783 if (view->close == NULL)
7784 close_tree_view(view);
7785 view_close(view);
7787 return err;
7790 static const struct got_error *
7791 close_tree_view(struct tog_view *view)
7793 struct tog_tree_view_state *s = &view->state.tree;
7795 free_colors(&s->colors);
7796 free(s->tree_label);
7797 s->tree_label = NULL;
7798 free(s->commit_id);
7799 s->commit_id = NULL;
7800 free(s->head_ref_name);
7801 s->head_ref_name = NULL;
7802 while (!TAILQ_EMPTY(&s->parents)) {
7803 struct tog_parent_tree *parent;
7804 parent = TAILQ_FIRST(&s->parents);
7805 TAILQ_REMOVE(&s->parents, parent, entry);
7806 if (parent->tree != s->root)
7807 got_object_tree_close(parent->tree);
7808 free(parent);
7811 if (s->tree != NULL && s->tree != s->root)
7812 got_object_tree_close(s->tree);
7813 if (s->root)
7814 got_object_tree_close(s->root);
7815 return NULL;
7818 static const struct got_error *
7819 search_start_tree_view(struct tog_view *view)
7821 struct tog_tree_view_state *s = &view->state.tree;
7823 s->matched_entry = NULL;
7824 return NULL;
7827 static int
7828 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7830 regmatch_t regmatch;
7832 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7833 0) == 0;
7836 static const struct got_error *
7837 search_next_tree_view(struct tog_view *view)
7839 struct tog_tree_view_state *s = &view->state.tree;
7840 struct got_tree_entry *te = NULL;
7842 if (!view->searching) {
7843 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7844 return NULL;
7847 if (s->matched_entry) {
7848 if (view->searching == TOG_SEARCH_FORWARD) {
7849 if (s->selected_entry)
7850 te = got_tree_entry_get_next(s->tree,
7851 s->selected_entry);
7852 else
7853 te = got_object_tree_get_first_entry(s->tree);
7854 } else {
7855 if (s->selected_entry == NULL)
7856 te = got_object_tree_get_last_entry(s->tree);
7857 else
7858 te = got_tree_entry_get_prev(s->tree,
7859 s->selected_entry);
7861 } else {
7862 if (s->selected_entry)
7863 te = s->selected_entry;
7864 else if (view->searching == TOG_SEARCH_FORWARD)
7865 te = got_object_tree_get_first_entry(s->tree);
7866 else
7867 te = got_object_tree_get_last_entry(s->tree);
7870 while (1) {
7871 if (te == NULL) {
7872 if (s->matched_entry == NULL) {
7873 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7874 return NULL;
7876 if (view->searching == TOG_SEARCH_FORWARD)
7877 te = got_object_tree_get_first_entry(s->tree);
7878 else
7879 te = got_object_tree_get_last_entry(s->tree);
7882 if (match_tree_entry(te, &view->regex)) {
7883 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7884 s->matched_entry = te;
7885 break;
7888 if (view->searching == TOG_SEARCH_FORWARD)
7889 te = got_tree_entry_get_next(s->tree, te);
7890 else
7891 te = got_tree_entry_get_prev(s->tree, te);
7894 if (s->matched_entry) {
7895 s->first_displayed_entry = s->matched_entry;
7896 s->selected = 0;
7899 return NULL;
7902 static const struct got_error *
7903 show_tree_view(struct tog_view *view)
7905 const struct got_error *err = NULL;
7906 struct tog_tree_view_state *s = &view->state.tree;
7907 char *parent_path;
7909 err = tree_entry_path(&parent_path, &s->parents, NULL);
7910 if (err)
7911 return err;
7913 err = draw_tree_entries(view, parent_path);
7914 free(parent_path);
7916 view_border(view);
7917 return err;
7920 static const struct got_error *
7921 tree_goto_line(struct tog_view *view, int nlines)
7923 const struct got_error *err = NULL;
7924 struct tog_tree_view_state *s = &view->state.tree;
7925 struct got_tree_entry **fte, **lte, **ste;
7926 int g, last, first = 1, i = 1;
7927 int root = s->tree == s->root;
7928 int off = root ? 1 : 2;
7930 g = view->gline;
7931 view->gline = 0;
7933 if (g == 0)
7934 g = 1;
7935 else if (g > got_object_tree_get_nentries(s->tree))
7936 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7938 fte = &s->first_displayed_entry;
7939 lte = &s->last_displayed_entry;
7940 ste = &s->selected_entry;
7942 if (*fte != NULL) {
7943 first = got_tree_entry_get_index(*fte);
7944 first += off; /* account for ".." */
7946 last = got_tree_entry_get_index(*lte);
7947 last += off;
7949 if (g >= first && g <= last && g - first < nlines) {
7950 s->selected = g - first;
7951 return NULL; /* gline is on the current page */
7954 if (*ste != NULL) {
7955 i = got_tree_entry_get_index(*ste);
7956 i += off;
7959 if (i < g) {
7960 err = tree_scroll_down(view, g - i);
7961 if (err)
7962 return err;
7963 if (got_tree_entry_get_index(*lte) >=
7964 got_object_tree_get_nentries(s->tree) - 1 &&
7965 first + s->selected < g &&
7966 s->selected < s->ndisplayed - 1) {
7967 first = got_tree_entry_get_index(*fte);
7968 first += off;
7969 s->selected = g - first;
7971 } else if (i > g)
7972 tree_scroll_up(s, i - g);
7974 if (g < nlines &&
7975 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7976 s->selected = g - 1;
7978 return NULL;
7981 static const struct got_error *
7982 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7984 const struct got_error *err = NULL;
7985 struct tog_tree_view_state *s = &view->state.tree;
7986 struct got_tree_entry *te;
7987 int n, nscroll = view->nlines - 3;
7989 if (view->gline)
7990 return tree_goto_line(view, nscroll);
7992 switch (ch) {
7993 case '0':
7994 case '$':
7995 case KEY_RIGHT:
7996 case 'l':
7997 case KEY_LEFT:
7998 case 'h':
7999 horizontal_scroll_input(view, ch);
8000 break;
8001 case 'i':
8002 s->show_ids = !s->show_ids;
8003 view->count = 0;
8004 break;
8005 case 'L':
8006 view->count = 0;
8007 if (!s->selected_entry)
8008 break;
8009 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8010 break;
8011 case 'R':
8012 view->count = 0;
8013 err = view_request_new(new_view, view, TOG_VIEW_REF);
8014 break;
8015 case 'g':
8016 case '=':
8017 case KEY_HOME:
8018 s->selected = 0;
8019 view->count = 0;
8020 if (s->tree == s->root)
8021 s->first_displayed_entry =
8022 got_object_tree_get_first_entry(s->tree);
8023 else
8024 s->first_displayed_entry = NULL;
8025 break;
8026 case 'G':
8027 case '*':
8028 case KEY_END: {
8029 int eos = view->nlines - 3;
8031 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8032 --eos; /* border */
8033 s->selected = 0;
8034 view->count = 0;
8035 te = got_object_tree_get_last_entry(s->tree);
8036 for (n = 0; n < eos; n++) {
8037 if (te == NULL) {
8038 if (s->tree != s->root) {
8039 s->first_displayed_entry = NULL;
8040 n++;
8042 break;
8044 s->first_displayed_entry = te;
8045 te = got_tree_entry_get_prev(s->tree, te);
8047 if (n > 0)
8048 s->selected = n - 1;
8049 break;
8051 case 'k':
8052 case KEY_UP:
8053 case CTRL('p'):
8054 if (s->selected > 0) {
8055 s->selected--;
8056 break;
8058 tree_scroll_up(s, 1);
8059 if (s->selected_entry == NULL ||
8060 (s->tree == s->root && s->selected_entry ==
8061 got_object_tree_get_first_entry(s->tree)))
8062 view->count = 0;
8063 break;
8064 case CTRL('u'):
8065 case 'u':
8066 nscroll /= 2;
8067 /* FALL THROUGH */
8068 case KEY_PPAGE:
8069 case CTRL('b'):
8070 case 'b':
8071 if (s->tree == s->root) {
8072 if (got_object_tree_get_first_entry(s->tree) ==
8073 s->first_displayed_entry)
8074 s->selected -= MIN(s->selected, nscroll);
8075 } else {
8076 if (s->first_displayed_entry == NULL)
8077 s->selected -= MIN(s->selected, nscroll);
8079 tree_scroll_up(s, MAX(0, nscroll));
8080 if (s->selected_entry == NULL ||
8081 (s->tree == s->root && s->selected_entry ==
8082 got_object_tree_get_first_entry(s->tree)))
8083 view->count = 0;
8084 break;
8085 case 'j':
8086 case KEY_DOWN:
8087 case CTRL('n'):
8088 if (s->selected < s->ndisplayed - 1) {
8089 s->selected++;
8090 break;
8092 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8093 == NULL) {
8094 /* can't scroll any further */
8095 view->count = 0;
8096 break;
8098 tree_scroll_down(view, 1);
8099 break;
8100 case CTRL('d'):
8101 case 'd':
8102 nscroll /= 2;
8103 /* FALL THROUGH */
8104 case KEY_NPAGE:
8105 case CTRL('f'):
8106 case 'f':
8107 case ' ':
8108 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8109 == NULL) {
8110 /* can't scroll any further; move cursor down */
8111 if (s->selected < s->ndisplayed - 1)
8112 s->selected += MIN(nscroll,
8113 s->ndisplayed - s->selected - 1);
8114 else
8115 view->count = 0;
8116 break;
8118 tree_scroll_down(view, nscroll);
8119 break;
8120 case KEY_ENTER:
8121 case '\r':
8122 case KEY_BACKSPACE:
8123 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
8124 struct tog_parent_tree *parent;
8125 /* user selected '..' */
8126 if (s->tree == s->root) {
8127 view->count = 0;
8128 break;
8130 parent = TAILQ_FIRST(&s->parents);
8131 TAILQ_REMOVE(&s->parents, parent,
8132 entry);
8133 got_object_tree_close(s->tree);
8134 s->tree = parent->tree;
8135 s->first_displayed_entry =
8136 parent->first_displayed_entry;
8137 s->selected_entry =
8138 parent->selected_entry;
8139 s->selected = parent->selected;
8140 if (s->selected > view->nlines - 3) {
8141 err = offset_selection_down(view);
8142 if (err)
8143 break;
8145 free(parent);
8146 } else if (S_ISDIR(got_tree_entry_get_mode(
8147 s->selected_entry))) {
8148 struct got_tree_object *subtree;
8149 view->count = 0;
8150 err = got_object_open_as_tree(&subtree, s->repo,
8151 got_tree_entry_get_id(s->selected_entry));
8152 if (err)
8153 break;
8154 err = tree_view_visit_subtree(s, subtree);
8155 if (err) {
8156 got_object_tree_close(subtree);
8157 break;
8159 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
8160 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
8161 break;
8162 case KEY_RESIZE:
8163 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
8164 s->selected = view->nlines - 4;
8165 view->count = 0;
8166 break;
8167 default:
8168 view->count = 0;
8169 break;
8172 return err;
8175 __dead static void
8176 usage_tree(void)
8178 endwin();
8179 fprintf(stderr,
8180 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
8181 getprogname());
8182 exit(1);
8185 static const struct got_error *
8186 cmd_tree(int argc, char *argv[])
8188 const struct got_error *error;
8189 struct got_repository *repo = NULL;
8190 struct got_worktree *worktree = NULL;
8191 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8192 struct got_object_id *commit_id = NULL;
8193 struct got_commit_object *commit = NULL;
8194 const char *commit_id_arg = NULL;
8195 char *keyword_idstr = NULL, *label = NULL;
8196 struct got_reference *ref = NULL;
8197 const char *head_ref_name = NULL;
8198 int ch;
8199 struct tog_view *view;
8200 int *pack_fds = NULL;
8202 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
8203 switch (ch) {
8204 case 'c':
8205 commit_id_arg = optarg;
8206 break;
8207 case 'r':
8208 repo_path = realpath(optarg, NULL);
8209 if (repo_path == NULL)
8210 return got_error_from_errno2("realpath",
8211 optarg);
8212 break;
8213 default:
8214 usage_tree();
8215 /* NOTREACHED */
8219 argc -= optind;
8220 argv += optind;
8222 if (argc > 1)
8223 usage_tree();
8225 error = got_repo_pack_fds_open(&pack_fds);
8226 if (error != NULL)
8227 goto done;
8229 if (repo_path == NULL) {
8230 cwd = getcwd(NULL, 0);
8231 if (cwd == NULL)
8232 return got_error_from_errno("getcwd");
8233 error = got_worktree_open(&worktree, cwd, NULL);
8234 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8235 goto done;
8236 if (worktree)
8237 repo_path =
8238 strdup(got_worktree_get_repo_path(worktree));
8239 else
8240 repo_path = strdup(cwd);
8241 if (repo_path == NULL) {
8242 error = got_error_from_errno("strdup");
8243 goto done;
8247 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8248 if (error != NULL)
8249 goto done;
8251 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8252 repo, worktree);
8253 if (error)
8254 goto done;
8256 init_curses();
8258 error = apply_unveil(got_repo_get_path(repo), NULL);
8259 if (error)
8260 goto done;
8262 error = tog_load_refs(repo, 0);
8263 if (error)
8264 goto done;
8266 if (commit_id_arg == NULL) {
8267 error = got_repo_match_object_id(&commit_id, &label,
8268 worktree ? got_worktree_get_head_ref_name(worktree) :
8269 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8270 if (error)
8271 goto done;
8272 head_ref_name = label;
8273 } else {
8274 error = got_keyword_to_idstr(&keyword_idstr, commit_id_arg,
8275 repo, worktree);
8276 if (error != NULL)
8277 goto done;
8278 if (keyword_idstr != NULL)
8279 commit_id_arg = keyword_idstr;
8281 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8282 if (error == NULL)
8283 head_ref_name = got_ref_get_name(ref);
8284 else if (error->code != GOT_ERR_NOT_REF)
8285 goto done;
8286 error = got_repo_match_object_id(&commit_id, NULL,
8287 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8288 if (error)
8289 goto done;
8292 error = got_object_open_as_commit(&commit, repo, commit_id);
8293 if (error)
8294 goto done;
8296 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8297 if (view == NULL) {
8298 error = got_error_from_errno("view_open");
8299 goto done;
8301 error = open_tree_view(view, commit_id, head_ref_name, repo);
8302 if (error)
8303 goto done;
8304 if (!got_path_is_root_dir(in_repo_path)) {
8305 error = tree_view_walk_path(&view->state.tree, commit,
8306 in_repo_path);
8307 if (error)
8308 goto done;
8311 if (worktree) {
8312 error = set_tog_base_commit(repo, worktree);
8313 if (error != NULL)
8314 goto done;
8316 /* Release work tree lock. */
8317 got_worktree_close(worktree);
8318 worktree = NULL;
8321 error = view_loop(view);
8323 done:
8324 free(tog_base_commit.id);
8325 free(keyword_idstr);
8326 free(repo_path);
8327 free(cwd);
8328 free(commit_id);
8329 free(label);
8330 if (ref)
8331 got_ref_close(ref);
8332 if (worktree != NULL)
8333 got_worktree_close(worktree);
8334 if (repo) {
8335 const struct got_error *close_err = got_repo_close(repo);
8336 if (error == NULL)
8337 error = close_err;
8339 if (pack_fds) {
8340 const struct got_error *pack_err =
8341 got_repo_pack_fds_close(pack_fds);
8342 if (error == NULL)
8343 error = pack_err;
8345 tog_free_refs();
8346 return error;
8349 static const struct got_error *
8350 ref_view_load_refs(struct tog_ref_view_state *s)
8352 struct got_reflist_entry *sre;
8353 struct tog_reflist_entry *re;
8355 s->nrefs = 0;
8356 TAILQ_FOREACH(sre, &tog_refs, entry) {
8357 if (strncmp(got_ref_get_name(sre->ref),
8358 "refs/got/", 9) == 0 &&
8359 strncmp(got_ref_get_name(sre->ref),
8360 "refs/got/backup/", 16) != 0)
8361 continue;
8363 re = malloc(sizeof(*re));
8364 if (re == NULL)
8365 return got_error_from_errno("malloc");
8367 re->ref = got_ref_dup(sre->ref);
8368 if (re->ref == NULL)
8369 return got_error_from_errno("got_ref_dup");
8370 re->idx = s->nrefs++;
8371 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8374 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8375 return NULL;
8378 static void
8379 ref_view_free_refs(struct tog_ref_view_state *s)
8381 struct tog_reflist_entry *re;
8383 while (!TAILQ_EMPTY(&s->refs)) {
8384 re = TAILQ_FIRST(&s->refs);
8385 TAILQ_REMOVE(&s->refs, re, entry);
8386 got_ref_close(re->ref);
8387 free(re);
8391 static const struct got_error *
8392 open_ref_view(struct tog_view *view, struct got_repository *repo)
8394 const struct got_error *err = NULL;
8395 struct tog_ref_view_state *s = &view->state.ref;
8397 s->selected_entry = 0;
8398 s->repo = repo;
8400 TAILQ_INIT(&s->refs);
8401 STAILQ_INIT(&s->colors);
8403 err = ref_view_load_refs(s);
8404 if (err)
8405 goto done;
8407 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8408 err = add_color(&s->colors, "^refs/heads/",
8409 TOG_COLOR_REFS_HEADS,
8410 get_color_value("TOG_COLOR_REFS_HEADS"));
8411 if (err)
8412 goto done;
8414 err = add_color(&s->colors, "^refs/tags/",
8415 TOG_COLOR_REFS_TAGS,
8416 get_color_value("TOG_COLOR_REFS_TAGS"));
8417 if (err)
8418 goto done;
8420 err = add_color(&s->colors, "^refs/remotes/",
8421 TOG_COLOR_REFS_REMOTES,
8422 get_color_value("TOG_COLOR_REFS_REMOTES"));
8423 if (err)
8424 goto done;
8426 err = add_color(&s->colors, "^refs/got/backup/",
8427 TOG_COLOR_REFS_BACKUP,
8428 get_color_value("TOG_COLOR_REFS_BACKUP"));
8429 if (err)
8430 goto done;
8433 view->show = show_ref_view;
8434 view->input = input_ref_view;
8435 view->close = close_ref_view;
8436 view->search_start = search_start_ref_view;
8437 view->search_next = search_next_ref_view;
8438 done:
8439 if (err) {
8440 if (view->close == NULL)
8441 close_ref_view(view);
8442 view_close(view);
8444 return err;
8447 static const struct got_error *
8448 close_ref_view(struct tog_view *view)
8450 struct tog_ref_view_state *s = &view->state.ref;
8452 ref_view_free_refs(s);
8453 free_colors(&s->colors);
8455 return NULL;
8458 static const struct got_error *
8459 resolve_reflist_entry(struct got_object_id **commit_id,
8460 struct tog_reflist_entry *re, struct got_repository *repo)
8462 const struct got_error *err = NULL;
8463 struct got_object_id *obj_id;
8464 struct got_tag_object *tag = NULL;
8465 int obj_type;
8467 *commit_id = NULL;
8469 err = got_ref_resolve(&obj_id, repo, re->ref);
8470 if (err)
8471 return err;
8473 err = got_object_get_type(&obj_type, repo, obj_id);
8474 if (err)
8475 goto done;
8477 switch (obj_type) {
8478 case GOT_OBJ_TYPE_COMMIT:
8479 *commit_id = obj_id;
8480 break;
8481 case GOT_OBJ_TYPE_TAG:
8482 err = got_object_open_as_tag(&tag, repo, obj_id);
8483 if (err)
8484 goto done;
8485 free(obj_id);
8486 err = got_object_get_type(&obj_type, repo,
8487 got_object_tag_get_object_id(tag));
8488 if (err)
8489 goto done;
8490 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8491 err = got_error(GOT_ERR_OBJ_TYPE);
8492 goto done;
8494 *commit_id = got_object_id_dup(
8495 got_object_tag_get_object_id(tag));
8496 if (*commit_id == NULL) {
8497 err = got_error_from_errno("got_object_id_dup");
8498 goto done;
8500 break;
8501 default:
8502 err = got_error(GOT_ERR_OBJ_TYPE);
8503 break;
8506 done:
8507 if (tag)
8508 got_object_tag_close(tag);
8509 if (err) {
8510 free(*commit_id);
8511 *commit_id = NULL;
8513 return err;
8516 static const struct got_error *
8517 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8518 struct tog_reflist_entry *re, struct got_repository *repo)
8520 struct tog_view *log_view;
8521 const struct got_error *err = NULL;
8522 struct got_object_id *commit_id = NULL;
8524 *new_view = NULL;
8526 err = resolve_reflist_entry(&commit_id, re, repo);
8527 if (err) {
8528 if (err->code != GOT_ERR_OBJ_TYPE)
8529 return err;
8530 else
8531 return NULL;
8534 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8535 if (log_view == NULL) {
8536 err = got_error_from_errno("view_open");
8537 goto done;
8540 err = open_log_view(log_view, commit_id, repo,
8541 got_ref_get_name(re->ref), "", 0, NULL);
8542 done:
8543 if (err)
8544 view_close(log_view);
8545 else
8546 *new_view = log_view;
8547 free(commit_id);
8548 return err;
8551 static void
8552 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8554 struct tog_reflist_entry *re;
8555 int i = 0;
8557 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8558 return;
8560 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8561 while (i++ < maxscroll) {
8562 if (re == NULL)
8563 break;
8564 s->first_displayed_entry = re;
8565 re = TAILQ_PREV(re, tog_reflist_head, entry);
8569 static const struct got_error *
8570 ref_scroll_down(struct tog_view *view, int maxscroll)
8572 struct tog_ref_view_state *s = &view->state.ref;
8573 struct tog_reflist_entry *next, *last;
8574 int n = 0;
8576 if (s->first_displayed_entry)
8577 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8578 else
8579 next = TAILQ_FIRST(&s->refs);
8581 last = s->last_displayed_entry;
8582 while (next && n++ < maxscroll) {
8583 if (last) {
8584 s->last_displayed_entry = last;
8585 last = TAILQ_NEXT(last, entry);
8587 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8588 s->first_displayed_entry = next;
8589 next = TAILQ_NEXT(next, entry);
8593 return NULL;
8596 static const struct got_error *
8597 search_start_ref_view(struct tog_view *view)
8599 struct tog_ref_view_state *s = &view->state.ref;
8601 s->matched_entry = NULL;
8602 return NULL;
8605 static int
8606 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8608 regmatch_t regmatch;
8610 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8611 0) == 0;
8614 static const struct got_error *
8615 search_next_ref_view(struct tog_view *view)
8617 struct tog_ref_view_state *s = &view->state.ref;
8618 struct tog_reflist_entry *re = NULL;
8620 if (!view->searching) {
8621 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8622 return NULL;
8625 if (s->matched_entry) {
8626 if (view->searching == TOG_SEARCH_FORWARD) {
8627 if (s->selected_entry)
8628 re = TAILQ_NEXT(s->selected_entry, entry);
8629 else
8630 re = TAILQ_PREV(s->selected_entry,
8631 tog_reflist_head, entry);
8632 } else {
8633 if (s->selected_entry == NULL)
8634 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8635 else
8636 re = TAILQ_PREV(s->selected_entry,
8637 tog_reflist_head, entry);
8639 } else {
8640 if (s->selected_entry)
8641 re = s->selected_entry;
8642 else if (view->searching == TOG_SEARCH_FORWARD)
8643 re = TAILQ_FIRST(&s->refs);
8644 else
8645 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8648 while (1) {
8649 if (re == NULL) {
8650 if (s->matched_entry == NULL) {
8651 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8652 return NULL;
8654 if (view->searching == TOG_SEARCH_FORWARD)
8655 re = TAILQ_FIRST(&s->refs);
8656 else
8657 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8660 if (match_reflist_entry(re, &view->regex)) {
8661 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8662 s->matched_entry = re;
8663 break;
8666 if (view->searching == TOG_SEARCH_FORWARD)
8667 re = TAILQ_NEXT(re, entry);
8668 else
8669 re = TAILQ_PREV(re, tog_reflist_head, entry);
8672 if (s->matched_entry) {
8673 s->first_displayed_entry = s->matched_entry;
8674 s->selected = 0;
8677 return NULL;
8680 static const struct got_error *
8681 show_ref_view(struct tog_view *view)
8683 const struct got_error *err = NULL;
8684 struct tog_ref_view_state *s = &view->state.ref;
8685 struct tog_reflist_entry *re;
8686 char *line = NULL;
8687 wchar_t *wline;
8688 struct tog_color *tc;
8689 int width, n, scrollx;
8690 int limit = view->nlines;
8692 werase(view->window);
8694 s->ndisplayed = 0;
8695 if (view_is_hsplit_top(view))
8696 --limit; /* border */
8698 if (limit == 0)
8699 return NULL;
8701 re = s->first_displayed_entry;
8703 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8704 s->nrefs) == -1)
8705 return got_error_from_errno("asprintf");
8707 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8708 if (err) {
8709 free(line);
8710 return err;
8712 if (view_needs_focus_indication(view))
8713 wstandout(view->window);
8714 waddwstr(view->window, wline);
8715 while (width++ < view->ncols)
8716 waddch(view->window, ' ');
8717 if (view_needs_focus_indication(view))
8718 wstandend(view->window);
8719 free(wline);
8720 wline = NULL;
8721 free(line);
8722 line = NULL;
8723 if (--limit <= 0)
8724 return NULL;
8726 n = 0;
8727 view->maxx = 0;
8728 while (re && limit > 0) {
8729 char *line = NULL;
8730 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8732 if (s->show_date) {
8733 struct got_commit_object *ci;
8734 struct got_tag_object *tag;
8735 struct got_object_id *id;
8736 struct tm tm;
8737 time_t t;
8739 err = got_ref_resolve(&id, s->repo, re->ref);
8740 if (err)
8741 return err;
8742 err = got_object_open_as_tag(&tag, s->repo, id);
8743 if (err) {
8744 if (err->code != GOT_ERR_OBJ_TYPE) {
8745 free(id);
8746 return err;
8748 err = got_object_open_as_commit(&ci, s->repo,
8749 id);
8750 if (err) {
8751 free(id);
8752 return err;
8754 t = got_object_commit_get_committer_time(ci);
8755 got_object_commit_close(ci);
8756 } else {
8757 t = got_object_tag_get_tagger_time(tag);
8758 got_object_tag_close(tag);
8760 free(id);
8761 if (gmtime_r(&t, &tm) == NULL)
8762 return got_error_from_errno("gmtime_r");
8763 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8764 return got_error(GOT_ERR_NO_SPACE);
8766 if (got_ref_is_symbolic(re->ref)) {
8767 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8768 ymd : "", got_ref_get_name(re->ref),
8769 got_ref_get_symref_target(re->ref)) == -1)
8770 return got_error_from_errno("asprintf");
8771 } else if (s->show_ids) {
8772 struct got_object_id *id;
8773 char *id_str;
8774 err = got_ref_resolve(&id, s->repo, re->ref);
8775 if (err)
8776 return err;
8777 err = got_object_id_str(&id_str, id);
8778 if (err) {
8779 free(id);
8780 return err;
8782 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8783 got_ref_get_name(re->ref), id_str) == -1) {
8784 err = got_error_from_errno("asprintf");
8785 free(id);
8786 free(id_str);
8787 return err;
8789 free(id);
8790 free(id_str);
8791 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8792 got_ref_get_name(re->ref)) == -1)
8793 return got_error_from_errno("asprintf");
8795 /* use full line width to determine view->maxx */
8796 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8797 if (err) {
8798 free(line);
8799 return err;
8801 view->maxx = MAX(view->maxx, width);
8802 free(wline);
8803 wline = NULL;
8805 err = format_line(&wline, &width, &scrollx, line, view->x,
8806 view->ncols, 0, 0);
8807 if (err) {
8808 free(line);
8809 return err;
8811 if (n == s->selected) {
8812 if (view->focussed)
8813 wstandout(view->window);
8814 s->selected_entry = re;
8816 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8817 if (tc)
8818 wattr_on(view->window,
8819 COLOR_PAIR(tc->colorpair), NULL);
8820 waddwstr(view->window, &wline[scrollx]);
8821 if (tc)
8822 wattr_off(view->window,
8823 COLOR_PAIR(tc->colorpair), NULL);
8824 if (width < view->ncols)
8825 waddch(view->window, '\n');
8826 if (n == s->selected && view->focussed)
8827 wstandend(view->window);
8828 free(line);
8829 free(wline);
8830 wline = NULL;
8831 n++;
8832 s->ndisplayed++;
8833 s->last_displayed_entry = re;
8835 limit--;
8836 re = TAILQ_NEXT(re, entry);
8839 view_border(view);
8840 return err;
8843 static const struct got_error *
8844 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8845 struct tog_reflist_entry *re, struct got_repository *repo)
8847 const struct got_error *err = NULL;
8848 struct got_object_id *commit_id = NULL;
8849 struct tog_view *tree_view;
8851 *new_view = NULL;
8853 err = resolve_reflist_entry(&commit_id, re, repo);
8854 if (err) {
8855 if (err->code != GOT_ERR_OBJ_TYPE)
8856 return err;
8857 else
8858 return NULL;
8862 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8863 if (tree_view == NULL) {
8864 err = got_error_from_errno("view_open");
8865 goto done;
8868 err = open_tree_view(tree_view, commit_id,
8869 got_ref_get_name(re->ref), repo);
8870 if (err)
8871 goto done;
8873 *new_view = tree_view;
8874 done:
8875 free(commit_id);
8876 return err;
8879 static const struct got_error *
8880 ref_goto_line(struct tog_view *view, int nlines)
8882 const struct got_error *err = NULL;
8883 struct tog_ref_view_state *s = &view->state.ref;
8884 int g, idx = s->selected_entry->idx;
8886 g = view->gline;
8887 view->gline = 0;
8889 if (g == 0)
8890 g = 1;
8891 else if (g > s->nrefs)
8892 g = s->nrefs;
8894 if (g >= s->first_displayed_entry->idx + 1 &&
8895 g <= s->last_displayed_entry->idx + 1 &&
8896 g - s->first_displayed_entry->idx - 1 < nlines) {
8897 s->selected = g - s->first_displayed_entry->idx - 1;
8898 return NULL;
8901 if (idx + 1 < g) {
8902 err = ref_scroll_down(view, g - idx - 1);
8903 if (err)
8904 return err;
8905 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8906 s->first_displayed_entry->idx + s->selected < g &&
8907 s->selected < s->ndisplayed - 1)
8908 s->selected = g - s->first_displayed_entry->idx - 1;
8909 } else if (idx + 1 > g)
8910 ref_scroll_up(s, idx - g + 1);
8912 if (g < nlines && s->first_displayed_entry->idx == 0)
8913 s->selected = g - 1;
8915 return NULL;
8919 static const struct got_error *
8920 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8922 const struct got_error *err = NULL;
8923 struct tog_ref_view_state *s = &view->state.ref;
8924 struct tog_reflist_entry *re;
8925 int n, nscroll = view->nlines - 1;
8927 if (view->gline)
8928 return ref_goto_line(view, nscroll);
8930 switch (ch) {
8931 case '0':
8932 case '$':
8933 case KEY_RIGHT:
8934 case 'l':
8935 case KEY_LEFT:
8936 case 'h':
8937 horizontal_scroll_input(view, ch);
8938 break;
8939 case 'i':
8940 s->show_ids = !s->show_ids;
8941 view->count = 0;
8942 break;
8943 case 'm':
8944 s->show_date = !s->show_date;
8945 view->count = 0;
8946 break;
8947 case 'o':
8948 s->sort_by_date = !s->sort_by_date;
8949 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8950 view->count = 0;
8951 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8952 got_ref_cmp_by_commit_timestamp_descending :
8953 tog_ref_cmp_by_name, s->repo);
8954 if (err)
8955 break;
8956 got_reflist_object_id_map_free(tog_refs_idmap);
8957 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8958 &tog_refs, s->repo);
8959 if (err)
8960 break;
8961 ref_view_free_refs(s);
8962 err = ref_view_load_refs(s);
8963 break;
8964 case KEY_ENTER:
8965 case '\r':
8966 view->count = 0;
8967 if (!s->selected_entry)
8968 break;
8969 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8970 break;
8971 case 'T':
8972 view->count = 0;
8973 if (!s->selected_entry)
8974 break;
8975 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8976 break;
8977 case 'g':
8978 case '=':
8979 case KEY_HOME:
8980 s->selected = 0;
8981 view->count = 0;
8982 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8983 break;
8984 case 'G':
8985 case '*':
8986 case KEY_END: {
8987 int eos = view->nlines - 1;
8989 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8990 --eos; /* border */
8991 s->selected = 0;
8992 view->count = 0;
8993 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8994 for (n = 0; n < eos; n++) {
8995 if (re == NULL)
8996 break;
8997 s->first_displayed_entry = re;
8998 re = TAILQ_PREV(re, tog_reflist_head, entry);
9000 if (n > 0)
9001 s->selected = n - 1;
9002 break;
9004 case 'k':
9005 case KEY_UP:
9006 case CTRL('p'):
9007 if (s->selected > 0) {
9008 s->selected--;
9009 break;
9011 ref_scroll_up(s, 1);
9012 if (s->selected_entry == TAILQ_FIRST(&s->refs))
9013 view->count = 0;
9014 break;
9015 case CTRL('u'):
9016 case 'u':
9017 nscroll /= 2;
9018 /* FALL THROUGH */
9019 case KEY_PPAGE:
9020 case CTRL('b'):
9021 case 'b':
9022 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
9023 s->selected -= MIN(nscroll, s->selected);
9024 ref_scroll_up(s, MAX(0, nscroll));
9025 if (s->selected_entry == TAILQ_FIRST(&s->refs))
9026 view->count = 0;
9027 break;
9028 case 'j':
9029 case KEY_DOWN:
9030 case CTRL('n'):
9031 if (s->selected < s->ndisplayed - 1) {
9032 s->selected++;
9033 break;
9035 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
9036 /* can't scroll any further */
9037 view->count = 0;
9038 break;
9040 ref_scroll_down(view, 1);
9041 break;
9042 case CTRL('d'):
9043 case 'd':
9044 nscroll /= 2;
9045 /* FALL THROUGH */
9046 case KEY_NPAGE:
9047 case CTRL('f'):
9048 case 'f':
9049 case ' ':
9050 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
9051 /* can't scroll any further; move cursor down */
9052 if (s->selected < s->ndisplayed - 1)
9053 s->selected += MIN(nscroll,
9054 s->ndisplayed - s->selected - 1);
9055 if (view->count > 1 && s->selected < s->ndisplayed - 1)
9056 s->selected += s->ndisplayed - s->selected - 1;
9057 view->count = 0;
9058 break;
9060 ref_scroll_down(view, nscroll);
9061 break;
9062 case CTRL('l'):
9063 view->count = 0;
9064 tog_free_refs();
9065 err = tog_load_refs(s->repo, s->sort_by_date);
9066 if (err)
9067 break;
9068 ref_view_free_refs(s);
9069 err = ref_view_load_refs(s);
9070 break;
9071 case KEY_RESIZE:
9072 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
9073 s->selected = view->nlines - 2;
9074 break;
9075 default:
9076 view->count = 0;
9077 break;
9080 return err;
9083 __dead static void
9084 usage_ref(void)
9086 endwin();
9087 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
9088 getprogname());
9089 exit(1);
9092 static const struct got_error *
9093 cmd_ref(int argc, char *argv[])
9095 const struct got_error *error;
9096 struct got_repository *repo = NULL;
9097 struct got_worktree *worktree = NULL;
9098 char *cwd = NULL, *repo_path = NULL;
9099 int ch;
9100 struct tog_view *view;
9101 int *pack_fds = NULL;
9103 while ((ch = getopt(argc, argv, "r:")) != -1) {
9104 switch (ch) {
9105 case 'r':
9106 repo_path = realpath(optarg, NULL);
9107 if (repo_path == NULL)
9108 return got_error_from_errno2("realpath",
9109 optarg);
9110 break;
9111 default:
9112 usage_ref();
9113 /* NOTREACHED */
9117 argc -= optind;
9118 argv += optind;
9120 if (argc > 1)
9121 usage_ref();
9123 error = got_repo_pack_fds_open(&pack_fds);
9124 if (error != NULL)
9125 goto done;
9127 if (repo_path == NULL) {
9128 cwd = getcwd(NULL, 0);
9129 if (cwd == NULL)
9130 return got_error_from_errno("getcwd");
9131 error = got_worktree_open(&worktree, cwd, NULL);
9132 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9133 goto done;
9134 if (worktree)
9135 repo_path =
9136 strdup(got_worktree_get_repo_path(worktree));
9137 else
9138 repo_path = strdup(cwd);
9139 if (repo_path == NULL) {
9140 error = got_error_from_errno("strdup");
9141 goto done;
9145 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9146 if (error != NULL)
9147 goto done;
9149 init_curses();
9151 error = apply_unveil(got_repo_get_path(repo), NULL);
9152 if (error)
9153 goto done;
9155 error = tog_load_refs(repo, 0);
9156 if (error)
9157 goto done;
9159 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
9160 if (view == NULL) {
9161 error = got_error_from_errno("view_open");
9162 goto done;
9165 error = open_ref_view(view, repo);
9166 if (error)
9167 goto done;
9169 if (worktree) {
9170 error = set_tog_base_commit(repo, worktree);
9171 if (error != NULL)
9172 goto done;
9174 /* Release work tree lock. */
9175 got_worktree_close(worktree);
9176 worktree = NULL;
9179 error = view_loop(view);
9181 done:
9182 free(tog_base_commit.id);
9183 free(repo_path);
9184 free(cwd);
9185 if (worktree != NULL)
9186 got_worktree_close(worktree);
9187 if (repo) {
9188 const struct got_error *close_err = got_repo_close(repo);
9189 if (close_err)
9190 error = close_err;
9192 if (pack_fds) {
9193 const struct got_error *pack_err =
9194 got_repo_pack_fds_close(pack_fds);
9195 if (error == NULL)
9196 error = pack_err;
9198 tog_free_refs();
9199 return error;
9202 static const struct got_error*
9203 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
9204 const char *str)
9206 size_t len;
9208 if (win == NULL)
9209 win = stdscr;
9211 len = strlen(str);
9212 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
9214 if (focus)
9215 wstandout(win);
9216 if (mvwprintw(win, y, x, "%s", str) == ERR)
9217 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
9218 if (focus)
9219 wstandend(win);
9221 return NULL;
9224 static const struct got_error *
9225 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
9227 off_t *p;
9229 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
9230 if (p == NULL) {
9231 free(*line_offsets);
9232 *line_offsets = NULL;
9233 return got_error_from_errno("reallocarray");
9236 *line_offsets = p;
9237 (*line_offsets)[*nlines] = off;
9238 ++(*nlines);
9239 return NULL;
9242 static const struct got_error *
9243 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
9245 *ret = 0;
9247 for (;n > 0; --n, ++km) {
9248 char *t0, *t, *k;
9249 size_t len = 1;
9251 if (km->keys == NULL)
9252 continue;
9254 t = t0 = strdup(km->keys);
9255 if (t0 == NULL)
9256 return got_error_from_errno("strdup");
9258 len += strlen(t);
9259 while ((k = strsep(&t, " ")) != NULL)
9260 len += strlen(k) > 1 ? 2 : 0;
9261 free(t0);
9262 *ret = MAX(*ret, len);
9265 return NULL;
9269 * Write keymap section headers, keys, and key info in km to f.
9270 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9271 * wrap control and symbolic keys in guillemets, else use <>.
9273 static const struct got_error *
9274 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9276 int n, len = width;
9278 if (km->keys) {
9279 static const char *u8_glyph[] = {
9280 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9281 "\xe2\x80\xba" /* U+203A (utf8 >) */
9283 char *t0, *t, *k;
9284 int cs, s, first = 1;
9286 cs = got_locale_is_utf8();
9288 t = t0 = strdup(km->keys);
9289 if (t0 == NULL)
9290 return got_error_from_errno("strdup");
9292 len = strlen(km->keys);
9293 while ((k = strsep(&t, " ")) != NULL) {
9294 s = strlen(k) > 1; /* control or symbolic key */
9295 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9296 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9297 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9298 if (n < 0) {
9299 free(t0);
9300 return got_error_from_errno("fprintf");
9302 first = 0;
9303 len += s ? 2 : 0;
9304 *off += n;
9306 free(t0);
9308 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9309 if (n < 0)
9310 return got_error_from_errno("fprintf");
9311 *off += n;
9313 return NULL;
9316 static const struct got_error *
9317 format_help(struct tog_help_view_state *s)
9319 const struct got_error *err = NULL;
9320 off_t off = 0;
9321 int i, max, n, show = s->all;
9322 static const struct tog_key_map km[] = {
9323 #define KEYMAP_(info, type) { NULL, (info), type }
9324 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9325 GENERATE_HELP
9326 #undef KEYMAP_
9327 #undef KEY_
9330 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9331 if (err)
9332 return err;
9334 n = nitems(km);
9335 err = max_key_str(&max, km, n);
9336 if (err)
9337 return err;
9339 for (i = 0; i < n; ++i) {
9340 if (km[i].keys == NULL) {
9341 show = s->all;
9342 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9343 km[i].type == s->type || s->all)
9344 show = 1;
9346 if (show) {
9347 err = format_help_line(&off, s->f, &km[i], max);
9348 if (err)
9349 return err;
9350 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9351 if (err)
9352 return err;
9355 fputc('\n', s->f);
9356 ++off;
9357 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9358 return err;
9361 static const struct got_error *
9362 create_help(struct tog_help_view_state *s)
9364 FILE *f;
9365 const struct got_error *err;
9367 free(s->line_offsets);
9368 s->line_offsets = NULL;
9369 s->nlines = 0;
9371 f = got_opentemp();
9372 if (f == NULL)
9373 return got_error_from_errno("got_opentemp");
9374 s->f = f;
9376 err = format_help(s);
9377 if (err)
9378 return err;
9380 if (s->f && fflush(s->f) != 0)
9381 return got_error_from_errno("fflush");
9383 return NULL;
9386 static const struct got_error *
9387 search_start_help_view(struct tog_view *view)
9389 view->state.help.matched_line = 0;
9390 return NULL;
9393 static void
9394 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9395 size_t *nlines, int **first, int **last, int **match, int **selected)
9397 struct tog_help_view_state *s = &view->state.help;
9399 *f = s->f;
9400 *nlines = s->nlines;
9401 *line_offsets = s->line_offsets;
9402 *match = &s->matched_line;
9403 *first = &s->first_displayed_line;
9404 *last = &s->last_displayed_line;
9405 *selected = &s->selected_line;
9408 static const struct got_error *
9409 show_help_view(struct tog_view *view)
9411 struct tog_help_view_state *s = &view->state.help;
9412 const struct got_error *err;
9413 regmatch_t *regmatch = &view->regmatch;
9414 wchar_t *wline;
9415 char *line;
9416 ssize_t linelen;
9417 size_t linesz = 0;
9418 int width, nprinted = 0, rc = 0;
9419 int eos = view->nlines;
9421 if (view_is_hsplit_top(view))
9422 --eos; /* account for border */
9424 s->lineno = 0;
9425 rewind(s->f);
9426 werase(view->window);
9428 if (view->gline > s->nlines - 1)
9429 view->gline = s->nlines - 1;
9431 err = win_draw_center(view->window, 0, 0, view->ncols,
9432 view_needs_focus_indication(view),
9433 "tog help (press q to return to tog)");
9434 if (err)
9435 return err;
9436 if (eos <= 1)
9437 return NULL;
9438 waddstr(view->window, "\n\n");
9439 eos -= 2;
9441 s->eof = 0;
9442 view->maxx = 0;
9443 line = NULL;
9444 while (eos > 0 && nprinted < eos) {
9445 attr_t attr = 0;
9447 linelen = getline(&line, &linesz, s->f);
9448 if (linelen == -1) {
9449 if (!feof(s->f)) {
9450 free(line);
9451 return got_ferror(s->f, GOT_ERR_IO);
9453 s->eof = 1;
9454 break;
9456 if (++s->lineno < s->first_displayed_line)
9457 continue;
9458 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9459 continue;
9460 if (s->lineno == view->hiline)
9461 attr = A_STANDOUT;
9463 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9464 view->x ? 1 : 0);
9465 if (err) {
9466 free(line);
9467 return err;
9469 view->maxx = MAX(view->maxx, width);
9470 free(wline);
9471 wline = NULL;
9473 if (attr)
9474 wattron(view->window, attr);
9475 if (s->first_displayed_line + nprinted == s->matched_line &&
9476 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9477 err = add_matched_line(&width, line, view->ncols - 1, 0,
9478 view->window, view->x, regmatch);
9479 if (err) {
9480 free(line);
9481 return err;
9483 } else {
9484 int skip;
9486 err = format_line(&wline, &width, &skip, line,
9487 view->x, view->ncols, 0, view->x ? 1 : 0);
9488 if (err) {
9489 free(line);
9490 return err;
9492 waddwstr(view->window, &wline[skip]);
9493 free(wline);
9494 wline = NULL;
9496 if (s->lineno == view->hiline) {
9497 while (width++ < view->ncols)
9498 waddch(view->window, ' ');
9499 } else {
9500 if (width < view->ncols)
9501 waddch(view->window, '\n');
9503 if (attr)
9504 wattroff(view->window, attr);
9505 if (++nprinted == 1)
9506 s->first_displayed_line = s->lineno;
9508 free(line);
9509 if (nprinted > 0)
9510 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9511 else
9512 s->last_displayed_line = s->first_displayed_line;
9514 view_border(view);
9516 if (s->eof) {
9517 rc = waddnstr(view->window,
9518 "See the tog(1) manual page for full documentation",
9519 view->ncols - 1);
9520 if (rc == ERR)
9521 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9522 } else {
9523 wmove(view->window, view->nlines - 1, 0);
9524 wclrtoeol(view->window);
9525 wstandout(view->window);
9526 rc = waddnstr(view->window, "scroll down for more...",
9527 view->ncols - 1);
9528 if (rc == ERR)
9529 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9530 if (getcurx(view->window) < view->ncols - 6) {
9531 rc = wprintw(view->window, "[%.0f%%]",
9532 100.00 * s->last_displayed_line / s->nlines);
9533 if (rc == ERR)
9534 return got_error_msg(GOT_ERR_IO, "wprintw");
9536 wstandend(view->window);
9539 return NULL;
9542 static const struct got_error *
9543 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9545 struct tog_help_view_state *s = &view->state.help;
9546 const struct got_error *err = NULL;
9547 char *line = NULL;
9548 ssize_t linelen;
9549 size_t linesz = 0;
9550 int eos, nscroll;
9552 eos = nscroll = view->nlines;
9553 if (view_is_hsplit_top(view))
9554 --eos; /* border */
9556 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9558 switch (ch) {
9559 case '0':
9560 case '$':
9561 case KEY_RIGHT:
9562 case 'l':
9563 case KEY_LEFT:
9564 case 'h':
9565 horizontal_scroll_input(view, ch);
9566 break;
9567 case 'g':
9568 case KEY_HOME:
9569 s->first_displayed_line = 1;
9570 view->count = 0;
9571 break;
9572 case 'G':
9573 case KEY_END:
9574 view->count = 0;
9575 if (s->eof)
9576 break;
9577 s->first_displayed_line = (s->nlines - eos) + 3;
9578 s->eof = 1;
9579 break;
9580 case 'k':
9581 case KEY_UP:
9582 if (s->first_displayed_line > 1)
9583 --s->first_displayed_line;
9584 else
9585 view->count = 0;
9586 break;
9587 case CTRL('u'):
9588 case 'u':
9589 nscroll /= 2;
9590 /* FALL THROUGH */
9591 case KEY_PPAGE:
9592 case CTRL('b'):
9593 case 'b':
9594 if (s->first_displayed_line == 1) {
9595 view->count = 0;
9596 break;
9598 while (--nscroll > 0 && s->first_displayed_line > 1)
9599 s->first_displayed_line--;
9600 break;
9601 case 'j':
9602 case KEY_DOWN:
9603 case CTRL('n'):
9604 if (!s->eof)
9605 ++s->first_displayed_line;
9606 else
9607 view->count = 0;
9608 break;
9609 case CTRL('d'):
9610 case 'd':
9611 nscroll /= 2;
9612 /* FALL THROUGH */
9613 case KEY_NPAGE:
9614 case CTRL('f'):
9615 case 'f':
9616 case ' ':
9617 if (s->eof) {
9618 view->count = 0;
9619 break;
9621 while (!s->eof && --nscroll > 0) {
9622 linelen = getline(&line, &linesz, s->f);
9623 s->first_displayed_line++;
9624 if (linelen == -1) {
9625 if (feof(s->f))
9626 s->eof = 1;
9627 else
9628 err = got_ferror(s->f, GOT_ERR_IO);
9629 break;
9632 free(line);
9633 break;
9634 default:
9635 view->count = 0;
9636 break;
9639 return err;
9642 static const struct got_error *
9643 close_help_view(struct tog_view *view)
9645 struct tog_help_view_state *s = &view->state.help;
9647 free(s->line_offsets);
9648 s->line_offsets = NULL;
9649 if (fclose(s->f) == EOF)
9650 return got_error_from_errno("fclose");
9652 return NULL;
9655 static const struct got_error *
9656 reset_help_view(struct tog_view *view)
9658 struct tog_help_view_state *s = &view->state.help;
9661 if (s->f && fclose(s->f) == EOF)
9662 return got_error_from_errno("fclose");
9664 wclear(view->window);
9665 view->count = 0;
9666 view->x = 0;
9667 s->all = !s->all;
9668 s->first_displayed_line = 1;
9669 s->last_displayed_line = view->nlines;
9670 s->matched_line = 0;
9672 return create_help(s);
9675 static const struct got_error *
9676 open_help_view(struct tog_view *view, struct tog_view *parent)
9678 const struct got_error *err = NULL;
9679 struct tog_help_view_state *s = &view->state.help;
9681 s->type = (enum tog_keymap_type)parent->type;
9682 s->first_displayed_line = 1;
9683 s->last_displayed_line = view->nlines;
9684 s->selected_line = 1;
9686 view->show = show_help_view;
9687 view->input = input_help_view;
9688 view->reset = reset_help_view;
9689 view->close = close_help_view;
9690 view->search_start = search_start_help_view;
9691 view->search_setup = search_setup_help_view;
9692 view->search_next = search_next_view_match;
9694 err = create_help(s);
9695 return err;
9698 static const struct got_error *
9699 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9700 enum tog_view_type request, int y, int x)
9702 const struct got_error *err = NULL;
9704 *new_view = NULL;
9706 switch (request) {
9707 case TOG_VIEW_DIFF:
9708 if (view->type == TOG_VIEW_LOG) {
9709 struct tog_log_view_state *s = &view->state.log;
9711 err = open_diff_view_for_commit(new_view, y, x,
9712 s->selected_entry->commit, s->selected_entry->id,
9713 view, s->repo);
9714 } else
9715 return got_error_msg(GOT_ERR_NOT_IMPL,
9716 "parent/child view pair not supported");
9717 break;
9718 case TOG_VIEW_BLAME:
9719 if (view->type == TOG_VIEW_TREE) {
9720 struct tog_tree_view_state *s = &view->state.tree;
9722 err = blame_tree_entry(new_view, y, x,
9723 s->selected_entry, &s->parents, s->commit_id,
9724 s->repo);
9725 } else
9726 return got_error_msg(GOT_ERR_NOT_IMPL,
9727 "parent/child view pair not supported");
9728 break;
9729 case TOG_VIEW_LOG:
9730 if (view->type == TOG_VIEW_BLAME)
9731 err = log_annotated_line(new_view, y, x,
9732 view->state.blame.repo, view->state.blame.id_to_log);
9733 else if (view->type == TOG_VIEW_TREE)
9734 err = log_selected_tree_entry(new_view, y, x,
9735 &view->state.tree);
9736 else if (view->type == TOG_VIEW_REF)
9737 err = log_ref_entry(new_view, y, x,
9738 view->state.ref.selected_entry,
9739 view->state.ref.repo);
9740 else
9741 return got_error_msg(GOT_ERR_NOT_IMPL,
9742 "parent/child view pair not supported");
9743 break;
9744 case TOG_VIEW_TREE:
9745 if (view->type == TOG_VIEW_LOG)
9746 err = browse_commit_tree(new_view, y, x,
9747 view->state.log.selected_entry,
9748 view->state.log.in_repo_path,
9749 view->state.log.head_ref_name,
9750 view->state.log.repo);
9751 else if (view->type == TOG_VIEW_REF)
9752 err = browse_ref_tree(new_view, y, x,
9753 view->state.ref.selected_entry,
9754 view->state.ref.repo);
9755 else
9756 return got_error_msg(GOT_ERR_NOT_IMPL,
9757 "parent/child view pair not supported");
9758 break;
9759 case TOG_VIEW_REF:
9760 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9761 if (*new_view == NULL)
9762 return got_error_from_errno("view_open");
9763 if (view->type == TOG_VIEW_LOG)
9764 err = open_ref_view(*new_view, view->state.log.repo);
9765 else if (view->type == TOG_VIEW_TREE)
9766 err = open_ref_view(*new_view, view->state.tree.repo);
9767 else
9768 err = got_error_msg(GOT_ERR_NOT_IMPL,
9769 "parent/child view pair not supported");
9770 if (err)
9771 view_close(*new_view);
9772 break;
9773 case TOG_VIEW_HELP:
9774 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9775 if (*new_view == NULL)
9776 return got_error_from_errno("view_open");
9777 err = open_help_view(*new_view, view);
9778 if (err)
9779 view_close(*new_view);
9780 break;
9781 default:
9782 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9785 return err;
9789 * If view was scrolled down to move the selected line into view when opening a
9790 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9792 static void
9793 offset_selection_up(struct tog_view *view)
9795 switch (view->type) {
9796 case TOG_VIEW_BLAME: {
9797 struct tog_blame_view_state *s = &view->state.blame;
9798 if (s->first_displayed_line == 1) {
9799 s->selected_line = MAX(s->selected_line - view->offset,
9800 1);
9801 break;
9803 if (s->first_displayed_line > view->offset)
9804 s->first_displayed_line -= view->offset;
9805 else
9806 s->first_displayed_line = 1;
9807 s->selected_line += view->offset;
9808 break;
9810 case TOG_VIEW_LOG:
9811 log_scroll_up(&view->state.log, view->offset);
9812 view->state.log.selected += view->offset;
9813 break;
9814 case TOG_VIEW_REF:
9815 ref_scroll_up(&view->state.ref, view->offset);
9816 view->state.ref.selected += view->offset;
9817 break;
9818 case TOG_VIEW_TREE:
9819 tree_scroll_up(&view->state.tree, view->offset);
9820 view->state.tree.selected += view->offset;
9821 break;
9822 default:
9823 break;
9826 view->offset = 0;
9830 * If the selected line is in the section of screen covered by the bottom split,
9831 * scroll down offset lines to move it into view and index its new position.
9833 static const struct got_error *
9834 offset_selection_down(struct tog_view *view)
9836 const struct got_error *err = NULL;
9837 const struct got_error *(*scrolld)(struct tog_view *, int);
9838 int *selected = NULL;
9839 int header, offset;
9841 switch (view->type) {
9842 case TOG_VIEW_BLAME: {
9843 struct tog_blame_view_state *s = &view->state.blame;
9844 header = 3;
9845 scrolld = NULL;
9846 if (s->selected_line > view->nlines - header) {
9847 offset = abs(view->nlines - s->selected_line - header);
9848 s->first_displayed_line += offset;
9849 s->selected_line -= offset;
9850 view->offset = offset;
9852 break;
9854 case TOG_VIEW_LOG: {
9855 struct tog_log_view_state *s = &view->state.log;
9856 scrolld = &log_scroll_down;
9857 header = view_is_parent_view(view) ? 3 : 2;
9858 selected = &s->selected;
9859 break;
9861 case TOG_VIEW_REF: {
9862 struct tog_ref_view_state *s = &view->state.ref;
9863 scrolld = &ref_scroll_down;
9864 header = 3;
9865 selected = &s->selected;
9866 break;
9868 case TOG_VIEW_TREE: {
9869 struct tog_tree_view_state *s = &view->state.tree;
9870 scrolld = &tree_scroll_down;
9871 header = 5;
9872 selected = &s->selected;
9873 break;
9875 default:
9876 selected = NULL;
9877 scrolld = NULL;
9878 header = 0;
9879 break;
9882 if (selected && *selected > view->nlines - header) {
9883 offset = abs(view->nlines - *selected - header);
9884 view->offset = offset;
9885 if (scrolld && offset) {
9886 err = scrolld(view, offset);
9887 *selected -= offset;
9891 return err;
9894 static void
9895 list_commands(FILE *fp)
9897 size_t i;
9899 fprintf(fp, "commands:");
9900 for (i = 0; i < nitems(tog_commands); i++) {
9901 const struct tog_cmd *cmd = &tog_commands[i];
9902 fprintf(fp, " %s", cmd->name);
9904 fputc('\n', fp);
9907 __dead static void
9908 usage(int hflag, int status)
9910 FILE *fp = (status == 0) ? stdout : stderr;
9912 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9913 getprogname());
9914 if (hflag) {
9915 fprintf(fp, "lazy usage: %s path\n", getprogname());
9916 list_commands(fp);
9918 exit(status);
9921 static char **
9922 make_argv(int argc, ...)
9924 va_list ap;
9925 char **argv;
9926 int i;
9928 va_start(ap, argc);
9930 argv = calloc(argc, sizeof(char *));
9931 if (argv == NULL)
9932 err(1, "calloc");
9933 for (i = 0; i < argc; i++) {
9934 argv[i] = strdup(va_arg(ap, char *));
9935 if (argv[i] == NULL)
9936 err(1, "strdup");
9939 va_end(ap);
9940 return argv;
9944 * Try to convert 'tog path' into a 'tog log path' command.
9945 * The user could simply have mistyped the command rather than knowingly
9946 * provided a path. So check whether argv[0] can in fact be resolved
9947 * to a path in the HEAD commit and print a special error if not.
9948 * This hack is for mpi@ <3
9950 static const struct got_error *
9951 tog_log_with_path(int argc, char *argv[])
9953 const struct got_error *error = NULL, *close_err;
9954 const struct tog_cmd *cmd = NULL;
9955 struct got_repository *repo = NULL;
9956 struct got_worktree *worktree = NULL;
9957 struct got_object_id *commit_id = NULL, *id = NULL;
9958 struct got_commit_object *commit = NULL;
9959 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9960 char *commit_id_str = NULL, **cmd_argv = NULL;
9961 int *pack_fds = NULL;
9963 cwd = getcwd(NULL, 0);
9964 if (cwd == NULL)
9965 return got_error_from_errno("getcwd");
9967 error = got_repo_pack_fds_open(&pack_fds);
9968 if (error != NULL)
9969 goto done;
9971 error = got_worktree_open(&worktree, cwd, NULL);
9972 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9973 goto done;
9975 if (worktree)
9976 repo_path = strdup(got_worktree_get_repo_path(worktree));
9977 else
9978 repo_path = strdup(cwd);
9979 if (repo_path == NULL) {
9980 error = got_error_from_errno("strdup");
9981 goto done;
9984 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9985 if (error != NULL)
9986 goto done;
9988 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9989 repo, worktree);
9990 if (error)
9991 goto done;
9993 error = tog_load_refs(repo, 0);
9994 if (error)
9995 goto done;
9996 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9997 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9998 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9999 if (error)
10000 goto done;
10002 if (worktree) {
10003 got_worktree_close(worktree);
10004 worktree = NULL;
10007 error = got_object_open_as_commit(&commit, repo, commit_id);
10008 if (error)
10009 goto done;
10011 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
10012 if (error) {
10013 if (error->code != GOT_ERR_NO_TREE_ENTRY)
10014 goto done;
10015 fprintf(stderr, "%s: '%s' is no known command or path\n",
10016 getprogname(), argv[0]);
10017 usage(1, 1);
10018 /* not reached */
10021 error = got_object_id_str(&commit_id_str, commit_id);
10022 if (error)
10023 goto done;
10025 cmd = &tog_commands[0]; /* log */
10026 argc = 4;
10027 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
10028 error = cmd->cmd_main(argc, cmd_argv);
10029 done:
10030 if (repo) {
10031 close_err = got_repo_close(repo);
10032 if (error == NULL)
10033 error = close_err;
10035 if (commit)
10036 got_object_commit_close(commit);
10037 if (worktree)
10038 got_worktree_close(worktree);
10039 if (pack_fds) {
10040 const struct got_error *pack_err =
10041 got_repo_pack_fds_close(pack_fds);
10042 if (error == NULL)
10043 error = pack_err;
10045 free(id);
10046 free(commit_id_str);
10047 free(commit_id);
10048 free(cwd);
10049 free(repo_path);
10050 free(in_repo_path);
10051 if (cmd_argv) {
10052 int i;
10053 for (i = 0; i < argc; i++)
10054 free(cmd_argv[i]);
10055 free(cmd_argv);
10057 tog_free_refs();
10058 return error;
10061 int
10062 main(int argc, char *argv[])
10064 const struct got_error *io_err, *error = NULL;
10065 const struct tog_cmd *cmd = NULL;
10066 int ch, hflag = 0, Vflag = 0;
10067 char **cmd_argv = NULL;
10068 static const struct option longopts[] = {
10069 { "version", no_argument, NULL, 'V' },
10070 { NULL, 0, NULL, 0}
10072 char *diff_algo_str = NULL;
10073 const char *test_script_path;
10075 setlocale(LC_CTYPE, "");
10078 * Override default signal handlers before starting ncurses.
10079 * This should prevent ncurses from installing its own
10080 * broken cleanup() signal handler.
10082 signal(SIGWINCH, tog_sigwinch);
10083 signal(SIGPIPE, tog_sigpipe);
10084 signal(SIGCONT, tog_sigcont);
10085 signal(SIGINT, tog_sigint);
10086 signal(SIGTERM, tog_sigterm);
10089 * Test mode init must happen before pledge() because "tty" will
10090 * not allow TTY-related ioctls to occur via regular files.
10092 test_script_path = getenv("TOG_TEST_SCRIPT");
10093 if (test_script_path != NULL) {
10094 error = init_mock_term(test_script_path);
10095 if (error) {
10096 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10097 return 1;
10099 } else if (!isatty(STDIN_FILENO))
10100 errx(1, "standard input is not a tty");
10102 #if !defined(PROFILE)
10103 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
10104 NULL) == -1)
10105 err(1, "pledge");
10106 #endif
10108 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
10109 switch (ch) {
10110 case 'h':
10111 hflag = 1;
10112 break;
10113 case 'V':
10114 Vflag = 1;
10115 break;
10116 default:
10117 usage(hflag, 1);
10118 /* NOTREACHED */
10122 argc -= optind;
10123 argv += optind;
10124 optind = 1;
10125 optreset = 1;
10127 if (Vflag) {
10128 got_version_print_str();
10129 return 0;
10132 if (argc == 0) {
10133 if (hflag)
10134 usage(hflag, 0);
10135 /* Build an argument vector which runs a default command. */
10136 cmd = &tog_commands[0];
10137 argc = 1;
10138 cmd_argv = make_argv(argc, cmd->name);
10139 } else {
10140 size_t i;
10142 /* Did the user specify a command? */
10143 for (i = 0; i < nitems(tog_commands); i++) {
10144 if (strncmp(tog_commands[i].name, argv[0],
10145 strlen(argv[0])) == 0) {
10146 cmd = &tog_commands[i];
10147 break;
10152 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
10153 if (diff_algo_str) {
10154 if (strcasecmp(diff_algo_str, "patience") == 0)
10155 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
10156 if (strcasecmp(diff_algo_str, "myers") == 0)
10157 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
10160 tog_base_commit.idx = -1;
10161 tog_base_commit.marker = GOT_WORKTREE_STATE_UNKNOWN;
10163 if (cmd == NULL) {
10164 if (argc != 1)
10165 usage(0, 1);
10166 /* No command specified; try log with a path */
10167 error = tog_log_with_path(argc, argv);
10168 } else {
10169 if (hflag)
10170 cmd->cmd_usage();
10171 else
10172 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
10175 if (using_mock_io) {
10176 io_err = tog_io_close();
10177 if (error == NULL)
10178 error = io_err;
10180 endwin();
10181 if (cmd_argv) {
10182 int i;
10183 for (i = 0; i < argc; i++)
10184 free(cmd_argv[i]);
10185 free(cmd_argv);
10188 if (error && error->code != GOT_ERR_CANCELLED &&
10189 error->code != GOT_ERR_EOF &&
10190 error->code != GOT_ERR_PRIVSEP_EXIT &&
10191 error->code != GOT_ERR_PRIVSEP_PIPE &&
10192 !(error->code == GOT_ERR_ERRNO && errno == EINTR)) {
10193 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10194 return 1;
10196 return 0;