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) {
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 return err;
6596 static const struct got_error *
6597 cancel_blame_view(void *arg)
6599 const struct got_error *err = NULL;
6600 int *done = arg;
6601 int errcode;
6603 errcode = pthread_mutex_lock(&tog_mutex);
6604 if (errcode)
6605 return got_error_set_errno(errcode,
6606 "pthread_mutex_unlock");
6608 if (*done)
6609 err = got_error(GOT_ERR_CANCELLED);
6611 errcode = pthread_mutex_unlock(&tog_mutex);
6612 if (errcode)
6613 return got_error_set_errno(errcode,
6614 "pthread_mutex_lock");
6616 return err;
6619 static const struct got_error *
6620 run_blame(struct tog_view *view)
6622 struct tog_blame_view_state *s = &view->state.blame;
6623 struct tog_blame *blame = &s->blame;
6624 const struct got_error *err = NULL;
6625 struct got_commit_object *commit = NULL;
6626 struct got_blob_object *blob = NULL;
6627 struct got_repository *thread_repo = NULL;
6628 struct got_object_id *obj_id = NULL;
6629 int obj_type, fd = -1;
6630 int *pack_fds = NULL;
6632 err = got_object_open_as_commit(&commit, s->repo,
6633 &s->blamed_commit->id);
6634 if (err)
6635 return err;
6637 fd = got_opentempfd();
6638 if (fd == -1) {
6639 err = got_error_from_errno("got_opentempfd");
6640 goto done;
6643 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6644 if (err)
6645 goto done;
6647 err = got_object_get_type(&obj_type, s->repo, obj_id);
6648 if (err)
6649 goto done;
6651 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6652 err = got_error(GOT_ERR_OBJ_TYPE);
6653 goto done;
6656 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6657 if (err)
6658 goto done;
6659 blame->f = got_opentemp();
6660 if (blame->f == NULL) {
6661 err = got_error_from_errno("got_opentemp");
6662 goto done;
6664 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6665 &blame->line_offsets, blame->f, blob);
6666 if (err)
6667 goto done;
6668 if (blame->nlines == 0) {
6669 s->blame_complete = 1;
6670 goto done;
6673 /* Don't include \n at EOF in the blame line count. */
6674 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6675 blame->nlines--;
6677 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6678 if (blame->lines == NULL) {
6679 err = got_error_from_errno("calloc");
6680 goto done;
6683 err = got_repo_pack_fds_open(&pack_fds);
6684 if (err)
6685 goto done;
6686 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6687 pack_fds);
6688 if (err)
6689 goto done;
6691 blame->pack_fds = pack_fds;
6692 blame->cb_args.view = view;
6693 blame->cb_args.lines = blame->lines;
6694 blame->cb_args.nlines = blame->nlines;
6695 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6696 if (blame->cb_args.commit_id == NULL) {
6697 err = got_error_from_errno("got_object_id_dup");
6698 goto done;
6700 blame->cb_args.quit = &s->done;
6702 blame->thread_args.path = s->path;
6703 blame->thread_args.repo = thread_repo;
6704 blame->thread_args.cb_args = &blame->cb_args;
6705 blame->thread_args.complete = &s->blame_complete;
6706 blame->thread_args.cancel_cb = cancel_blame_view;
6707 blame->thread_args.cancel_arg = &s->done;
6708 s->blame_complete = 0;
6710 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6711 s->first_displayed_line = 1;
6712 s->last_displayed_line = view->nlines;
6713 s->selected_line = 1;
6715 s->matched_line = 0;
6717 done:
6718 if (commit)
6719 got_object_commit_close(commit);
6720 if (fd != -1 && close(fd) == -1 && err == NULL)
6721 err = got_error_from_errno("close");
6722 if (blob)
6723 got_object_blob_close(blob);
6724 free(obj_id);
6725 if (err)
6726 stop_blame(blame);
6727 return err;
6730 static const struct got_error *
6731 open_blame_view(struct tog_view *view, char *path,
6732 struct got_object_id *commit_id, struct got_repository *repo)
6734 const struct got_error *err = NULL;
6735 struct tog_blame_view_state *s = &view->state.blame;
6737 STAILQ_INIT(&s->blamed_commits);
6739 s->path = strdup(path);
6740 if (s->path == NULL)
6741 return got_error_from_errno("strdup");
6743 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6744 if (err) {
6745 free(s->path);
6746 return err;
6749 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6750 s->first_displayed_line = 1;
6751 s->last_displayed_line = view->nlines;
6752 s->selected_line = 1;
6753 s->blame_complete = 0;
6754 s->repo = repo;
6755 s->commit_id = commit_id;
6756 memset(&s->blame, 0, sizeof(s->blame));
6758 STAILQ_INIT(&s->colors);
6759 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6760 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6761 get_color_value("TOG_COLOR_COMMIT"));
6762 if (err)
6763 return err;
6766 view->show = show_blame_view;
6767 view->input = input_blame_view;
6768 view->reset = reset_blame_view;
6769 view->close = close_blame_view;
6770 view->search_start = search_start_blame_view;
6771 view->search_setup = search_setup_blame_view;
6772 view->search_next = search_next_view_match;
6774 if (using_mock_io) {
6775 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6776 int rc;
6778 rc = pthread_cond_init(&bta->blame_complete, NULL);
6779 if (rc)
6780 return got_error_set_errno(rc, "pthread_cond_init");
6783 return run_blame(view);
6786 static const struct got_error *
6787 close_blame_view(struct tog_view *view)
6789 const struct got_error *err = NULL;
6790 struct tog_blame_view_state *s = &view->state.blame;
6792 if (s->blame.thread)
6793 err = stop_blame(&s->blame);
6795 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6796 struct got_object_qid *blamed_commit;
6797 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6798 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6799 got_object_qid_free(blamed_commit);
6802 if (using_mock_io) {
6803 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6804 int rc;
6806 rc = pthread_cond_destroy(&bta->blame_complete);
6807 if (rc && err == NULL)
6808 err = got_error_set_errno(rc, "pthread_cond_destroy");
6811 free(s->path);
6812 free_colors(&s->colors);
6813 return err;
6816 static const struct got_error *
6817 search_start_blame_view(struct tog_view *view)
6819 struct tog_blame_view_state *s = &view->state.blame;
6821 s->matched_line = 0;
6822 return NULL;
6825 static void
6826 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6827 size_t *nlines, int **first, int **last, int **match, int **selected)
6829 struct tog_blame_view_state *s = &view->state.blame;
6831 *f = s->blame.f;
6832 *nlines = s->blame.nlines;
6833 *line_offsets = s->blame.line_offsets;
6834 *match = &s->matched_line;
6835 *first = &s->first_displayed_line;
6836 *last = &s->last_displayed_line;
6837 *selected = &s->selected_line;
6840 static const struct got_error *
6841 show_blame_view(struct tog_view *view)
6843 const struct got_error *err = NULL;
6844 struct tog_blame_view_state *s = &view->state.blame;
6845 int errcode;
6847 if (s->blame.thread == NULL && !s->blame_complete) {
6848 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6849 &s->blame.thread_args);
6850 if (errcode)
6851 return got_error_set_errno(errcode, "pthread_create");
6853 if (!using_mock_io)
6854 halfdelay(1); /* fast refresh while annotating */
6857 if (s->blame_complete && !using_mock_io)
6858 halfdelay(10); /* disable fast refresh */
6860 err = draw_blame(view);
6862 view_border(view);
6863 return err;
6866 static const struct got_error *
6867 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6868 struct got_repository *repo, struct got_object_id *id)
6870 struct tog_view *log_view;
6871 const struct got_error *err = NULL;
6873 *new_view = NULL;
6875 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6876 if (log_view == NULL)
6877 return got_error_from_errno("view_open");
6879 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0, NULL);
6880 if (err)
6881 view_close(log_view);
6882 else
6883 *new_view = log_view;
6885 return err;
6888 static const struct got_error *
6889 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6891 const struct got_error *err = NULL, *thread_err = NULL;
6892 struct tog_view *diff_view;
6893 struct tog_blame_view_state *s = &view->state.blame;
6894 int eos, nscroll, begin_y = 0, begin_x = 0;
6896 eos = nscroll = view->nlines - 2;
6897 if (view_is_hsplit_top(view))
6898 --eos; /* border */
6900 switch (ch) {
6901 case '0':
6902 case '$':
6903 case KEY_RIGHT:
6904 case 'l':
6905 case KEY_LEFT:
6906 case 'h':
6907 horizontal_scroll_input(view, ch);
6908 break;
6909 case 'q':
6910 s->done = 1;
6911 break;
6912 case 'g':
6913 case KEY_HOME:
6914 s->selected_line = 1;
6915 s->first_displayed_line = 1;
6916 view->count = 0;
6917 break;
6918 case 'G':
6919 case KEY_END:
6920 if (s->blame.nlines < eos) {
6921 s->selected_line = s->blame.nlines;
6922 s->first_displayed_line = 1;
6923 } else {
6924 s->selected_line = eos;
6925 s->first_displayed_line = s->blame.nlines - (eos - 1);
6927 view->count = 0;
6928 break;
6929 case 'k':
6930 case KEY_UP:
6931 case CTRL('p'):
6932 if (s->selected_line > 1)
6933 s->selected_line--;
6934 else if (s->selected_line == 1 &&
6935 s->first_displayed_line > 1)
6936 s->first_displayed_line--;
6937 else
6938 view->count = 0;
6939 break;
6940 case CTRL('u'):
6941 case 'u':
6942 nscroll /= 2;
6943 /* FALL THROUGH */
6944 case KEY_PPAGE:
6945 case CTRL('b'):
6946 case 'b':
6947 if (s->first_displayed_line == 1) {
6948 if (view->count > 1)
6949 nscroll += nscroll;
6950 s->selected_line = MAX(1, s->selected_line - nscroll);
6951 view->count = 0;
6952 break;
6954 if (s->first_displayed_line > nscroll)
6955 s->first_displayed_line -= nscroll;
6956 else
6957 s->first_displayed_line = 1;
6958 break;
6959 case 'j':
6960 case KEY_DOWN:
6961 case CTRL('n'):
6962 if (s->selected_line < eos && s->first_displayed_line +
6963 s->selected_line <= s->blame.nlines)
6964 s->selected_line++;
6965 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6966 s->first_displayed_line++;
6967 else
6968 view->count = 0;
6969 break;
6970 case 'c':
6971 case 'p': {
6972 struct got_object_id *id = NULL;
6974 view->count = 0;
6975 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6976 s->first_displayed_line, s->selected_line);
6977 if (id == NULL)
6978 break;
6979 if (ch == 'p') {
6980 struct got_commit_object *commit, *pcommit;
6981 struct got_object_qid *pid;
6982 struct got_object_id *blob_id = NULL;
6983 int obj_type;
6984 err = got_object_open_as_commit(&commit,
6985 s->repo, id);
6986 if (err)
6987 break;
6988 pid = STAILQ_FIRST(
6989 got_object_commit_get_parent_ids(commit));
6990 if (pid == NULL) {
6991 got_object_commit_close(commit);
6992 break;
6994 /* Check if path history ends here. */
6995 err = got_object_open_as_commit(&pcommit,
6996 s->repo, &pid->id);
6997 if (err)
6998 break;
6999 err = got_object_id_by_path(&blob_id, s->repo,
7000 pcommit, s->path);
7001 got_object_commit_close(pcommit);
7002 if (err) {
7003 if (err->code == GOT_ERR_NO_TREE_ENTRY)
7004 err = NULL;
7005 got_object_commit_close(commit);
7006 break;
7008 err = got_object_get_type(&obj_type, s->repo,
7009 blob_id);
7010 free(blob_id);
7011 /* Can't blame non-blob type objects. */
7012 if (obj_type != GOT_OBJ_TYPE_BLOB) {
7013 got_object_commit_close(commit);
7014 break;
7016 err = got_object_qid_alloc(&s->blamed_commit,
7017 &pid->id);
7018 got_object_commit_close(commit);
7019 } else {
7020 if (got_object_id_cmp(id,
7021 &s->blamed_commit->id) == 0)
7022 break;
7023 err = got_object_qid_alloc(&s->blamed_commit,
7024 id);
7026 if (err)
7027 break;
7028 s->done = 1;
7029 thread_err = stop_blame(&s->blame);
7030 s->done = 0;
7031 if (thread_err)
7032 break;
7033 STAILQ_INSERT_HEAD(&s->blamed_commits,
7034 s->blamed_commit, entry);
7035 err = run_blame(view);
7036 if (err)
7037 break;
7038 break;
7040 case 'C': {
7041 struct got_object_qid *first;
7043 view->count = 0;
7044 first = STAILQ_FIRST(&s->blamed_commits);
7045 if (!got_object_id_cmp(&first->id, s->commit_id))
7046 break;
7047 s->done = 1;
7048 thread_err = stop_blame(&s->blame);
7049 s->done = 0;
7050 if (thread_err)
7051 break;
7052 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
7053 got_object_qid_free(s->blamed_commit);
7054 s->blamed_commit =
7055 STAILQ_FIRST(&s->blamed_commits);
7056 err = run_blame(view);
7057 if (err)
7058 break;
7059 break;
7061 case 'L':
7062 view->count = 0;
7063 s->id_to_log = get_selected_commit_id(s->blame.lines,
7064 s->blame.nlines, s->first_displayed_line, s->selected_line);
7065 if (s->id_to_log)
7066 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7067 break;
7068 case KEY_ENTER:
7069 case '\r': {
7070 struct got_object_id *id = NULL;
7071 struct got_object_qid *pid;
7072 struct got_commit_object *commit = NULL;
7074 view->count = 0;
7075 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7076 s->first_displayed_line, s->selected_line);
7077 if (id == NULL)
7078 break;
7079 err = got_object_open_as_commit(&commit, s->repo, id);
7080 if (err)
7081 break;
7082 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7083 if (*new_view) {
7084 /* traversed from diff view, release diff resources */
7085 err = close_diff_view(*new_view);
7086 if (err)
7087 break;
7088 diff_view = *new_view;
7089 } else {
7090 if (view_is_parent_view(view))
7091 view_get_split(view, &begin_y, &begin_x);
7093 diff_view = view_open(0, 0, begin_y, begin_x,
7094 TOG_VIEW_DIFF);
7095 if (diff_view == NULL) {
7096 got_object_commit_close(commit);
7097 err = got_error_from_errno("view_open");
7098 break;
7101 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
7102 id, NULL, NULL, 3, 0, 0, view, s->repo);
7103 got_object_commit_close(commit);
7104 if (err)
7105 break;
7106 s->last_diffed_line = s->first_displayed_line - 1 +
7107 s->selected_line;
7108 if (*new_view)
7109 break; /* still open from active diff view */
7110 if (view_is_parent_view(view) &&
7111 view->mode == TOG_VIEW_SPLIT_HRZN) {
7112 err = view_init_hsplit(view, begin_y);
7113 if (err)
7114 break;
7117 view->focussed = 0;
7118 diff_view->focussed = 1;
7119 diff_view->mode = view->mode;
7120 diff_view->nlines = view->lines - begin_y;
7121 if (view_is_parent_view(view)) {
7122 view_transfer_size(diff_view, view);
7123 err = view_close_child(view);
7124 if (err)
7125 break;
7126 err = view_set_child(view, diff_view);
7127 if (err)
7128 break;
7129 view->focus_child = 1;
7130 } else
7131 *new_view = diff_view;
7132 if (err)
7133 break;
7134 break;
7136 case CTRL('d'):
7137 case 'd':
7138 nscroll /= 2;
7139 /* FALL THROUGH */
7140 case KEY_NPAGE:
7141 case CTRL('f'):
7142 case 'f':
7143 case ' ':
7144 if (s->last_displayed_line >= s->blame.nlines &&
7145 s->selected_line >= MIN(s->blame.nlines,
7146 view->nlines - 2)) {
7147 view->count = 0;
7148 break;
7150 if (s->last_displayed_line >= s->blame.nlines &&
7151 s->selected_line < view->nlines - 2) {
7152 s->selected_line +=
7153 MIN(nscroll, s->last_displayed_line -
7154 s->first_displayed_line - s->selected_line + 1);
7156 if (s->last_displayed_line + nscroll <= s->blame.nlines)
7157 s->first_displayed_line += nscroll;
7158 else
7159 s->first_displayed_line =
7160 s->blame.nlines - (view->nlines - 3);
7161 break;
7162 case KEY_RESIZE:
7163 if (s->selected_line > view->nlines - 2) {
7164 s->selected_line = MIN(s->blame.nlines,
7165 view->nlines - 2);
7167 break;
7168 default:
7169 view->count = 0;
7170 break;
7172 return thread_err ? thread_err : err;
7175 static const struct got_error *
7176 reset_blame_view(struct tog_view *view)
7178 const struct got_error *err;
7179 struct tog_blame_view_state *s = &view->state.blame;
7181 view->count = 0;
7182 s->done = 1;
7183 err = stop_blame(&s->blame);
7184 s->done = 0;
7185 if (err)
7186 return err;
7187 return run_blame(view);
7190 static const struct got_error *
7191 cmd_blame(int argc, char *argv[])
7193 const struct got_error *error;
7194 struct got_repository *repo = NULL;
7195 struct got_worktree *worktree = NULL;
7196 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7197 char *link_target = NULL;
7198 struct got_object_id *commit_id = NULL;
7199 struct got_commit_object *commit = NULL;
7200 char *keyword_idstr = NULL, *commit_id_str = NULL;
7201 int ch;
7202 struct tog_view *view = NULL;
7203 int *pack_fds = NULL;
7205 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7206 switch (ch) {
7207 case 'c':
7208 commit_id_str = optarg;
7209 break;
7210 case 'r':
7211 repo_path = realpath(optarg, NULL);
7212 if (repo_path == NULL)
7213 return got_error_from_errno2("realpath",
7214 optarg);
7215 break;
7216 default:
7217 usage_blame();
7218 /* NOTREACHED */
7222 argc -= optind;
7223 argv += optind;
7225 if (argc != 1)
7226 usage_blame();
7228 error = got_repo_pack_fds_open(&pack_fds);
7229 if (error != NULL)
7230 goto done;
7232 if (repo_path == NULL) {
7233 cwd = getcwd(NULL, 0);
7234 if (cwd == NULL)
7235 return got_error_from_errno("getcwd");
7236 error = got_worktree_open(&worktree, cwd, NULL);
7237 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7238 goto done;
7239 if (worktree)
7240 repo_path =
7241 strdup(got_worktree_get_repo_path(worktree));
7242 else
7243 repo_path = strdup(cwd);
7244 if (repo_path == NULL) {
7245 error = got_error_from_errno("strdup");
7246 goto done;
7250 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7251 if (error != NULL)
7252 goto done;
7254 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7255 worktree);
7256 if (error)
7257 goto done;
7259 init_curses();
7261 error = apply_unveil(got_repo_get_path(repo), NULL);
7262 if (error)
7263 goto done;
7265 error = tog_load_refs(repo, 0);
7266 if (error)
7267 goto done;
7269 if (commit_id_str == NULL) {
7270 struct got_reference *head_ref;
7271 error = got_ref_open(&head_ref, repo, worktree ?
7272 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7273 if (error != NULL)
7274 goto done;
7275 error = got_ref_resolve(&commit_id, repo, head_ref);
7276 got_ref_close(head_ref);
7277 } else {
7278 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
7279 repo, worktree);
7280 if (error != NULL)
7281 goto done;
7282 if (keyword_idstr != NULL)
7283 commit_id_str = keyword_idstr;
7285 error = got_repo_match_object_id(&commit_id, NULL,
7286 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7288 if (error != NULL)
7289 goto done;
7291 error = got_object_open_as_commit(&commit, repo, commit_id);
7292 if (error)
7293 goto done;
7295 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7296 commit, repo);
7297 if (error)
7298 goto done;
7300 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7301 if (view == NULL) {
7302 error = got_error_from_errno("view_open");
7303 goto done;
7305 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7306 commit_id, repo);
7307 if (error != NULL) {
7308 if (view->close == NULL)
7309 close_blame_view(view);
7310 view_close(view);
7311 goto done;
7314 if (worktree) {
7315 error = set_tog_base_commit(repo, worktree);
7316 if (error != NULL)
7317 goto done;
7319 /* Release work tree lock. */
7320 got_worktree_close(worktree);
7321 worktree = NULL;
7324 error = view_loop(view);
7326 done:
7327 free(tog_base_commit.id);
7328 free(repo_path);
7329 free(in_repo_path);
7330 free(link_target);
7331 free(cwd);
7332 free(commit_id);
7333 free(keyword_idstr);
7334 if (commit)
7335 got_object_commit_close(commit);
7336 if (worktree)
7337 got_worktree_close(worktree);
7338 if (repo) {
7339 const struct got_error *close_err = got_repo_close(repo);
7340 if (error == NULL)
7341 error = close_err;
7343 if (pack_fds) {
7344 const struct got_error *pack_err =
7345 got_repo_pack_fds_close(pack_fds);
7346 if (error == NULL)
7347 error = pack_err;
7349 tog_free_refs();
7350 return error;
7353 static const struct got_error *
7354 draw_tree_entries(struct tog_view *view, const char *parent_path)
7356 struct tog_tree_view_state *s = &view->state.tree;
7357 const struct got_error *err = NULL;
7358 struct got_tree_entry *te;
7359 wchar_t *wline;
7360 char *index = NULL;
7361 struct tog_color *tc;
7362 int width, n, nentries, scrollx, i = 1;
7363 int limit = view->nlines;
7365 s->ndisplayed = 0;
7366 if (view_is_hsplit_top(view))
7367 --limit; /* border */
7369 werase(view->window);
7371 if (limit == 0)
7372 return NULL;
7374 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7375 0, 0);
7376 if (err)
7377 return err;
7378 if (view_needs_focus_indication(view))
7379 wstandout(view->window);
7380 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7381 if (tc)
7382 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7383 waddwstr(view->window, wline);
7384 free(wline);
7385 wline = NULL;
7386 while (width++ < view->ncols)
7387 waddch(view->window, ' ');
7388 if (tc)
7389 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7390 if (view_needs_focus_indication(view))
7391 wstandend(view->window);
7392 if (--limit <= 0)
7393 return NULL;
7395 i += s->selected;
7396 if (s->first_displayed_entry) {
7397 i += got_tree_entry_get_index(s->first_displayed_entry);
7398 if (s->tree != s->root)
7399 ++i; /* account for ".." entry */
7401 nentries = got_object_tree_get_nentries(s->tree);
7402 if (asprintf(&index, "[%d/%d] %s",
7403 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7404 return got_error_from_errno("asprintf");
7405 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7406 free(index);
7407 if (err)
7408 return err;
7409 waddwstr(view->window, wline);
7410 free(wline);
7411 wline = NULL;
7412 if (width < view->ncols - 1)
7413 waddch(view->window, '\n');
7414 if (--limit <= 0)
7415 return NULL;
7416 waddch(view->window, '\n');
7417 if (--limit <= 0)
7418 return NULL;
7420 if (s->first_displayed_entry == NULL) {
7421 te = got_object_tree_get_first_entry(s->tree);
7422 if (s->selected == 0) {
7423 if (view->focussed)
7424 wstandout(view->window);
7425 s->selected_entry = NULL;
7427 waddstr(view->window, " ..\n"); /* parent directory */
7428 if (s->selected == 0 && view->focussed)
7429 wstandend(view->window);
7430 s->ndisplayed++;
7431 if (--limit <= 0)
7432 return NULL;
7433 n = 1;
7434 } else {
7435 n = 0;
7436 te = s->first_displayed_entry;
7439 view->maxx = 0;
7440 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7441 char *line = NULL, *id_str = NULL, *link_target = NULL;
7442 const char *modestr = "";
7443 mode_t mode;
7445 te = got_object_tree_get_entry(s->tree, i);
7446 mode = got_tree_entry_get_mode(te);
7448 if (s->show_ids) {
7449 err = got_object_id_str(&id_str,
7450 got_tree_entry_get_id(te));
7451 if (err)
7452 return got_error_from_errno(
7453 "got_object_id_str");
7455 if (got_object_tree_entry_is_submodule(te))
7456 modestr = "$";
7457 else if (S_ISLNK(mode)) {
7458 int i;
7460 err = got_tree_entry_get_symlink_target(&link_target,
7461 te, s->repo);
7462 if (err) {
7463 free(id_str);
7464 return err;
7466 for (i = 0; link_target[i] != '\0'; i++) {
7467 if (!isprint((unsigned char)link_target[i]))
7468 link_target[i] = '?';
7470 modestr = "@";
7472 else if (S_ISDIR(mode))
7473 modestr = "/";
7474 else if (mode & S_IXUSR)
7475 modestr = "*";
7476 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7477 got_tree_entry_get_name(te), modestr,
7478 link_target ? " -> ": "",
7479 link_target ? link_target : "") == -1) {
7480 free(id_str);
7481 free(link_target);
7482 return got_error_from_errno("asprintf");
7484 free(id_str);
7485 free(link_target);
7487 /* use full line width to determine view->maxx */
7488 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7489 if (err) {
7490 free(line);
7491 break;
7493 view->maxx = MAX(view->maxx, width);
7494 free(wline);
7495 wline = NULL;
7497 err = format_line(&wline, &width, &scrollx, line, view->x,
7498 view->ncols, 0, 0);
7499 if (err) {
7500 free(line);
7501 break;
7503 if (n == s->selected) {
7504 if (view->focussed)
7505 wstandout(view->window);
7506 s->selected_entry = te;
7508 tc = match_color(&s->colors, line);
7509 if (tc)
7510 wattr_on(view->window,
7511 COLOR_PAIR(tc->colorpair), NULL);
7512 waddwstr(view->window, &wline[scrollx]);
7513 if (tc)
7514 wattr_off(view->window,
7515 COLOR_PAIR(tc->colorpair), NULL);
7516 if (width < view->ncols)
7517 waddch(view->window, '\n');
7518 if (n == s->selected && view->focussed)
7519 wstandend(view->window);
7520 free(line);
7521 free(wline);
7522 wline = NULL;
7523 n++;
7524 s->ndisplayed++;
7525 s->last_displayed_entry = te;
7526 if (--limit <= 0)
7527 break;
7530 return err;
7533 static void
7534 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7536 struct got_tree_entry *te;
7537 int isroot = s->tree == s->root;
7538 int i = 0;
7540 if (s->first_displayed_entry == NULL)
7541 return;
7543 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7544 while (i++ < maxscroll) {
7545 if (te == NULL) {
7546 if (!isroot)
7547 s->first_displayed_entry = NULL;
7548 break;
7550 s->first_displayed_entry = te;
7551 te = got_tree_entry_get_prev(s->tree, te);
7555 static const struct got_error *
7556 tree_scroll_down(struct tog_view *view, int maxscroll)
7558 struct tog_tree_view_state *s = &view->state.tree;
7559 struct got_tree_entry *next, *last;
7560 int n = 0;
7562 if (s->first_displayed_entry)
7563 next = got_tree_entry_get_next(s->tree,
7564 s->first_displayed_entry);
7565 else
7566 next = got_object_tree_get_first_entry(s->tree);
7568 last = s->last_displayed_entry;
7569 while (next && n++ < maxscroll) {
7570 if (last) {
7571 s->last_displayed_entry = last;
7572 last = got_tree_entry_get_next(s->tree, last);
7574 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7575 s->first_displayed_entry = next;
7576 next = got_tree_entry_get_next(s->tree, next);
7580 return NULL;
7583 static const struct got_error *
7584 tree_entry_path(char **path, struct tog_parent_trees *parents,
7585 struct got_tree_entry *te)
7587 const struct got_error *err = NULL;
7588 struct tog_parent_tree *pt;
7589 size_t len = 2; /* for leading slash and NUL */
7591 TAILQ_FOREACH(pt, parents, entry)
7592 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7593 + 1 /* slash */;
7594 if (te)
7595 len += strlen(got_tree_entry_get_name(te));
7597 *path = calloc(1, len);
7598 if (path == NULL)
7599 return got_error_from_errno("calloc");
7601 (*path)[0] = '/';
7602 pt = TAILQ_LAST(parents, tog_parent_trees);
7603 while (pt) {
7604 const char *name = got_tree_entry_get_name(pt->selected_entry);
7605 if (strlcat(*path, name, len) >= len) {
7606 err = got_error(GOT_ERR_NO_SPACE);
7607 goto done;
7609 if (strlcat(*path, "/", len) >= len) {
7610 err = got_error(GOT_ERR_NO_SPACE);
7611 goto done;
7613 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7615 if (te) {
7616 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7617 err = got_error(GOT_ERR_NO_SPACE);
7618 goto done;
7621 done:
7622 if (err) {
7623 free(*path);
7624 *path = NULL;
7626 return err;
7629 static const struct got_error *
7630 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7631 struct got_tree_entry *te, struct tog_parent_trees *parents,
7632 struct got_object_id *commit_id, struct got_repository *repo)
7634 const struct got_error *err = NULL;
7635 char *path;
7636 struct tog_view *blame_view;
7638 *new_view = NULL;
7640 err = tree_entry_path(&path, parents, te);
7641 if (err)
7642 return err;
7644 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7645 if (blame_view == NULL) {
7646 err = got_error_from_errno("view_open");
7647 goto done;
7650 err = open_blame_view(blame_view, path, commit_id, repo);
7651 if (err) {
7652 if (err->code == GOT_ERR_CANCELLED)
7653 err = NULL;
7654 view_close(blame_view);
7655 } else
7656 *new_view = blame_view;
7657 done:
7658 free(path);
7659 return err;
7662 static const struct got_error *
7663 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7664 struct tog_tree_view_state *s)
7666 struct tog_view *log_view;
7667 const struct got_error *err = NULL;
7668 char *path;
7670 *new_view = NULL;
7672 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7673 if (log_view == NULL)
7674 return got_error_from_errno("view_open");
7676 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7677 if (err)
7678 return err;
7680 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7681 path, 0, NULL);
7682 if (err)
7683 view_close(log_view);
7684 else
7685 *new_view = log_view;
7686 free(path);
7687 return err;
7690 static const struct got_error *
7691 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7692 const char *head_ref_name, struct got_repository *repo)
7694 const struct got_error *err = NULL;
7695 char *commit_id_str = NULL;
7696 struct tog_tree_view_state *s = &view->state.tree;
7697 struct got_commit_object *commit = NULL;
7699 TAILQ_INIT(&s->parents);
7700 STAILQ_INIT(&s->colors);
7702 s->commit_id = got_object_id_dup(commit_id);
7703 if (s->commit_id == NULL) {
7704 err = got_error_from_errno("got_object_id_dup");
7705 goto done;
7708 err = got_object_open_as_commit(&commit, repo, commit_id);
7709 if (err)
7710 goto done;
7713 * The root is opened here and will be closed when the view is closed.
7714 * Any visited subtrees and their path-wise parents are opened and
7715 * closed on demand.
7717 err = got_object_open_as_tree(&s->root, repo,
7718 got_object_commit_get_tree_id(commit));
7719 if (err)
7720 goto done;
7721 s->tree = s->root;
7723 err = got_object_id_str(&commit_id_str, commit_id);
7724 if (err != NULL)
7725 goto done;
7727 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7728 err = got_error_from_errno("asprintf");
7729 goto done;
7732 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7733 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7734 if (head_ref_name) {
7735 s->head_ref_name = strdup(head_ref_name);
7736 if (s->head_ref_name == NULL) {
7737 err = got_error_from_errno("strdup");
7738 goto done;
7741 s->repo = repo;
7743 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7744 err = add_color(&s->colors, "\\$$",
7745 TOG_COLOR_TREE_SUBMODULE,
7746 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7747 if (err)
7748 goto done;
7749 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7750 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7751 if (err)
7752 goto done;
7753 err = add_color(&s->colors, "/$",
7754 TOG_COLOR_TREE_DIRECTORY,
7755 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7756 if (err)
7757 goto done;
7759 err = add_color(&s->colors, "\\*$",
7760 TOG_COLOR_TREE_EXECUTABLE,
7761 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7762 if (err)
7763 goto done;
7765 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7766 get_color_value("TOG_COLOR_COMMIT"));
7767 if (err)
7768 goto done;
7771 view->show = show_tree_view;
7772 view->input = input_tree_view;
7773 view->close = close_tree_view;
7774 view->search_start = search_start_tree_view;
7775 view->search_next = search_next_tree_view;
7776 done:
7777 free(commit_id_str);
7778 if (commit)
7779 got_object_commit_close(commit);
7780 if (err) {
7781 if (view->close == NULL)
7782 close_tree_view(view);
7783 view_close(view);
7785 return err;
7788 static const struct got_error *
7789 close_tree_view(struct tog_view *view)
7791 struct tog_tree_view_state *s = &view->state.tree;
7793 free_colors(&s->colors);
7794 free(s->tree_label);
7795 s->tree_label = NULL;
7796 free(s->commit_id);
7797 s->commit_id = NULL;
7798 free(s->head_ref_name);
7799 s->head_ref_name = NULL;
7800 while (!TAILQ_EMPTY(&s->parents)) {
7801 struct tog_parent_tree *parent;
7802 parent = TAILQ_FIRST(&s->parents);
7803 TAILQ_REMOVE(&s->parents, parent, entry);
7804 if (parent->tree != s->root)
7805 got_object_tree_close(parent->tree);
7806 free(parent);
7809 if (s->tree != NULL && s->tree != s->root)
7810 got_object_tree_close(s->tree);
7811 if (s->root)
7812 got_object_tree_close(s->root);
7813 return NULL;
7816 static const struct got_error *
7817 search_start_tree_view(struct tog_view *view)
7819 struct tog_tree_view_state *s = &view->state.tree;
7821 s->matched_entry = NULL;
7822 return NULL;
7825 static int
7826 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7828 regmatch_t regmatch;
7830 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7831 0) == 0;
7834 static const struct got_error *
7835 search_next_tree_view(struct tog_view *view)
7837 struct tog_tree_view_state *s = &view->state.tree;
7838 struct got_tree_entry *te = NULL;
7840 if (!view->searching) {
7841 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7842 return NULL;
7845 if (s->matched_entry) {
7846 if (view->searching == TOG_SEARCH_FORWARD) {
7847 if (s->selected_entry)
7848 te = got_tree_entry_get_next(s->tree,
7849 s->selected_entry);
7850 else
7851 te = got_object_tree_get_first_entry(s->tree);
7852 } else {
7853 if (s->selected_entry == NULL)
7854 te = got_object_tree_get_last_entry(s->tree);
7855 else
7856 te = got_tree_entry_get_prev(s->tree,
7857 s->selected_entry);
7859 } else {
7860 if (s->selected_entry)
7861 te = s->selected_entry;
7862 else if (view->searching == TOG_SEARCH_FORWARD)
7863 te = got_object_tree_get_first_entry(s->tree);
7864 else
7865 te = got_object_tree_get_last_entry(s->tree);
7868 while (1) {
7869 if (te == NULL) {
7870 if (s->matched_entry == NULL) {
7871 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7872 return NULL;
7874 if (view->searching == TOG_SEARCH_FORWARD)
7875 te = got_object_tree_get_first_entry(s->tree);
7876 else
7877 te = got_object_tree_get_last_entry(s->tree);
7880 if (match_tree_entry(te, &view->regex)) {
7881 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7882 s->matched_entry = te;
7883 break;
7886 if (view->searching == TOG_SEARCH_FORWARD)
7887 te = got_tree_entry_get_next(s->tree, te);
7888 else
7889 te = got_tree_entry_get_prev(s->tree, te);
7892 if (s->matched_entry) {
7893 s->first_displayed_entry = s->matched_entry;
7894 s->selected = 0;
7897 return NULL;
7900 static const struct got_error *
7901 show_tree_view(struct tog_view *view)
7903 const struct got_error *err = NULL;
7904 struct tog_tree_view_state *s = &view->state.tree;
7905 char *parent_path;
7907 err = tree_entry_path(&parent_path, &s->parents, NULL);
7908 if (err)
7909 return err;
7911 err = draw_tree_entries(view, parent_path);
7912 free(parent_path);
7914 view_border(view);
7915 return err;
7918 static const struct got_error *
7919 tree_goto_line(struct tog_view *view, int nlines)
7921 const struct got_error *err = NULL;
7922 struct tog_tree_view_state *s = &view->state.tree;
7923 struct got_tree_entry **fte, **lte, **ste;
7924 int g, last, first = 1, i = 1;
7925 int root = s->tree == s->root;
7926 int off = root ? 1 : 2;
7928 g = view->gline;
7929 view->gline = 0;
7931 if (g == 0)
7932 g = 1;
7933 else if (g > got_object_tree_get_nentries(s->tree))
7934 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7936 fte = &s->first_displayed_entry;
7937 lte = &s->last_displayed_entry;
7938 ste = &s->selected_entry;
7940 if (*fte != NULL) {
7941 first = got_tree_entry_get_index(*fte);
7942 first += off; /* account for ".." */
7944 last = got_tree_entry_get_index(*lte);
7945 last += off;
7947 if (g >= first && g <= last && g - first < nlines) {
7948 s->selected = g - first;
7949 return NULL; /* gline is on the current page */
7952 if (*ste != NULL) {
7953 i = got_tree_entry_get_index(*ste);
7954 i += off;
7957 if (i < g) {
7958 err = tree_scroll_down(view, g - i);
7959 if (err)
7960 return err;
7961 if (got_tree_entry_get_index(*lte) >=
7962 got_object_tree_get_nentries(s->tree) - 1 &&
7963 first + s->selected < g &&
7964 s->selected < s->ndisplayed - 1) {
7965 first = got_tree_entry_get_index(*fte);
7966 first += off;
7967 s->selected = g - first;
7969 } else if (i > g)
7970 tree_scroll_up(s, i - g);
7972 if (g < nlines &&
7973 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7974 s->selected = g - 1;
7976 return NULL;
7979 static const struct got_error *
7980 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7982 const struct got_error *err = NULL;
7983 struct tog_tree_view_state *s = &view->state.tree;
7984 struct got_tree_entry *te;
7985 int n, nscroll = view->nlines - 3;
7987 if (view->gline)
7988 return tree_goto_line(view, nscroll);
7990 switch (ch) {
7991 case '0':
7992 case '$':
7993 case KEY_RIGHT:
7994 case 'l':
7995 case KEY_LEFT:
7996 case 'h':
7997 horizontal_scroll_input(view, ch);
7998 break;
7999 case 'i':
8000 s->show_ids = !s->show_ids;
8001 view->count = 0;
8002 break;
8003 case 'L':
8004 view->count = 0;
8005 if (!s->selected_entry)
8006 break;
8007 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8008 break;
8009 case 'R':
8010 view->count = 0;
8011 err = view_request_new(new_view, view, TOG_VIEW_REF);
8012 break;
8013 case 'g':
8014 case '=':
8015 case KEY_HOME:
8016 s->selected = 0;
8017 view->count = 0;
8018 if (s->tree == s->root)
8019 s->first_displayed_entry =
8020 got_object_tree_get_first_entry(s->tree);
8021 else
8022 s->first_displayed_entry = NULL;
8023 break;
8024 case 'G':
8025 case '*':
8026 case KEY_END: {
8027 int eos = view->nlines - 3;
8029 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8030 --eos; /* border */
8031 s->selected = 0;
8032 view->count = 0;
8033 te = got_object_tree_get_last_entry(s->tree);
8034 for (n = 0; n < eos; n++) {
8035 if (te == NULL) {
8036 if (s->tree != s->root) {
8037 s->first_displayed_entry = NULL;
8038 n++;
8040 break;
8042 s->first_displayed_entry = te;
8043 te = got_tree_entry_get_prev(s->tree, te);
8045 if (n > 0)
8046 s->selected = n - 1;
8047 break;
8049 case 'k':
8050 case KEY_UP:
8051 case CTRL('p'):
8052 if (s->selected > 0) {
8053 s->selected--;
8054 break;
8056 tree_scroll_up(s, 1);
8057 if (s->selected_entry == NULL ||
8058 (s->tree == s->root && s->selected_entry ==
8059 got_object_tree_get_first_entry(s->tree)))
8060 view->count = 0;
8061 break;
8062 case CTRL('u'):
8063 case 'u':
8064 nscroll /= 2;
8065 /* FALL THROUGH */
8066 case KEY_PPAGE:
8067 case CTRL('b'):
8068 case 'b':
8069 if (s->tree == s->root) {
8070 if (got_object_tree_get_first_entry(s->tree) ==
8071 s->first_displayed_entry)
8072 s->selected -= MIN(s->selected, nscroll);
8073 } else {
8074 if (s->first_displayed_entry == NULL)
8075 s->selected -= MIN(s->selected, nscroll);
8077 tree_scroll_up(s, MAX(0, nscroll));
8078 if (s->selected_entry == NULL ||
8079 (s->tree == s->root && s->selected_entry ==
8080 got_object_tree_get_first_entry(s->tree)))
8081 view->count = 0;
8082 break;
8083 case 'j':
8084 case KEY_DOWN:
8085 case CTRL('n'):
8086 if (s->selected < s->ndisplayed - 1) {
8087 s->selected++;
8088 break;
8090 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8091 == NULL) {
8092 /* can't scroll any further */
8093 view->count = 0;
8094 break;
8096 tree_scroll_down(view, 1);
8097 break;
8098 case CTRL('d'):
8099 case 'd':
8100 nscroll /= 2;
8101 /* FALL THROUGH */
8102 case KEY_NPAGE:
8103 case CTRL('f'):
8104 case 'f':
8105 case ' ':
8106 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8107 == NULL) {
8108 /* can't scroll any further; move cursor down */
8109 if (s->selected < s->ndisplayed - 1)
8110 s->selected += MIN(nscroll,
8111 s->ndisplayed - s->selected - 1);
8112 else
8113 view->count = 0;
8114 break;
8116 tree_scroll_down(view, nscroll);
8117 break;
8118 case KEY_ENTER:
8119 case '\r':
8120 case KEY_BACKSPACE:
8121 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
8122 struct tog_parent_tree *parent;
8123 /* user selected '..' */
8124 if (s->tree == s->root) {
8125 view->count = 0;
8126 break;
8128 parent = TAILQ_FIRST(&s->parents);
8129 TAILQ_REMOVE(&s->parents, parent,
8130 entry);
8131 got_object_tree_close(s->tree);
8132 s->tree = parent->tree;
8133 s->first_displayed_entry =
8134 parent->first_displayed_entry;
8135 s->selected_entry =
8136 parent->selected_entry;
8137 s->selected = parent->selected;
8138 if (s->selected > view->nlines - 3) {
8139 err = offset_selection_down(view);
8140 if (err)
8141 break;
8143 free(parent);
8144 } else if (S_ISDIR(got_tree_entry_get_mode(
8145 s->selected_entry))) {
8146 struct got_tree_object *subtree;
8147 view->count = 0;
8148 err = got_object_open_as_tree(&subtree, s->repo,
8149 got_tree_entry_get_id(s->selected_entry));
8150 if (err)
8151 break;
8152 err = tree_view_visit_subtree(s, subtree);
8153 if (err) {
8154 got_object_tree_close(subtree);
8155 break;
8157 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
8158 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
8159 break;
8160 case KEY_RESIZE:
8161 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
8162 s->selected = view->nlines - 4;
8163 view->count = 0;
8164 break;
8165 default:
8166 view->count = 0;
8167 break;
8170 return err;
8173 __dead static void
8174 usage_tree(void)
8176 endwin();
8177 fprintf(stderr,
8178 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
8179 getprogname());
8180 exit(1);
8183 static const struct got_error *
8184 cmd_tree(int argc, char *argv[])
8186 const struct got_error *error;
8187 struct got_repository *repo = NULL;
8188 struct got_worktree *worktree = NULL;
8189 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8190 struct got_object_id *commit_id = NULL;
8191 struct got_commit_object *commit = NULL;
8192 const char *commit_id_arg = NULL;
8193 char *keyword_idstr = NULL, *label = NULL;
8194 struct got_reference *ref = NULL;
8195 const char *head_ref_name = NULL;
8196 int ch;
8197 struct tog_view *view;
8198 int *pack_fds = NULL;
8200 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
8201 switch (ch) {
8202 case 'c':
8203 commit_id_arg = optarg;
8204 break;
8205 case 'r':
8206 repo_path = realpath(optarg, NULL);
8207 if (repo_path == NULL)
8208 return got_error_from_errno2("realpath",
8209 optarg);
8210 break;
8211 default:
8212 usage_tree();
8213 /* NOTREACHED */
8217 argc -= optind;
8218 argv += optind;
8220 if (argc > 1)
8221 usage_tree();
8223 error = got_repo_pack_fds_open(&pack_fds);
8224 if (error != NULL)
8225 goto done;
8227 if (repo_path == NULL) {
8228 cwd = getcwd(NULL, 0);
8229 if (cwd == NULL)
8230 return got_error_from_errno("getcwd");
8231 error = got_worktree_open(&worktree, cwd, NULL);
8232 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8233 goto done;
8234 if (worktree)
8235 repo_path =
8236 strdup(got_worktree_get_repo_path(worktree));
8237 else
8238 repo_path = strdup(cwd);
8239 if (repo_path == NULL) {
8240 error = got_error_from_errno("strdup");
8241 goto done;
8245 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8246 if (error != NULL)
8247 goto done;
8249 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8250 repo, worktree);
8251 if (error)
8252 goto done;
8254 init_curses();
8256 error = apply_unveil(got_repo_get_path(repo), NULL);
8257 if (error)
8258 goto done;
8260 error = tog_load_refs(repo, 0);
8261 if (error)
8262 goto done;
8264 if (commit_id_arg == NULL) {
8265 error = got_repo_match_object_id(&commit_id, &label,
8266 worktree ? got_worktree_get_head_ref_name(worktree) :
8267 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8268 if (error)
8269 goto done;
8270 head_ref_name = label;
8271 } else {
8272 error = got_keyword_to_idstr(&keyword_idstr, commit_id_arg,
8273 repo, worktree);
8274 if (error != NULL)
8275 goto done;
8276 if (keyword_idstr != NULL)
8277 commit_id_arg = keyword_idstr;
8279 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8280 if (error == NULL)
8281 head_ref_name = got_ref_get_name(ref);
8282 else if (error->code != GOT_ERR_NOT_REF)
8283 goto done;
8284 error = got_repo_match_object_id(&commit_id, NULL,
8285 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8286 if (error)
8287 goto done;
8290 error = got_object_open_as_commit(&commit, repo, commit_id);
8291 if (error)
8292 goto done;
8294 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8295 if (view == NULL) {
8296 error = got_error_from_errno("view_open");
8297 goto done;
8299 error = open_tree_view(view, commit_id, head_ref_name, repo);
8300 if (error)
8301 goto done;
8302 if (!got_path_is_root_dir(in_repo_path)) {
8303 error = tree_view_walk_path(&view->state.tree, commit,
8304 in_repo_path);
8305 if (error)
8306 goto done;
8309 if (worktree) {
8310 error = set_tog_base_commit(repo, worktree);
8311 if (error != NULL)
8312 goto done;
8314 /* Release work tree lock. */
8315 got_worktree_close(worktree);
8316 worktree = NULL;
8319 error = view_loop(view);
8321 done:
8322 free(tog_base_commit.id);
8323 free(keyword_idstr);
8324 free(repo_path);
8325 free(cwd);
8326 free(commit_id);
8327 free(label);
8328 if (ref)
8329 got_ref_close(ref);
8330 if (worktree != NULL)
8331 got_worktree_close(worktree);
8332 if (repo) {
8333 const struct got_error *close_err = got_repo_close(repo);
8334 if (error == NULL)
8335 error = close_err;
8337 if (pack_fds) {
8338 const struct got_error *pack_err =
8339 got_repo_pack_fds_close(pack_fds);
8340 if (error == NULL)
8341 error = pack_err;
8343 tog_free_refs();
8344 return error;
8347 static const struct got_error *
8348 ref_view_load_refs(struct tog_ref_view_state *s)
8350 struct got_reflist_entry *sre;
8351 struct tog_reflist_entry *re;
8353 s->nrefs = 0;
8354 TAILQ_FOREACH(sre, &tog_refs, entry) {
8355 if (strncmp(got_ref_get_name(sre->ref),
8356 "refs/got/", 9) == 0 &&
8357 strncmp(got_ref_get_name(sre->ref),
8358 "refs/got/backup/", 16) != 0)
8359 continue;
8361 re = malloc(sizeof(*re));
8362 if (re == NULL)
8363 return got_error_from_errno("malloc");
8365 re->ref = got_ref_dup(sre->ref);
8366 if (re->ref == NULL)
8367 return got_error_from_errno("got_ref_dup");
8368 re->idx = s->nrefs++;
8369 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8372 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8373 return NULL;
8376 static void
8377 ref_view_free_refs(struct tog_ref_view_state *s)
8379 struct tog_reflist_entry *re;
8381 while (!TAILQ_EMPTY(&s->refs)) {
8382 re = TAILQ_FIRST(&s->refs);
8383 TAILQ_REMOVE(&s->refs, re, entry);
8384 got_ref_close(re->ref);
8385 free(re);
8389 static const struct got_error *
8390 open_ref_view(struct tog_view *view, struct got_repository *repo)
8392 const struct got_error *err = NULL;
8393 struct tog_ref_view_state *s = &view->state.ref;
8395 s->selected_entry = 0;
8396 s->repo = repo;
8398 TAILQ_INIT(&s->refs);
8399 STAILQ_INIT(&s->colors);
8401 err = ref_view_load_refs(s);
8402 if (err)
8403 goto done;
8405 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8406 err = add_color(&s->colors, "^refs/heads/",
8407 TOG_COLOR_REFS_HEADS,
8408 get_color_value("TOG_COLOR_REFS_HEADS"));
8409 if (err)
8410 goto done;
8412 err = add_color(&s->colors, "^refs/tags/",
8413 TOG_COLOR_REFS_TAGS,
8414 get_color_value("TOG_COLOR_REFS_TAGS"));
8415 if (err)
8416 goto done;
8418 err = add_color(&s->colors, "^refs/remotes/",
8419 TOG_COLOR_REFS_REMOTES,
8420 get_color_value("TOG_COLOR_REFS_REMOTES"));
8421 if (err)
8422 goto done;
8424 err = add_color(&s->colors, "^refs/got/backup/",
8425 TOG_COLOR_REFS_BACKUP,
8426 get_color_value("TOG_COLOR_REFS_BACKUP"));
8427 if (err)
8428 goto done;
8431 view->show = show_ref_view;
8432 view->input = input_ref_view;
8433 view->close = close_ref_view;
8434 view->search_start = search_start_ref_view;
8435 view->search_next = search_next_ref_view;
8436 done:
8437 if (err) {
8438 if (view->close == NULL)
8439 close_ref_view(view);
8440 view_close(view);
8442 return err;
8445 static const struct got_error *
8446 close_ref_view(struct tog_view *view)
8448 struct tog_ref_view_state *s = &view->state.ref;
8450 ref_view_free_refs(s);
8451 free_colors(&s->colors);
8453 return NULL;
8456 static const struct got_error *
8457 resolve_reflist_entry(struct got_object_id **commit_id,
8458 struct tog_reflist_entry *re, struct got_repository *repo)
8460 const struct got_error *err = NULL;
8461 struct got_object_id *obj_id;
8462 struct got_tag_object *tag = NULL;
8463 int obj_type;
8465 *commit_id = NULL;
8467 err = got_ref_resolve(&obj_id, repo, re->ref);
8468 if (err)
8469 return err;
8471 err = got_object_get_type(&obj_type, repo, obj_id);
8472 if (err)
8473 goto done;
8475 switch (obj_type) {
8476 case GOT_OBJ_TYPE_COMMIT:
8477 *commit_id = obj_id;
8478 break;
8479 case GOT_OBJ_TYPE_TAG:
8480 err = got_object_open_as_tag(&tag, repo, obj_id);
8481 if (err)
8482 goto done;
8483 free(obj_id);
8484 err = got_object_get_type(&obj_type, repo,
8485 got_object_tag_get_object_id(tag));
8486 if (err)
8487 goto done;
8488 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8489 err = got_error(GOT_ERR_OBJ_TYPE);
8490 goto done;
8492 *commit_id = got_object_id_dup(
8493 got_object_tag_get_object_id(tag));
8494 if (*commit_id == NULL) {
8495 err = got_error_from_errno("got_object_id_dup");
8496 goto done;
8498 break;
8499 default:
8500 err = got_error(GOT_ERR_OBJ_TYPE);
8501 break;
8504 done:
8505 if (tag)
8506 got_object_tag_close(tag);
8507 if (err) {
8508 free(*commit_id);
8509 *commit_id = NULL;
8511 return err;
8514 static const struct got_error *
8515 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8516 struct tog_reflist_entry *re, struct got_repository *repo)
8518 struct tog_view *log_view;
8519 const struct got_error *err = NULL;
8520 struct got_object_id *commit_id = NULL;
8522 *new_view = NULL;
8524 err = resolve_reflist_entry(&commit_id, re, repo);
8525 if (err) {
8526 if (err->code != GOT_ERR_OBJ_TYPE)
8527 return err;
8528 else
8529 return NULL;
8532 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8533 if (log_view == NULL) {
8534 err = got_error_from_errno("view_open");
8535 goto done;
8538 err = open_log_view(log_view, commit_id, repo,
8539 got_ref_get_name(re->ref), "", 0, NULL);
8540 done:
8541 if (err)
8542 view_close(log_view);
8543 else
8544 *new_view = log_view;
8545 free(commit_id);
8546 return err;
8549 static void
8550 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8552 struct tog_reflist_entry *re;
8553 int i = 0;
8555 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8556 return;
8558 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8559 while (i++ < maxscroll) {
8560 if (re == NULL)
8561 break;
8562 s->first_displayed_entry = re;
8563 re = TAILQ_PREV(re, tog_reflist_head, entry);
8567 static const struct got_error *
8568 ref_scroll_down(struct tog_view *view, int maxscroll)
8570 struct tog_ref_view_state *s = &view->state.ref;
8571 struct tog_reflist_entry *next, *last;
8572 int n = 0;
8574 if (s->first_displayed_entry)
8575 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8576 else
8577 next = TAILQ_FIRST(&s->refs);
8579 last = s->last_displayed_entry;
8580 while (next && n++ < maxscroll) {
8581 if (last) {
8582 s->last_displayed_entry = last;
8583 last = TAILQ_NEXT(last, entry);
8585 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8586 s->first_displayed_entry = next;
8587 next = TAILQ_NEXT(next, entry);
8591 return NULL;
8594 static const struct got_error *
8595 search_start_ref_view(struct tog_view *view)
8597 struct tog_ref_view_state *s = &view->state.ref;
8599 s->matched_entry = NULL;
8600 return NULL;
8603 static int
8604 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8606 regmatch_t regmatch;
8608 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8609 0) == 0;
8612 static const struct got_error *
8613 search_next_ref_view(struct tog_view *view)
8615 struct tog_ref_view_state *s = &view->state.ref;
8616 struct tog_reflist_entry *re = NULL;
8618 if (!view->searching) {
8619 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8620 return NULL;
8623 if (s->matched_entry) {
8624 if (view->searching == TOG_SEARCH_FORWARD) {
8625 if (s->selected_entry)
8626 re = TAILQ_NEXT(s->selected_entry, entry);
8627 else
8628 re = TAILQ_PREV(s->selected_entry,
8629 tog_reflist_head, entry);
8630 } else {
8631 if (s->selected_entry == NULL)
8632 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8633 else
8634 re = TAILQ_PREV(s->selected_entry,
8635 tog_reflist_head, entry);
8637 } else {
8638 if (s->selected_entry)
8639 re = s->selected_entry;
8640 else if (view->searching == TOG_SEARCH_FORWARD)
8641 re = TAILQ_FIRST(&s->refs);
8642 else
8643 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8646 while (1) {
8647 if (re == NULL) {
8648 if (s->matched_entry == NULL) {
8649 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8650 return NULL;
8652 if (view->searching == TOG_SEARCH_FORWARD)
8653 re = TAILQ_FIRST(&s->refs);
8654 else
8655 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8658 if (match_reflist_entry(re, &view->regex)) {
8659 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8660 s->matched_entry = re;
8661 break;
8664 if (view->searching == TOG_SEARCH_FORWARD)
8665 re = TAILQ_NEXT(re, entry);
8666 else
8667 re = TAILQ_PREV(re, tog_reflist_head, entry);
8670 if (s->matched_entry) {
8671 s->first_displayed_entry = s->matched_entry;
8672 s->selected = 0;
8675 return NULL;
8678 static const struct got_error *
8679 show_ref_view(struct tog_view *view)
8681 const struct got_error *err = NULL;
8682 struct tog_ref_view_state *s = &view->state.ref;
8683 struct tog_reflist_entry *re;
8684 char *line = NULL;
8685 wchar_t *wline;
8686 struct tog_color *tc;
8687 int width, n, scrollx;
8688 int limit = view->nlines;
8690 werase(view->window);
8692 s->ndisplayed = 0;
8693 if (view_is_hsplit_top(view))
8694 --limit; /* border */
8696 if (limit == 0)
8697 return NULL;
8699 re = s->first_displayed_entry;
8701 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8702 s->nrefs) == -1)
8703 return got_error_from_errno("asprintf");
8705 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8706 if (err) {
8707 free(line);
8708 return err;
8710 if (view_needs_focus_indication(view))
8711 wstandout(view->window);
8712 waddwstr(view->window, wline);
8713 while (width++ < view->ncols)
8714 waddch(view->window, ' ');
8715 if (view_needs_focus_indication(view))
8716 wstandend(view->window);
8717 free(wline);
8718 wline = NULL;
8719 free(line);
8720 line = NULL;
8721 if (--limit <= 0)
8722 return NULL;
8724 n = 0;
8725 view->maxx = 0;
8726 while (re && limit > 0) {
8727 char *line = NULL;
8728 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8730 if (s->show_date) {
8731 struct got_commit_object *ci;
8732 struct got_tag_object *tag;
8733 struct got_object_id *id;
8734 struct tm tm;
8735 time_t t;
8737 err = got_ref_resolve(&id, s->repo, re->ref);
8738 if (err)
8739 return err;
8740 err = got_object_open_as_tag(&tag, s->repo, id);
8741 if (err) {
8742 if (err->code != GOT_ERR_OBJ_TYPE) {
8743 free(id);
8744 return err;
8746 err = got_object_open_as_commit(&ci, s->repo,
8747 id);
8748 if (err) {
8749 free(id);
8750 return err;
8752 t = got_object_commit_get_committer_time(ci);
8753 got_object_commit_close(ci);
8754 } else {
8755 t = got_object_tag_get_tagger_time(tag);
8756 got_object_tag_close(tag);
8758 free(id);
8759 if (gmtime_r(&t, &tm) == NULL)
8760 return got_error_from_errno("gmtime_r");
8761 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8762 return got_error(GOT_ERR_NO_SPACE);
8764 if (got_ref_is_symbolic(re->ref)) {
8765 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8766 ymd : "", got_ref_get_name(re->ref),
8767 got_ref_get_symref_target(re->ref)) == -1)
8768 return got_error_from_errno("asprintf");
8769 } else if (s->show_ids) {
8770 struct got_object_id *id;
8771 char *id_str;
8772 err = got_ref_resolve(&id, s->repo, re->ref);
8773 if (err)
8774 return err;
8775 err = got_object_id_str(&id_str, id);
8776 if (err) {
8777 free(id);
8778 return err;
8780 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8781 got_ref_get_name(re->ref), id_str) == -1) {
8782 err = got_error_from_errno("asprintf");
8783 free(id);
8784 free(id_str);
8785 return err;
8787 free(id);
8788 free(id_str);
8789 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8790 got_ref_get_name(re->ref)) == -1)
8791 return got_error_from_errno("asprintf");
8793 /* use full line width to determine view->maxx */
8794 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8795 if (err) {
8796 free(line);
8797 return err;
8799 view->maxx = MAX(view->maxx, width);
8800 free(wline);
8801 wline = NULL;
8803 err = format_line(&wline, &width, &scrollx, line, view->x,
8804 view->ncols, 0, 0);
8805 if (err) {
8806 free(line);
8807 return err;
8809 if (n == s->selected) {
8810 if (view->focussed)
8811 wstandout(view->window);
8812 s->selected_entry = re;
8814 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8815 if (tc)
8816 wattr_on(view->window,
8817 COLOR_PAIR(tc->colorpair), NULL);
8818 waddwstr(view->window, &wline[scrollx]);
8819 if (tc)
8820 wattr_off(view->window,
8821 COLOR_PAIR(tc->colorpair), NULL);
8822 if (width < view->ncols)
8823 waddch(view->window, '\n');
8824 if (n == s->selected && view->focussed)
8825 wstandend(view->window);
8826 free(line);
8827 free(wline);
8828 wline = NULL;
8829 n++;
8830 s->ndisplayed++;
8831 s->last_displayed_entry = re;
8833 limit--;
8834 re = TAILQ_NEXT(re, entry);
8837 view_border(view);
8838 return err;
8841 static const struct got_error *
8842 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8843 struct tog_reflist_entry *re, struct got_repository *repo)
8845 const struct got_error *err = NULL;
8846 struct got_object_id *commit_id = NULL;
8847 struct tog_view *tree_view;
8849 *new_view = NULL;
8851 err = resolve_reflist_entry(&commit_id, re, repo);
8852 if (err) {
8853 if (err->code != GOT_ERR_OBJ_TYPE)
8854 return err;
8855 else
8856 return NULL;
8860 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8861 if (tree_view == NULL) {
8862 err = got_error_from_errno("view_open");
8863 goto done;
8866 err = open_tree_view(tree_view, commit_id,
8867 got_ref_get_name(re->ref), repo);
8868 if (err)
8869 goto done;
8871 *new_view = tree_view;
8872 done:
8873 free(commit_id);
8874 return err;
8877 static const struct got_error *
8878 ref_goto_line(struct tog_view *view, int nlines)
8880 const struct got_error *err = NULL;
8881 struct tog_ref_view_state *s = &view->state.ref;
8882 int g, idx = s->selected_entry->idx;
8884 g = view->gline;
8885 view->gline = 0;
8887 if (g == 0)
8888 g = 1;
8889 else if (g > s->nrefs)
8890 g = s->nrefs;
8892 if (g >= s->first_displayed_entry->idx + 1 &&
8893 g <= s->last_displayed_entry->idx + 1 &&
8894 g - s->first_displayed_entry->idx - 1 < nlines) {
8895 s->selected = g - s->first_displayed_entry->idx - 1;
8896 return NULL;
8899 if (idx + 1 < g) {
8900 err = ref_scroll_down(view, g - idx - 1);
8901 if (err)
8902 return err;
8903 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8904 s->first_displayed_entry->idx + s->selected < g &&
8905 s->selected < s->ndisplayed - 1)
8906 s->selected = g - s->first_displayed_entry->idx - 1;
8907 } else if (idx + 1 > g)
8908 ref_scroll_up(s, idx - g + 1);
8910 if (g < nlines && s->first_displayed_entry->idx == 0)
8911 s->selected = g - 1;
8913 return NULL;
8917 static const struct got_error *
8918 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8920 const struct got_error *err = NULL;
8921 struct tog_ref_view_state *s = &view->state.ref;
8922 struct tog_reflist_entry *re;
8923 int n, nscroll = view->nlines - 1;
8925 if (view->gline)
8926 return ref_goto_line(view, nscroll);
8928 switch (ch) {
8929 case '0':
8930 case '$':
8931 case KEY_RIGHT:
8932 case 'l':
8933 case KEY_LEFT:
8934 case 'h':
8935 horizontal_scroll_input(view, ch);
8936 break;
8937 case 'i':
8938 s->show_ids = !s->show_ids;
8939 view->count = 0;
8940 break;
8941 case 'm':
8942 s->show_date = !s->show_date;
8943 view->count = 0;
8944 break;
8945 case 'o':
8946 s->sort_by_date = !s->sort_by_date;
8947 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8948 view->count = 0;
8949 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8950 got_ref_cmp_by_commit_timestamp_descending :
8951 tog_ref_cmp_by_name, s->repo);
8952 if (err)
8953 break;
8954 got_reflist_object_id_map_free(tog_refs_idmap);
8955 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8956 &tog_refs, s->repo);
8957 if (err)
8958 break;
8959 ref_view_free_refs(s);
8960 err = ref_view_load_refs(s);
8961 break;
8962 case KEY_ENTER:
8963 case '\r':
8964 view->count = 0;
8965 if (!s->selected_entry)
8966 break;
8967 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8968 break;
8969 case 'T':
8970 view->count = 0;
8971 if (!s->selected_entry)
8972 break;
8973 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8974 break;
8975 case 'g':
8976 case '=':
8977 case KEY_HOME:
8978 s->selected = 0;
8979 view->count = 0;
8980 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8981 break;
8982 case 'G':
8983 case '*':
8984 case KEY_END: {
8985 int eos = view->nlines - 1;
8987 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8988 --eos; /* border */
8989 s->selected = 0;
8990 view->count = 0;
8991 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8992 for (n = 0; n < eos; n++) {
8993 if (re == NULL)
8994 break;
8995 s->first_displayed_entry = re;
8996 re = TAILQ_PREV(re, tog_reflist_head, entry);
8998 if (n > 0)
8999 s->selected = n - 1;
9000 break;
9002 case 'k':
9003 case KEY_UP:
9004 case CTRL('p'):
9005 if (s->selected > 0) {
9006 s->selected--;
9007 break;
9009 ref_scroll_up(s, 1);
9010 if (s->selected_entry == TAILQ_FIRST(&s->refs))
9011 view->count = 0;
9012 break;
9013 case CTRL('u'):
9014 case 'u':
9015 nscroll /= 2;
9016 /* FALL THROUGH */
9017 case KEY_PPAGE:
9018 case CTRL('b'):
9019 case 'b':
9020 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
9021 s->selected -= MIN(nscroll, s->selected);
9022 ref_scroll_up(s, MAX(0, nscroll));
9023 if (s->selected_entry == TAILQ_FIRST(&s->refs))
9024 view->count = 0;
9025 break;
9026 case 'j':
9027 case KEY_DOWN:
9028 case CTRL('n'):
9029 if (s->selected < s->ndisplayed - 1) {
9030 s->selected++;
9031 break;
9033 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
9034 /* can't scroll any further */
9035 view->count = 0;
9036 break;
9038 ref_scroll_down(view, 1);
9039 break;
9040 case CTRL('d'):
9041 case 'd':
9042 nscroll /= 2;
9043 /* FALL THROUGH */
9044 case KEY_NPAGE:
9045 case CTRL('f'):
9046 case 'f':
9047 case ' ':
9048 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
9049 /* can't scroll any further; move cursor down */
9050 if (s->selected < s->ndisplayed - 1)
9051 s->selected += MIN(nscroll,
9052 s->ndisplayed - s->selected - 1);
9053 if (view->count > 1 && s->selected < s->ndisplayed - 1)
9054 s->selected += s->ndisplayed - s->selected - 1;
9055 view->count = 0;
9056 break;
9058 ref_scroll_down(view, nscroll);
9059 break;
9060 case CTRL('l'):
9061 view->count = 0;
9062 tog_free_refs();
9063 err = tog_load_refs(s->repo, s->sort_by_date);
9064 if (err)
9065 break;
9066 ref_view_free_refs(s);
9067 err = ref_view_load_refs(s);
9068 break;
9069 case KEY_RESIZE:
9070 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
9071 s->selected = view->nlines - 2;
9072 break;
9073 default:
9074 view->count = 0;
9075 break;
9078 return err;
9081 __dead static void
9082 usage_ref(void)
9084 endwin();
9085 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
9086 getprogname());
9087 exit(1);
9090 static const struct got_error *
9091 cmd_ref(int argc, char *argv[])
9093 const struct got_error *error;
9094 struct got_repository *repo = NULL;
9095 struct got_worktree *worktree = NULL;
9096 char *cwd = NULL, *repo_path = NULL;
9097 int ch;
9098 struct tog_view *view;
9099 int *pack_fds = NULL;
9101 while ((ch = getopt(argc, argv, "r:")) != -1) {
9102 switch (ch) {
9103 case 'r':
9104 repo_path = realpath(optarg, NULL);
9105 if (repo_path == NULL)
9106 return got_error_from_errno2("realpath",
9107 optarg);
9108 break;
9109 default:
9110 usage_ref();
9111 /* NOTREACHED */
9115 argc -= optind;
9116 argv += optind;
9118 if (argc > 1)
9119 usage_ref();
9121 error = got_repo_pack_fds_open(&pack_fds);
9122 if (error != NULL)
9123 goto done;
9125 if (repo_path == NULL) {
9126 cwd = getcwd(NULL, 0);
9127 if (cwd == NULL)
9128 return got_error_from_errno("getcwd");
9129 error = got_worktree_open(&worktree, cwd, NULL);
9130 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9131 goto done;
9132 if (worktree)
9133 repo_path =
9134 strdup(got_worktree_get_repo_path(worktree));
9135 else
9136 repo_path = strdup(cwd);
9137 if (repo_path == NULL) {
9138 error = got_error_from_errno("strdup");
9139 goto done;
9143 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9144 if (error != NULL)
9145 goto done;
9147 init_curses();
9149 error = apply_unveil(got_repo_get_path(repo), NULL);
9150 if (error)
9151 goto done;
9153 error = tog_load_refs(repo, 0);
9154 if (error)
9155 goto done;
9157 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
9158 if (view == NULL) {
9159 error = got_error_from_errno("view_open");
9160 goto done;
9163 error = open_ref_view(view, repo);
9164 if (error)
9165 goto done;
9167 if (worktree) {
9168 error = set_tog_base_commit(repo, worktree);
9169 if (error != NULL)
9170 goto done;
9172 /* Release work tree lock. */
9173 got_worktree_close(worktree);
9174 worktree = NULL;
9177 error = view_loop(view);
9179 done:
9180 free(tog_base_commit.id);
9181 free(repo_path);
9182 free(cwd);
9183 if (worktree != NULL)
9184 got_worktree_close(worktree);
9185 if (repo) {
9186 const struct got_error *close_err = got_repo_close(repo);
9187 if (close_err)
9188 error = close_err;
9190 if (pack_fds) {
9191 const struct got_error *pack_err =
9192 got_repo_pack_fds_close(pack_fds);
9193 if (error == NULL)
9194 error = pack_err;
9196 tog_free_refs();
9197 return error;
9200 static const struct got_error*
9201 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
9202 const char *str)
9204 size_t len;
9206 if (win == NULL)
9207 win = stdscr;
9209 len = strlen(str);
9210 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
9212 if (focus)
9213 wstandout(win);
9214 if (mvwprintw(win, y, x, "%s", str) == ERR)
9215 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
9216 if (focus)
9217 wstandend(win);
9219 return NULL;
9222 static const struct got_error *
9223 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
9225 off_t *p;
9227 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
9228 if (p == NULL) {
9229 free(*line_offsets);
9230 *line_offsets = NULL;
9231 return got_error_from_errno("reallocarray");
9234 *line_offsets = p;
9235 (*line_offsets)[*nlines] = off;
9236 ++(*nlines);
9237 return NULL;
9240 static const struct got_error *
9241 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
9243 *ret = 0;
9245 for (;n > 0; --n, ++km) {
9246 char *t0, *t, *k;
9247 size_t len = 1;
9249 if (km->keys == NULL)
9250 continue;
9252 t = t0 = strdup(km->keys);
9253 if (t0 == NULL)
9254 return got_error_from_errno("strdup");
9256 len += strlen(t);
9257 while ((k = strsep(&t, " ")) != NULL)
9258 len += strlen(k) > 1 ? 2 : 0;
9259 free(t0);
9260 *ret = MAX(*ret, len);
9263 return NULL;
9267 * Write keymap section headers, keys, and key info in km to f.
9268 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9269 * wrap control and symbolic keys in guillemets, else use <>.
9271 static const struct got_error *
9272 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9274 int n, len = width;
9276 if (km->keys) {
9277 static const char *u8_glyph[] = {
9278 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9279 "\xe2\x80\xba" /* U+203A (utf8 >) */
9281 char *t0, *t, *k;
9282 int cs, s, first = 1;
9284 cs = got_locale_is_utf8();
9286 t = t0 = strdup(km->keys);
9287 if (t0 == NULL)
9288 return got_error_from_errno("strdup");
9290 len = strlen(km->keys);
9291 while ((k = strsep(&t, " ")) != NULL) {
9292 s = strlen(k) > 1; /* control or symbolic key */
9293 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9294 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9295 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9296 if (n < 0) {
9297 free(t0);
9298 return got_error_from_errno("fprintf");
9300 first = 0;
9301 len += s ? 2 : 0;
9302 *off += n;
9304 free(t0);
9306 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9307 if (n < 0)
9308 return got_error_from_errno("fprintf");
9309 *off += n;
9311 return NULL;
9314 static const struct got_error *
9315 format_help(struct tog_help_view_state *s)
9317 const struct got_error *err = NULL;
9318 off_t off = 0;
9319 int i, max, n, show = s->all;
9320 static const struct tog_key_map km[] = {
9321 #define KEYMAP_(info, type) { NULL, (info), type }
9322 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9323 GENERATE_HELP
9324 #undef KEYMAP_
9325 #undef KEY_
9328 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9329 if (err)
9330 return err;
9332 n = nitems(km);
9333 err = max_key_str(&max, km, n);
9334 if (err)
9335 return err;
9337 for (i = 0; i < n; ++i) {
9338 if (km[i].keys == NULL) {
9339 show = s->all;
9340 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9341 km[i].type == s->type || s->all)
9342 show = 1;
9344 if (show) {
9345 err = format_help_line(&off, s->f, &km[i], max);
9346 if (err)
9347 return err;
9348 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9349 if (err)
9350 return err;
9353 fputc('\n', s->f);
9354 ++off;
9355 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9356 return err;
9359 static const struct got_error *
9360 create_help(struct tog_help_view_state *s)
9362 FILE *f;
9363 const struct got_error *err;
9365 free(s->line_offsets);
9366 s->line_offsets = NULL;
9367 s->nlines = 0;
9369 f = got_opentemp();
9370 if (f == NULL)
9371 return got_error_from_errno("got_opentemp");
9372 s->f = f;
9374 err = format_help(s);
9375 if (err)
9376 return err;
9378 if (s->f && fflush(s->f) != 0)
9379 return got_error_from_errno("fflush");
9381 return NULL;
9384 static const struct got_error *
9385 search_start_help_view(struct tog_view *view)
9387 view->state.help.matched_line = 0;
9388 return NULL;
9391 static void
9392 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9393 size_t *nlines, int **first, int **last, int **match, int **selected)
9395 struct tog_help_view_state *s = &view->state.help;
9397 *f = s->f;
9398 *nlines = s->nlines;
9399 *line_offsets = s->line_offsets;
9400 *match = &s->matched_line;
9401 *first = &s->first_displayed_line;
9402 *last = &s->last_displayed_line;
9403 *selected = &s->selected_line;
9406 static const struct got_error *
9407 show_help_view(struct tog_view *view)
9409 struct tog_help_view_state *s = &view->state.help;
9410 const struct got_error *err;
9411 regmatch_t *regmatch = &view->regmatch;
9412 wchar_t *wline;
9413 char *line;
9414 ssize_t linelen;
9415 size_t linesz = 0;
9416 int width, nprinted = 0, rc = 0;
9417 int eos = view->nlines;
9419 if (view_is_hsplit_top(view))
9420 --eos; /* account for border */
9422 s->lineno = 0;
9423 rewind(s->f);
9424 werase(view->window);
9426 if (view->gline > s->nlines - 1)
9427 view->gline = s->nlines - 1;
9429 err = win_draw_center(view->window, 0, 0, view->ncols,
9430 view_needs_focus_indication(view),
9431 "tog help (press q to return to tog)");
9432 if (err)
9433 return err;
9434 if (eos <= 1)
9435 return NULL;
9436 waddstr(view->window, "\n\n");
9437 eos -= 2;
9439 s->eof = 0;
9440 view->maxx = 0;
9441 line = NULL;
9442 while (eos > 0 && nprinted < eos) {
9443 attr_t attr = 0;
9445 linelen = getline(&line, &linesz, s->f);
9446 if (linelen == -1) {
9447 if (!feof(s->f)) {
9448 free(line);
9449 return got_ferror(s->f, GOT_ERR_IO);
9451 s->eof = 1;
9452 break;
9454 if (++s->lineno < s->first_displayed_line)
9455 continue;
9456 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9457 continue;
9458 if (s->lineno == view->hiline)
9459 attr = A_STANDOUT;
9461 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9462 view->x ? 1 : 0);
9463 if (err) {
9464 free(line);
9465 return err;
9467 view->maxx = MAX(view->maxx, width);
9468 free(wline);
9469 wline = NULL;
9471 if (attr)
9472 wattron(view->window, attr);
9473 if (s->first_displayed_line + nprinted == s->matched_line &&
9474 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9475 err = add_matched_line(&width, line, view->ncols - 1, 0,
9476 view->window, view->x, regmatch);
9477 if (err) {
9478 free(line);
9479 return err;
9481 } else {
9482 int skip;
9484 err = format_line(&wline, &width, &skip, line,
9485 view->x, view->ncols, 0, view->x ? 1 : 0);
9486 if (err) {
9487 free(line);
9488 return err;
9490 waddwstr(view->window, &wline[skip]);
9491 free(wline);
9492 wline = NULL;
9494 if (s->lineno == view->hiline) {
9495 while (width++ < view->ncols)
9496 waddch(view->window, ' ');
9497 } else {
9498 if (width < view->ncols)
9499 waddch(view->window, '\n');
9501 if (attr)
9502 wattroff(view->window, attr);
9503 if (++nprinted == 1)
9504 s->first_displayed_line = s->lineno;
9506 free(line);
9507 if (nprinted > 0)
9508 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9509 else
9510 s->last_displayed_line = s->first_displayed_line;
9512 view_border(view);
9514 if (s->eof) {
9515 rc = waddnstr(view->window,
9516 "See the tog(1) manual page for full documentation",
9517 view->ncols - 1);
9518 if (rc == ERR)
9519 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9520 } else {
9521 wmove(view->window, view->nlines - 1, 0);
9522 wclrtoeol(view->window);
9523 wstandout(view->window);
9524 rc = waddnstr(view->window, "scroll down for more...",
9525 view->ncols - 1);
9526 if (rc == ERR)
9527 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9528 if (getcurx(view->window) < view->ncols - 6) {
9529 rc = wprintw(view->window, "[%.0f%%]",
9530 100.00 * s->last_displayed_line / s->nlines);
9531 if (rc == ERR)
9532 return got_error_msg(GOT_ERR_IO, "wprintw");
9534 wstandend(view->window);
9537 return NULL;
9540 static const struct got_error *
9541 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9543 struct tog_help_view_state *s = &view->state.help;
9544 const struct got_error *err = NULL;
9545 char *line = NULL;
9546 ssize_t linelen;
9547 size_t linesz = 0;
9548 int eos, nscroll;
9550 eos = nscroll = view->nlines;
9551 if (view_is_hsplit_top(view))
9552 --eos; /* border */
9554 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9556 switch (ch) {
9557 case '0':
9558 case '$':
9559 case KEY_RIGHT:
9560 case 'l':
9561 case KEY_LEFT:
9562 case 'h':
9563 horizontal_scroll_input(view, ch);
9564 break;
9565 case 'g':
9566 case KEY_HOME:
9567 s->first_displayed_line = 1;
9568 view->count = 0;
9569 break;
9570 case 'G':
9571 case KEY_END:
9572 view->count = 0;
9573 if (s->eof)
9574 break;
9575 s->first_displayed_line = (s->nlines - eos) + 3;
9576 s->eof = 1;
9577 break;
9578 case 'k':
9579 case KEY_UP:
9580 if (s->first_displayed_line > 1)
9581 --s->first_displayed_line;
9582 else
9583 view->count = 0;
9584 break;
9585 case CTRL('u'):
9586 case 'u':
9587 nscroll /= 2;
9588 /* FALL THROUGH */
9589 case KEY_PPAGE:
9590 case CTRL('b'):
9591 case 'b':
9592 if (s->first_displayed_line == 1) {
9593 view->count = 0;
9594 break;
9596 while (--nscroll > 0 && s->first_displayed_line > 1)
9597 s->first_displayed_line--;
9598 break;
9599 case 'j':
9600 case KEY_DOWN:
9601 case CTRL('n'):
9602 if (!s->eof)
9603 ++s->first_displayed_line;
9604 else
9605 view->count = 0;
9606 break;
9607 case CTRL('d'):
9608 case 'd':
9609 nscroll /= 2;
9610 /* FALL THROUGH */
9611 case KEY_NPAGE:
9612 case CTRL('f'):
9613 case 'f':
9614 case ' ':
9615 if (s->eof) {
9616 view->count = 0;
9617 break;
9619 while (!s->eof && --nscroll > 0) {
9620 linelen = getline(&line, &linesz, s->f);
9621 s->first_displayed_line++;
9622 if (linelen == -1) {
9623 if (feof(s->f))
9624 s->eof = 1;
9625 else
9626 err = got_ferror(s->f, GOT_ERR_IO);
9627 break;
9630 free(line);
9631 break;
9632 default:
9633 view->count = 0;
9634 break;
9637 return err;
9640 static const struct got_error *
9641 close_help_view(struct tog_view *view)
9643 struct tog_help_view_state *s = &view->state.help;
9645 free(s->line_offsets);
9646 s->line_offsets = NULL;
9647 if (fclose(s->f) == EOF)
9648 return got_error_from_errno("fclose");
9650 return NULL;
9653 static const struct got_error *
9654 reset_help_view(struct tog_view *view)
9656 struct tog_help_view_state *s = &view->state.help;
9659 if (s->f && fclose(s->f) == EOF)
9660 return got_error_from_errno("fclose");
9662 wclear(view->window);
9663 view->count = 0;
9664 view->x = 0;
9665 s->all = !s->all;
9666 s->first_displayed_line = 1;
9667 s->last_displayed_line = view->nlines;
9668 s->matched_line = 0;
9670 return create_help(s);
9673 static const struct got_error *
9674 open_help_view(struct tog_view *view, struct tog_view *parent)
9676 const struct got_error *err = NULL;
9677 struct tog_help_view_state *s = &view->state.help;
9679 s->type = (enum tog_keymap_type)parent->type;
9680 s->first_displayed_line = 1;
9681 s->last_displayed_line = view->nlines;
9682 s->selected_line = 1;
9684 view->show = show_help_view;
9685 view->input = input_help_view;
9686 view->reset = reset_help_view;
9687 view->close = close_help_view;
9688 view->search_start = search_start_help_view;
9689 view->search_setup = search_setup_help_view;
9690 view->search_next = search_next_view_match;
9692 err = create_help(s);
9693 return err;
9696 static const struct got_error *
9697 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9698 enum tog_view_type request, int y, int x)
9700 const struct got_error *err = NULL;
9702 *new_view = NULL;
9704 switch (request) {
9705 case TOG_VIEW_DIFF:
9706 if (view->type == TOG_VIEW_LOG) {
9707 struct tog_log_view_state *s = &view->state.log;
9709 err = open_diff_view_for_commit(new_view, y, x,
9710 s->selected_entry->commit, s->selected_entry->id,
9711 view, s->repo);
9712 } else
9713 return got_error_msg(GOT_ERR_NOT_IMPL,
9714 "parent/child view pair not supported");
9715 break;
9716 case TOG_VIEW_BLAME:
9717 if (view->type == TOG_VIEW_TREE) {
9718 struct tog_tree_view_state *s = &view->state.tree;
9720 err = blame_tree_entry(new_view, y, x,
9721 s->selected_entry, &s->parents, s->commit_id,
9722 s->repo);
9723 } else
9724 return got_error_msg(GOT_ERR_NOT_IMPL,
9725 "parent/child view pair not supported");
9726 break;
9727 case TOG_VIEW_LOG:
9728 if (view->type == TOG_VIEW_BLAME)
9729 err = log_annotated_line(new_view, y, x,
9730 view->state.blame.repo, view->state.blame.id_to_log);
9731 else if (view->type == TOG_VIEW_TREE)
9732 err = log_selected_tree_entry(new_view, y, x,
9733 &view->state.tree);
9734 else if (view->type == TOG_VIEW_REF)
9735 err = log_ref_entry(new_view, y, x,
9736 view->state.ref.selected_entry,
9737 view->state.ref.repo);
9738 else
9739 return got_error_msg(GOT_ERR_NOT_IMPL,
9740 "parent/child view pair not supported");
9741 break;
9742 case TOG_VIEW_TREE:
9743 if (view->type == TOG_VIEW_LOG)
9744 err = browse_commit_tree(new_view, y, x,
9745 view->state.log.selected_entry,
9746 view->state.log.in_repo_path,
9747 view->state.log.head_ref_name,
9748 view->state.log.repo);
9749 else if (view->type == TOG_VIEW_REF)
9750 err = browse_ref_tree(new_view, y, x,
9751 view->state.ref.selected_entry,
9752 view->state.ref.repo);
9753 else
9754 return got_error_msg(GOT_ERR_NOT_IMPL,
9755 "parent/child view pair not supported");
9756 break;
9757 case TOG_VIEW_REF:
9758 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9759 if (*new_view == NULL)
9760 return got_error_from_errno("view_open");
9761 if (view->type == TOG_VIEW_LOG)
9762 err = open_ref_view(*new_view, view->state.log.repo);
9763 else if (view->type == TOG_VIEW_TREE)
9764 err = open_ref_view(*new_view, view->state.tree.repo);
9765 else
9766 err = got_error_msg(GOT_ERR_NOT_IMPL,
9767 "parent/child view pair not supported");
9768 if (err)
9769 view_close(*new_view);
9770 break;
9771 case TOG_VIEW_HELP:
9772 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9773 if (*new_view == NULL)
9774 return got_error_from_errno("view_open");
9775 err = open_help_view(*new_view, view);
9776 if (err)
9777 view_close(*new_view);
9778 break;
9779 default:
9780 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9783 return err;
9787 * If view was scrolled down to move the selected line into view when opening a
9788 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9790 static void
9791 offset_selection_up(struct tog_view *view)
9793 switch (view->type) {
9794 case TOG_VIEW_BLAME: {
9795 struct tog_blame_view_state *s = &view->state.blame;
9796 if (s->first_displayed_line == 1) {
9797 s->selected_line = MAX(s->selected_line - view->offset,
9798 1);
9799 break;
9801 if (s->first_displayed_line > view->offset)
9802 s->first_displayed_line -= view->offset;
9803 else
9804 s->first_displayed_line = 1;
9805 s->selected_line += view->offset;
9806 break;
9808 case TOG_VIEW_LOG:
9809 log_scroll_up(&view->state.log, view->offset);
9810 view->state.log.selected += view->offset;
9811 break;
9812 case TOG_VIEW_REF:
9813 ref_scroll_up(&view->state.ref, view->offset);
9814 view->state.ref.selected += view->offset;
9815 break;
9816 case TOG_VIEW_TREE:
9817 tree_scroll_up(&view->state.tree, view->offset);
9818 view->state.tree.selected += view->offset;
9819 break;
9820 default:
9821 break;
9824 view->offset = 0;
9828 * If the selected line is in the section of screen covered by the bottom split,
9829 * scroll down offset lines to move it into view and index its new position.
9831 static const struct got_error *
9832 offset_selection_down(struct tog_view *view)
9834 const struct got_error *err = NULL;
9835 const struct got_error *(*scrolld)(struct tog_view *, int);
9836 int *selected = NULL;
9837 int header, offset;
9839 switch (view->type) {
9840 case TOG_VIEW_BLAME: {
9841 struct tog_blame_view_state *s = &view->state.blame;
9842 header = 3;
9843 scrolld = NULL;
9844 if (s->selected_line > view->nlines - header) {
9845 offset = abs(view->nlines - s->selected_line - header);
9846 s->first_displayed_line += offset;
9847 s->selected_line -= offset;
9848 view->offset = offset;
9850 break;
9852 case TOG_VIEW_LOG: {
9853 struct tog_log_view_state *s = &view->state.log;
9854 scrolld = &log_scroll_down;
9855 header = view_is_parent_view(view) ? 3 : 2;
9856 selected = &s->selected;
9857 break;
9859 case TOG_VIEW_REF: {
9860 struct tog_ref_view_state *s = &view->state.ref;
9861 scrolld = &ref_scroll_down;
9862 header = 3;
9863 selected = &s->selected;
9864 break;
9866 case TOG_VIEW_TREE: {
9867 struct tog_tree_view_state *s = &view->state.tree;
9868 scrolld = &tree_scroll_down;
9869 header = 5;
9870 selected = &s->selected;
9871 break;
9873 default:
9874 selected = NULL;
9875 scrolld = NULL;
9876 header = 0;
9877 break;
9880 if (selected && *selected > view->nlines - header) {
9881 offset = abs(view->nlines - *selected - header);
9882 view->offset = offset;
9883 if (scrolld && offset) {
9884 err = scrolld(view, offset);
9885 *selected -= offset;
9889 return err;
9892 static void
9893 list_commands(FILE *fp)
9895 size_t i;
9897 fprintf(fp, "commands:");
9898 for (i = 0; i < nitems(tog_commands); i++) {
9899 const struct tog_cmd *cmd = &tog_commands[i];
9900 fprintf(fp, " %s", cmd->name);
9902 fputc('\n', fp);
9905 __dead static void
9906 usage(int hflag, int status)
9908 FILE *fp = (status == 0) ? stdout : stderr;
9910 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9911 getprogname());
9912 if (hflag) {
9913 fprintf(fp, "lazy usage: %s path\n", getprogname());
9914 list_commands(fp);
9916 exit(status);
9919 static char **
9920 make_argv(int argc, ...)
9922 va_list ap;
9923 char **argv;
9924 int i;
9926 va_start(ap, argc);
9928 argv = calloc(argc, sizeof(char *));
9929 if (argv == NULL)
9930 err(1, "calloc");
9931 for (i = 0; i < argc; i++) {
9932 argv[i] = strdup(va_arg(ap, char *));
9933 if (argv[i] == NULL)
9934 err(1, "strdup");
9937 va_end(ap);
9938 return argv;
9942 * Try to convert 'tog path' into a 'tog log path' command.
9943 * The user could simply have mistyped the command rather than knowingly
9944 * provided a path. So check whether argv[0] can in fact be resolved
9945 * to a path in the HEAD commit and print a special error if not.
9946 * This hack is for mpi@ <3
9948 static const struct got_error *
9949 tog_log_with_path(int argc, char *argv[])
9951 const struct got_error *error = NULL, *close_err;
9952 const struct tog_cmd *cmd = NULL;
9953 struct got_repository *repo = NULL;
9954 struct got_worktree *worktree = NULL;
9955 struct got_object_id *commit_id = NULL, *id = NULL;
9956 struct got_commit_object *commit = NULL;
9957 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9958 char *commit_id_str = NULL, **cmd_argv = NULL;
9959 int *pack_fds = NULL;
9961 cwd = getcwd(NULL, 0);
9962 if (cwd == NULL)
9963 return got_error_from_errno("getcwd");
9965 error = got_repo_pack_fds_open(&pack_fds);
9966 if (error != NULL)
9967 goto done;
9969 error = got_worktree_open(&worktree, cwd, NULL);
9970 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9971 goto done;
9973 if (worktree)
9974 repo_path = strdup(got_worktree_get_repo_path(worktree));
9975 else
9976 repo_path = strdup(cwd);
9977 if (repo_path == NULL) {
9978 error = got_error_from_errno("strdup");
9979 goto done;
9982 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9983 if (error != NULL)
9984 goto done;
9986 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9987 repo, worktree);
9988 if (error)
9989 goto done;
9991 error = tog_load_refs(repo, 0);
9992 if (error)
9993 goto done;
9994 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9995 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9996 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9997 if (error)
9998 goto done;
10000 if (worktree) {
10001 got_worktree_close(worktree);
10002 worktree = NULL;
10005 error = got_object_open_as_commit(&commit, repo, commit_id);
10006 if (error)
10007 goto done;
10009 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
10010 if (error) {
10011 if (error->code != GOT_ERR_NO_TREE_ENTRY)
10012 goto done;
10013 fprintf(stderr, "%s: '%s' is no known command or path\n",
10014 getprogname(), argv[0]);
10015 usage(1, 1);
10016 /* not reached */
10019 error = got_object_id_str(&commit_id_str, commit_id);
10020 if (error)
10021 goto done;
10023 cmd = &tog_commands[0]; /* log */
10024 argc = 4;
10025 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
10026 error = cmd->cmd_main(argc, cmd_argv);
10027 done:
10028 if (repo) {
10029 close_err = got_repo_close(repo);
10030 if (error == NULL)
10031 error = close_err;
10033 if (commit)
10034 got_object_commit_close(commit);
10035 if (worktree)
10036 got_worktree_close(worktree);
10037 if (pack_fds) {
10038 const struct got_error *pack_err =
10039 got_repo_pack_fds_close(pack_fds);
10040 if (error == NULL)
10041 error = pack_err;
10043 free(id);
10044 free(commit_id_str);
10045 free(commit_id);
10046 free(cwd);
10047 free(repo_path);
10048 free(in_repo_path);
10049 if (cmd_argv) {
10050 int i;
10051 for (i = 0; i < argc; i++)
10052 free(cmd_argv[i]);
10053 free(cmd_argv);
10055 tog_free_refs();
10056 return error;
10059 int
10060 main(int argc, char *argv[])
10062 const struct got_error *io_err, *error = NULL;
10063 const struct tog_cmd *cmd = NULL;
10064 int ch, hflag = 0, Vflag = 0;
10065 char **cmd_argv = NULL;
10066 static const struct option longopts[] = {
10067 { "version", no_argument, NULL, 'V' },
10068 { NULL, 0, NULL, 0}
10070 char *diff_algo_str = NULL;
10071 const char *test_script_path;
10073 setlocale(LC_CTYPE, "");
10076 * Override default signal handlers before starting ncurses.
10077 * This should prevent ncurses from installing its own
10078 * broken cleanup() signal handler.
10080 signal(SIGWINCH, tog_sigwinch);
10081 signal(SIGPIPE, tog_sigpipe);
10082 signal(SIGCONT, tog_sigcont);
10083 signal(SIGINT, tog_sigint);
10084 signal(SIGTERM, tog_sigterm);
10087 * Test mode init must happen before pledge() because "tty" will
10088 * not allow TTY-related ioctls to occur via regular files.
10090 test_script_path = getenv("TOG_TEST_SCRIPT");
10091 if (test_script_path != NULL) {
10092 error = init_mock_term(test_script_path);
10093 if (error) {
10094 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10095 return 1;
10097 } else if (!isatty(STDIN_FILENO))
10098 errx(1, "standard input is not a tty");
10100 #if !defined(PROFILE)
10101 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
10102 NULL) == -1)
10103 err(1, "pledge");
10104 #endif
10106 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
10107 switch (ch) {
10108 case 'h':
10109 hflag = 1;
10110 break;
10111 case 'V':
10112 Vflag = 1;
10113 break;
10114 default:
10115 usage(hflag, 1);
10116 /* NOTREACHED */
10120 argc -= optind;
10121 argv += optind;
10122 optind = 1;
10123 optreset = 1;
10125 if (Vflag) {
10126 got_version_print_str();
10127 return 0;
10130 if (argc == 0) {
10131 if (hflag)
10132 usage(hflag, 0);
10133 /* Build an argument vector which runs a default command. */
10134 cmd = &tog_commands[0];
10135 argc = 1;
10136 cmd_argv = make_argv(argc, cmd->name);
10137 } else {
10138 size_t i;
10140 /* Did the user specify a command? */
10141 for (i = 0; i < nitems(tog_commands); i++) {
10142 if (strncmp(tog_commands[i].name, argv[0],
10143 strlen(argv[0])) == 0) {
10144 cmd = &tog_commands[i];
10145 break;
10150 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
10151 if (diff_algo_str) {
10152 if (strcasecmp(diff_algo_str, "patience") == 0)
10153 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
10154 if (strcasecmp(diff_algo_str, "myers") == 0)
10155 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
10158 tog_base_commit.idx = -1;
10159 tog_base_commit.marker = GOT_WORKTREE_STATE_UNKNOWN;
10161 if (cmd == NULL) {
10162 if (argc != 1)
10163 usage(0, 1);
10164 /* No command specified; try log with a path */
10165 error = tog_log_with_path(argc, argv);
10166 } else {
10167 if (hflag)
10168 cmd->cmd_usage();
10169 else
10170 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
10173 if (using_mock_io) {
10174 io_err = tog_io_close();
10175 if (error == NULL)
10176 error = io_err;
10178 endwin();
10179 if (cmd_argv) {
10180 int i;
10181 for (i = 0; i < argc; i++)
10182 free(cmd_argv[i]);
10183 free(cmd_argv);
10186 if (error && error->code != GOT_ERR_CANCELLED &&
10187 error->code != GOT_ERR_EOF &&
10188 error->code != GOT_ERR_PRIVSEP_EXIT &&
10189 error->code != GOT_ERR_PRIVSEP_PIPE &&
10190 !(error->code == GOT_ERR_ERRNO && errno == EINTR)) {
10191 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10192 return 1;
10194 return 0;