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 "got_compat.h"
19 #include <sys/queue.h>
20 #include <sys/stat.h>
21 #include <sys/ioctl.h>
23 #include <ctype.h>
24 #include <errno.h>
25 #if defined(__FreeBSD__) || defined(__APPLE__)
26 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
27 #endif
28 #include <curses.h>
29 #include <panel.h>
30 #include <locale.h>
31 #include <signal.h>
32 #include <stdlib.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <getopt.h>
36 #include <string.h>
37 #include <err.h>
38 #include <unistd.h>
39 #include <limits.h>
40 #include <wchar.h>
41 #include <time.h>
42 #include <pthread.h>
43 #include <libgen.h>
44 #include <regex.h>
45 #include <sched.h>
47 #include "got_version.h"
48 #include "got_error.h"
49 #include "got_object.h"
50 #include "got_reference.h"
51 #include "got_repository.h"
52 #include "got_diff.h"
53 #include "got_opentemp.h"
54 #include "got_utf8.h"
55 #include "got_cancel.h"
56 #include "got_commit_graph.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_path.h"
60 #include "got_worktree.h"
61 #include "got_keyword.h"
63 #ifndef MIN
64 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
65 #endif
67 #ifndef MAX
68 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
69 #endif
71 #ifndef CTRL
72 #define CTRL(x) ((x) & 0x1f)
73 #endif
75 #ifndef nitems
76 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
77 #endif
79 struct tog_cmd {
80 const char *name;
81 const struct got_error *(*cmd_main)(int, char *[]);
82 void (*cmd_usage)(void);
83 };
85 __dead static void usage(int, int);
86 __dead static void usage_log(void);
87 __dead static void usage_diff(void);
88 __dead static void usage_blame(void);
89 __dead static void usage_tree(void);
90 __dead static void usage_ref(void);
92 static const struct got_error* cmd_log(int, char *[]);
93 static const struct got_error* cmd_diff(int, char *[]);
94 static const struct got_error* cmd_blame(int, char *[]);
95 static const struct got_error* cmd_tree(int, char *[]);
96 static const struct got_error* cmd_ref(int, char *[]);
98 static const struct tog_cmd tog_commands[] = {
99 { "log", cmd_log, usage_log },
100 { "diff", cmd_diff, usage_diff },
101 { "blame", cmd_blame, usage_blame },
102 { "tree", cmd_tree, usage_tree },
103 { "ref", cmd_ref, usage_ref },
104 };
106 enum tog_view_type {
107 TOG_VIEW_DIFF,
108 TOG_VIEW_LOG,
109 TOG_VIEW_BLAME,
110 TOG_VIEW_TREE,
111 TOG_VIEW_REF,
112 TOG_VIEW_HELP
113 };
115 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
116 enum tog_keymap_type {
117 TOG_KEYMAP_KEYS = -2,
118 TOG_KEYMAP_GLOBAL,
119 TOG_KEYMAP_DIFF,
120 TOG_KEYMAP_LOG,
121 TOG_KEYMAP_BLAME,
122 TOG_KEYMAP_TREE,
123 TOG_KEYMAP_REF,
124 TOG_KEYMAP_HELP
125 };
127 enum tog_view_mode {
128 TOG_VIEW_SPLIT_NONE,
129 TOG_VIEW_SPLIT_VERT,
130 TOG_VIEW_SPLIT_HRZN
131 };
133 #define HSPLIT_SCALE 0.3f /* default horizontal split scale */
135 #define TOG_EOF_STRING "(END)"
137 struct commit_queue_entry {
138 TAILQ_ENTRY(commit_queue_entry) entry;
139 struct got_object_id *id;
140 struct got_commit_object *commit;
141 int idx;
142 };
143 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
144 struct commit_queue {
145 int ncommits;
146 struct commit_queue_head head;
147 };
149 struct tog_color {
150 STAILQ_ENTRY(tog_color) entry;
151 regex_t regex;
152 short colorpair;
153 };
154 STAILQ_HEAD(tog_colors, tog_color);
156 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
157 static struct got_reflist_object_id_map *tog_refs_idmap;
158 static struct {
159 struct got_object_id *id;
160 int idx;
161 char marker;
162 } tog_base_commit;
163 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
165 static const struct got_error *
166 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
167 struct got_reference* re2)
169 const char *name1 = got_ref_get_name(re1);
170 const char *name2 = got_ref_get_name(re2);
171 int isbackup1, isbackup2;
173 /* Sort backup refs towards the bottom of the list. */
174 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
175 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
176 if (!isbackup1 && isbackup2) {
177 *cmp = -1;
178 return NULL;
179 } else if (isbackup1 && !isbackup2) {
180 *cmp = 1;
181 return NULL;
184 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
185 return NULL;
188 static const struct got_error *
189 tog_load_refs(struct got_repository *repo, int sort_by_date)
191 const struct got_error *err;
193 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
194 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
195 repo);
196 if (err)
197 return err;
199 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
200 repo);
203 static void
204 tog_free_refs(void)
206 if (tog_refs_idmap) {
207 got_reflist_object_id_map_free(tog_refs_idmap);
208 tog_refs_idmap = NULL;
210 got_ref_list_free(&tog_refs);
213 static const struct got_error *
214 add_color(struct tog_colors *colors, const char *pattern,
215 int idx, short color)
217 const struct got_error *err = NULL;
218 struct tog_color *tc;
219 int regerr = 0;
221 if (idx < 1 || idx > COLOR_PAIRS - 1)
222 return NULL;
224 init_pair(idx, color, -1);
226 tc = calloc(1, sizeof(*tc));
227 if (tc == NULL)
228 return got_error_from_errno("calloc");
229 regerr = regcomp(&tc->regex, pattern,
230 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
231 if (regerr) {
232 static char regerr_msg[512];
233 static char err_msg[512];
234 regerror(regerr, &tc->regex, regerr_msg,
235 sizeof(regerr_msg));
236 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
237 regerr_msg);
238 err = got_error_msg(GOT_ERR_REGEX, err_msg);
239 free(tc);
240 return err;
242 tc->colorpair = idx;
243 STAILQ_INSERT_HEAD(colors, tc, entry);
244 return NULL;
247 static void
248 free_colors(struct tog_colors *colors)
250 struct tog_color *tc;
252 while (!STAILQ_EMPTY(colors)) {
253 tc = STAILQ_FIRST(colors);
254 STAILQ_REMOVE_HEAD(colors, entry);
255 regfree(&tc->regex);
256 free(tc);
260 static struct tog_color *
261 get_color(struct tog_colors *colors, int colorpair)
263 struct tog_color *tc = NULL;
265 STAILQ_FOREACH(tc, colors, entry) {
266 if (tc->colorpair == colorpair)
267 return tc;
270 return NULL;
273 static int
274 default_color_value(const char *envvar)
276 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
277 return COLOR_MAGENTA;
278 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
279 return COLOR_CYAN;
280 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
281 return COLOR_YELLOW;
282 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
283 return COLOR_GREEN;
284 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
285 return COLOR_MAGENTA;
286 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
287 return COLOR_MAGENTA;
288 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
289 return COLOR_CYAN;
290 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
291 return COLOR_GREEN;
292 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
293 return COLOR_GREEN;
294 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
295 return COLOR_CYAN;
296 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
297 return COLOR_YELLOW;
298 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
299 return COLOR_GREEN;
300 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
301 return COLOR_MAGENTA;
302 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
303 return COLOR_YELLOW;
304 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
305 return COLOR_CYAN;
307 return -1;
310 static int
311 get_color_value(const char *envvar)
313 const char *val = getenv(envvar);
315 if (val == NULL)
316 return default_color_value(envvar);
318 if (strcasecmp(val, "black") == 0)
319 return COLOR_BLACK;
320 if (strcasecmp(val, "red") == 0)
321 return COLOR_RED;
322 if (strcasecmp(val, "green") == 0)
323 return COLOR_GREEN;
324 if (strcasecmp(val, "yellow") == 0)
325 return COLOR_YELLOW;
326 if (strcasecmp(val, "blue") == 0)
327 return COLOR_BLUE;
328 if (strcasecmp(val, "magenta") == 0)
329 return COLOR_MAGENTA;
330 if (strcasecmp(val, "cyan") == 0)
331 return COLOR_CYAN;
332 if (strcasecmp(val, "white") == 0)
333 return COLOR_WHITE;
334 if (strcasecmp(val, "default") == 0)
335 return -1;
337 return default_color_value(envvar);
340 struct tog_diff_view_state {
341 struct got_object_id *id1, *id2;
342 const char *label1, *label2;
343 FILE *f, *f1, *f2;
344 int fd1, fd2;
345 int lineno;
346 int first_displayed_line;
347 int last_displayed_line;
348 int eof;
349 int diff_context;
350 int ignore_whitespace;
351 int force_text_diff;
352 struct got_repository *repo;
353 struct got_diff_line *lines;
354 size_t nlines;
355 int matched_line;
356 int selected_line;
358 /* passed from log or blame view; may be NULL */
359 struct tog_view *parent_view;
360 };
362 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
363 static volatile sig_atomic_t tog_thread_error;
365 struct tog_log_thread_args {
366 pthread_cond_t need_commits;
367 pthread_cond_t commit_loaded;
368 int commits_needed;
369 int load_all;
370 struct got_commit_graph *graph;
371 struct commit_queue *real_commits;
372 const char *in_repo_path;
373 struct got_object_id *start_id;
374 struct got_repository *repo;
375 int *pack_fds;
376 int log_complete;
377 pthread_cond_t log_loaded;
378 sig_atomic_t *quit;
379 struct commit_queue_entry **first_displayed_entry;
380 struct commit_queue_entry **selected_entry;
381 int *searching;
382 int *search_next_done;
383 regex_t *regex;
384 int *limiting;
385 int limit_match;
386 regex_t *limit_regex;
387 struct commit_queue *limit_commits;
388 struct got_worktree *worktree;
389 int need_commit_marker;
390 };
392 struct tog_log_view_state {
393 struct commit_queue *commits;
394 struct commit_queue_entry *first_displayed_entry;
395 struct commit_queue_entry *last_displayed_entry;
396 struct commit_queue_entry *selected_entry;
397 struct commit_queue real_commits;
398 int selected;
399 char *in_repo_path;
400 char *head_ref_name;
401 int log_branches;
402 struct got_repository *repo;
403 struct got_object_id *start_id;
404 sig_atomic_t quit;
405 pthread_t thread;
406 struct tog_log_thread_args thread_args;
407 struct commit_queue_entry *matched_entry;
408 struct commit_queue_entry *search_entry;
409 struct tog_colors colors;
410 int use_committer;
411 int limit_view;
412 regex_t limit_regex;
413 struct commit_queue limit_commits;
414 };
416 #define TOG_COLOR_DIFF_MINUS 1
417 #define TOG_COLOR_DIFF_PLUS 2
418 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
419 #define TOG_COLOR_DIFF_META 4
420 #define TOG_COLOR_TREE_SUBMODULE 5
421 #define TOG_COLOR_TREE_SYMLINK 6
422 #define TOG_COLOR_TREE_DIRECTORY 7
423 #define TOG_COLOR_TREE_EXECUTABLE 8
424 #define TOG_COLOR_COMMIT 9
425 #define TOG_COLOR_AUTHOR 10
426 #define TOG_COLOR_DATE 11
427 #define TOG_COLOR_REFS_HEADS 12
428 #define TOG_COLOR_REFS_TAGS 13
429 #define TOG_COLOR_REFS_REMOTES 14
430 #define TOG_COLOR_REFS_BACKUP 15
432 struct tog_blame_cb_args {
433 struct tog_blame_line *lines; /* one per line */
434 int nlines;
436 struct tog_view *view;
437 struct got_object_id *commit_id;
438 int *quit;
439 };
441 struct tog_blame_thread_args {
442 const char *path;
443 struct got_repository *repo;
444 struct tog_blame_cb_args *cb_args;
445 int *complete;
446 got_cancel_cb cancel_cb;
447 void *cancel_arg;
448 pthread_cond_t blame_complete;
449 };
451 struct tog_blame {
452 FILE *f;
453 off_t filesize;
454 struct tog_blame_line *lines;
455 int nlines;
456 off_t *line_offsets;
457 pthread_t thread;
458 struct tog_blame_thread_args thread_args;
459 struct tog_blame_cb_args cb_args;
460 const char *path;
461 int *pack_fds;
462 };
464 struct tog_blame_view_state {
465 int first_displayed_line;
466 int last_displayed_line;
467 int selected_line;
468 int last_diffed_line;
469 int blame_complete;
470 int eof;
471 int done;
472 struct got_object_id_queue blamed_commits;
473 struct got_object_qid *blamed_commit;
474 char *path;
475 struct got_repository *repo;
476 struct got_object_id *commit_id;
477 struct got_object_id *id_to_log;
478 struct tog_blame blame;
479 int matched_line;
480 struct tog_colors colors;
481 };
483 struct tog_parent_tree {
484 TAILQ_ENTRY(tog_parent_tree) entry;
485 struct got_tree_object *tree;
486 struct got_tree_entry *first_displayed_entry;
487 struct got_tree_entry *selected_entry;
488 int selected;
489 };
491 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
493 struct tog_tree_view_state {
494 char *tree_label;
495 struct got_object_id *commit_id;/* commit which this tree belongs to */
496 struct got_tree_object *root; /* the commit's root tree entry */
497 struct got_tree_object *tree; /* currently displayed (sub-)tree */
498 struct got_tree_entry *first_displayed_entry;
499 struct got_tree_entry *last_displayed_entry;
500 struct got_tree_entry *selected_entry;
501 int ndisplayed, selected, show_ids;
502 struct tog_parent_trees parents; /* parent trees of current sub-tree */
503 char *head_ref_name;
504 struct got_repository *repo;
505 struct got_tree_entry *matched_entry;
506 struct tog_colors colors;
507 };
509 struct tog_reflist_entry {
510 TAILQ_ENTRY(tog_reflist_entry) entry;
511 struct got_reference *ref;
512 int idx;
513 };
515 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
517 struct tog_ref_view_state {
518 struct tog_reflist_head refs;
519 struct tog_reflist_entry *first_displayed_entry;
520 struct tog_reflist_entry *last_displayed_entry;
521 struct tog_reflist_entry *selected_entry;
522 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
523 struct got_repository *repo;
524 struct tog_reflist_entry *matched_entry;
525 struct tog_colors colors;
526 };
528 struct tog_help_view_state {
529 FILE *f;
530 off_t *line_offsets;
531 size_t nlines;
532 int lineno;
533 int first_displayed_line;
534 int last_displayed_line;
535 int eof;
536 int matched_line;
537 int selected_line;
538 int all;
539 enum tog_keymap_type type;
540 };
542 #define GENERATE_HELP \
543 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
544 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
545 KEY_("k C-p Up", "Move cursor or page up one line"), \
546 KEY_("j C-n Down", "Move cursor or page down one line"), \
547 KEY_("C-b b PgUp", "Scroll the view up one page"), \
548 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
549 KEY_("C-u u", "Scroll the view up one half page"), \
550 KEY_("C-d d", "Scroll the view down one half page"), \
551 KEY_("g", "Go to line N (default: first line)"), \
552 KEY_("Home =", "Go to the first line"), \
553 KEY_("G", "Go to line N (default: last line)"), \
554 KEY_("End *", "Go to the last line"), \
555 KEY_("l Right", "Scroll the view right"), \
556 KEY_("h Left", "Scroll the view left"), \
557 KEY_("$", "Scroll view to the rightmost position"), \
558 KEY_("0", "Scroll view to the leftmost position"), \
559 KEY_("-", "Decrease size of the focussed split"), \
560 KEY_("+", "Increase size of the focussed split"), \
561 KEY_("Tab", "Switch focus between views"), \
562 KEY_("F", "Toggle fullscreen mode"), \
563 KEY_("S", "Switch split-screen layout"), \
564 KEY_("/", "Open prompt to enter search term"), \
565 KEY_("n", "Find next line/token matching the current search term"), \
566 KEY_("N", "Find previous line/token matching the current search term"),\
567 KEY_("q", "Quit the focussed view; Quit help screen"), \
568 KEY_("Q", "Quit tog"), \
570 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
571 KEY_("< ,", "Move cursor up one commit"), \
572 KEY_("> .", "Move cursor down one commit"), \
573 KEY_("Enter", "Open diff view of the selected commit"), \
574 KEY_("B", "Reload the log view and toggle display of merged commits"), \
575 KEY_("R", "Open ref view of all repository references"), \
576 KEY_("T", "Display tree view of the repository from the selected" \
577 " commit"), \
578 KEY_("@", "Toggle between displaying author and committer name"), \
579 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
580 KEY_("C-g Backspace", "Cancel current search or log operation"), \
581 KEY_("C-l", "Reload the log view with new commits in the repository"), \
583 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
584 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
585 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
586 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
587 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
588 " data"), \
589 KEY_("(", "Go to the previous file in the diff"), \
590 KEY_(")", "Go to the next file in the diff"), \
591 KEY_("{", "Go to the previous hunk in the diff"), \
592 KEY_("}", "Go to the next hunk in the diff"), \
593 KEY_("[", "Decrease the number of context lines"), \
594 KEY_("]", "Increase the number of context lines"), \
595 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
597 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
598 KEY_("Enter", "Display diff view of the selected line's commit"), \
599 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
600 KEY_("L", "Open log view for the currently selected annotated line"), \
601 KEY_("C", "Reload view with the previously blamed commit"), \
602 KEY_("c", "Reload view with the version of the file found in the" \
603 " selected line's commit"), \
604 KEY_("p", "Reload view with the version of the file found in the" \
605 " selected line's parent commit"), \
607 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
608 KEY_("Enter", "Enter selected directory or open blame view of the" \
609 " selected file"), \
610 KEY_("L", "Open log view for the selected entry"), \
611 KEY_("R", "Open ref view of all repository references"), \
612 KEY_("i", "Show object IDs for all tree entries"), \
613 KEY_("Backspace", "Return to the parent directory"), \
615 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
616 KEY_("Enter", "Display log view of the selected reference"), \
617 KEY_("T", "Display tree view of the selected reference"), \
618 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
619 KEY_("m", "Toggle display of last modified date for each reference"), \
620 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
621 KEY_("C-l", "Reload view with all repository references")
623 struct tog_key_map {
624 const char *keys;
625 const char *info;
626 enum tog_keymap_type type;
627 };
629 /* curses io for tog regress */
630 struct tog_io {
631 FILE *cin;
632 FILE *cout;
633 FILE *f;
634 FILE *sdump;
635 int wait_for_ui;
636 } tog_io;
637 static int using_mock_io;
639 #define TOG_KEY_SCRDUMP SHRT_MIN
641 /*
642 * We implement two types of views: parent views and child views.
644 * The 'Tab' key switches focus between a parent view and its child view.
645 * Child views are shown side-by-side to their parent view, provided
646 * there is enough screen estate.
648 * When a new view is opened from within a parent view, this new view
649 * becomes a child view of the parent view, replacing any existing child.
651 * When a new view is opened from within a child view, this new view
652 * becomes a parent view which will obscure the views below until the
653 * user quits the new parent view by typing 'q'.
655 * This list of views contains parent views only.
656 * Child views are only pointed to by their parent view.
657 */
658 TAILQ_HEAD(tog_view_list_head, tog_view);
660 struct tog_view {
661 TAILQ_ENTRY(tog_view) entry;
662 WINDOW *window;
663 PANEL *panel;
664 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
665 int resized_y, resized_x; /* begin_y/x based on user resizing */
666 int maxx, x; /* max column and current start column */
667 int lines, cols; /* copies of LINES and COLS */
668 int nscrolled, offset; /* lines scrolled and hsplit line offset */
669 int gline, hiline; /* navigate to and highlight this nG line */
670 int ch, count; /* current keymap and count prefix */
671 int resized; /* set when in a resize event */
672 int focussed; /* Only set on one parent or child view at a time. */
673 int dying;
674 struct tog_view *parent;
675 struct tog_view *child;
677 /*
678 * This flag is initially set on parent views when a new child view
679 * is created. It gets toggled when the 'Tab' key switches focus
680 * between parent and child.
681 * The flag indicates whether focus should be passed on to our child
682 * view if this parent view gets picked for focus after another parent
683 * view was closed. This prevents child views from losing focus in such
684 * situations.
685 */
686 int focus_child;
688 enum tog_view_mode mode;
689 /* type-specific state */
690 enum tog_view_type type;
691 union {
692 struct tog_diff_view_state diff;
693 struct tog_log_view_state log;
694 struct tog_blame_view_state blame;
695 struct tog_tree_view_state tree;
696 struct tog_ref_view_state ref;
697 struct tog_help_view_state help;
698 } state;
700 const struct got_error *(*show)(struct tog_view *);
701 const struct got_error *(*input)(struct tog_view **,
702 struct tog_view *, int);
703 const struct got_error *(*reset)(struct tog_view *);
704 const struct got_error *(*resize)(struct tog_view *, int);
705 const struct got_error *(*close)(struct tog_view *);
707 const struct got_error *(*search_start)(struct tog_view *);
708 const struct got_error *(*search_next)(struct tog_view *);
709 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
710 int **, int **, int **, int **);
711 int search_started;
712 int searching;
713 #define TOG_SEARCH_FORWARD 1
714 #define TOG_SEARCH_BACKWARD 2
715 int search_next_done;
716 #define TOG_SEARCH_HAVE_MORE 1
717 #define TOG_SEARCH_NO_MORE 2
718 #define TOG_SEARCH_HAVE_NONE 3
719 regex_t regex;
720 regmatch_t regmatch;
721 const char *action;
722 };
724 static const struct got_error *open_diff_view(struct tog_view *,
725 struct got_object_id *, struct got_object_id *,
726 const char *, const char *, int, int, int, struct tog_view *,
727 struct got_repository *);
728 static const struct got_error *show_diff_view(struct tog_view *);
729 static const struct got_error *input_diff_view(struct tog_view **,
730 struct tog_view *, int);
731 static const struct got_error *reset_diff_view(struct tog_view *);
732 static const struct got_error* close_diff_view(struct tog_view *);
733 static const struct got_error *search_start_diff_view(struct tog_view *);
734 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
735 size_t *, int **, int **, int **, int **);
736 static const struct got_error *search_next_view_match(struct tog_view *);
738 static const struct got_error *open_log_view(struct tog_view *,
739 struct got_object_id *, struct got_repository *,
740 const char *, const char *, int, struct got_worktree *);
741 static const struct got_error * show_log_view(struct tog_view *);
742 static const struct got_error *input_log_view(struct tog_view **,
743 struct tog_view *, int);
744 static const struct got_error *resize_log_view(struct tog_view *, int);
745 static const struct got_error *close_log_view(struct tog_view *);
746 static const struct got_error *search_start_log_view(struct tog_view *);
747 static const struct got_error *search_next_log_view(struct tog_view *);
749 static const struct got_error *open_blame_view(struct tog_view *, char *,
750 struct got_object_id *, struct got_repository *);
751 static const struct got_error *show_blame_view(struct tog_view *);
752 static const struct got_error *input_blame_view(struct tog_view **,
753 struct tog_view *, int);
754 static const struct got_error *reset_blame_view(struct tog_view *);
755 static const struct got_error *close_blame_view(struct tog_view *);
756 static const struct got_error *search_start_blame_view(struct tog_view *);
757 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
758 size_t *, int **, int **, int **, int **);
760 static const struct got_error *open_tree_view(struct tog_view *,
761 struct got_object_id *, const char *, struct got_repository *);
762 static const struct got_error *show_tree_view(struct tog_view *);
763 static const struct got_error *input_tree_view(struct tog_view **,
764 struct tog_view *, int);
765 static const struct got_error *close_tree_view(struct tog_view *);
766 static const struct got_error *search_start_tree_view(struct tog_view *);
767 static const struct got_error *search_next_tree_view(struct tog_view *);
769 static const struct got_error *open_ref_view(struct tog_view *,
770 struct got_repository *);
771 static const struct got_error *show_ref_view(struct tog_view *);
772 static const struct got_error *input_ref_view(struct tog_view **,
773 struct tog_view *, int);
774 static const struct got_error *close_ref_view(struct tog_view *);
775 static const struct got_error *search_start_ref_view(struct tog_view *);
776 static const struct got_error *search_next_ref_view(struct tog_view *);
778 static const struct got_error *open_help_view(struct tog_view *,
779 struct tog_view *);
780 static const struct got_error *show_help_view(struct tog_view *);
781 static const struct got_error *input_help_view(struct tog_view **,
782 struct tog_view *, int);
783 static const struct got_error *reset_help_view(struct tog_view *);
784 static const struct got_error* close_help_view(struct tog_view *);
785 static const struct got_error *search_start_help_view(struct tog_view *);
786 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
787 size_t *, int **, int **, int **, int **);
789 static volatile sig_atomic_t tog_sigwinch_received;
790 static volatile sig_atomic_t tog_sigpipe_received;
791 static volatile sig_atomic_t tog_sigcont_received;
792 static volatile sig_atomic_t tog_sigint_received;
793 static volatile sig_atomic_t tog_sigterm_received;
795 static void
796 tog_sigwinch(int signo)
798 tog_sigwinch_received = 1;
801 static void
802 tog_sigpipe(int signo)
804 tog_sigpipe_received = 1;
807 static void
808 tog_sigcont(int signo)
810 tog_sigcont_received = 1;
813 static void
814 tog_sigint(int signo)
816 tog_sigint_received = 1;
819 static void
820 tog_sigterm(int signo)
822 tog_sigterm_received = 1;
825 static int
826 tog_fatal_signal_received(void)
828 return (tog_sigpipe_received ||
829 tog_sigint_received || tog_sigterm_received);
832 static const struct got_error *
833 view_close(struct tog_view *view)
835 const struct got_error *err = NULL, *child_err = NULL;
837 if (view->child) {
838 child_err = view_close(view->child);
839 view->child = NULL;
841 if (view->close)
842 err = view->close(view);
843 if (view->panel)
844 del_panel(view->panel);
845 if (view->window)
846 delwin(view->window);
847 free(view);
848 return err ? err : child_err;
851 static struct tog_view *
852 view_open(int nlines, int ncols, int begin_y, int begin_x,
853 enum tog_view_type type)
855 struct tog_view *view = calloc(1, sizeof(*view));
857 if (view == NULL)
858 return NULL;
860 view->type = type;
861 view->lines = LINES;
862 view->cols = COLS;
863 view->nlines = nlines ? nlines : LINES - begin_y;
864 view->ncols = ncols ? ncols : COLS - begin_x;
865 view->begin_y = begin_y;
866 view->begin_x = begin_x;
867 view->window = newwin(nlines, ncols, begin_y, begin_x);
868 if (view->window == NULL) {
869 view_close(view);
870 return NULL;
872 view->panel = new_panel(view->window);
873 if (view->panel == NULL ||
874 set_panel_userptr(view->panel, view) != OK) {
875 view_close(view);
876 return NULL;
879 keypad(view->window, TRUE);
880 return view;
883 static int
884 view_split_begin_x(int begin_x)
886 if (begin_x > 0 || COLS < 120)
887 return 0;
888 return (COLS - MAX(COLS / 2, 80));
891 /* XXX Stub till we decide what to do. */
892 static int
893 view_split_begin_y(int lines)
895 return lines * HSPLIT_SCALE;
898 static const struct got_error *view_resize(struct tog_view *);
900 static const struct got_error *
901 view_splitscreen(struct tog_view *view)
903 const struct got_error *err = NULL;
905 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
906 if (view->resized_y && view->resized_y < view->lines)
907 view->begin_y = view->resized_y;
908 else
909 view->begin_y = view_split_begin_y(view->nlines);
910 view->begin_x = 0;
911 } else if (!view->resized) {
912 if (view->resized_x && view->resized_x < view->cols - 1 &&
913 view->cols > 119)
914 view->begin_x = view->resized_x;
915 else
916 view->begin_x = view_split_begin_x(0);
917 view->begin_y = 0;
919 view->nlines = LINES - view->begin_y;
920 view->ncols = COLS - view->begin_x;
921 view->lines = LINES;
922 view->cols = COLS;
923 err = view_resize(view);
924 if (err)
925 return err;
927 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
928 view->parent->nlines = view->begin_y;
930 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
931 return got_error_from_errno("mvwin");
933 return NULL;
936 static const struct got_error *
937 view_fullscreen(struct tog_view *view)
939 const struct got_error *err = NULL;
941 view->begin_x = 0;
942 view->begin_y = view->resized ? view->begin_y : 0;
943 view->nlines = view->resized ? view->nlines : LINES;
944 view->ncols = COLS;
945 view->lines = LINES;
946 view->cols = COLS;
947 err = view_resize(view);
948 if (err)
949 return err;
951 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
952 return got_error_from_errno("mvwin");
954 return NULL;
957 static int
958 view_is_parent_view(struct tog_view *view)
960 return view->parent == NULL;
963 static int
964 view_is_splitscreen(struct tog_view *view)
966 return view->begin_x > 0 || view->begin_y > 0;
969 static int
970 view_is_fullscreen(struct tog_view *view)
972 return view->nlines == LINES && view->ncols == COLS;
975 static int
976 view_is_hsplit_top(struct tog_view *view)
978 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
979 view_is_splitscreen(view->child);
982 static void
983 view_border(struct tog_view *view)
985 PANEL *panel;
986 const struct tog_view *view_above;
988 if (view->parent)
989 return view_border(view->parent);
991 panel = panel_above(view->panel);
992 if (panel == NULL)
993 return;
995 view_above = panel_userptr(panel);
996 if (view->mode == TOG_VIEW_SPLIT_HRZN)
997 mvwhline(view->window, view_above->begin_y - 1,
998 view->begin_x, ACS_HLINE, view->ncols);
999 else
1000 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
1001 ACS_VLINE, view->nlines);
1004 static const struct got_error *view_init_hsplit(struct tog_view *, int);
1005 static const struct got_error *request_log_commits(struct tog_view *);
1006 static const struct got_error *offset_selection_down(struct tog_view *);
1007 static void offset_selection_up(struct tog_view *);
1008 static void view_get_split(struct tog_view *, int *, int *);
1010 static const struct got_error *
1011 view_resize(struct tog_view *view)
1013 const struct got_error *err = NULL;
1014 int dif, nlines, ncols;
1016 dif = LINES - view->lines; /* line difference */
1018 if (view->lines > LINES)
1019 nlines = view->nlines - (view->lines - LINES);
1020 else
1021 nlines = view->nlines + (LINES - view->lines);
1022 if (view->cols > COLS)
1023 ncols = view->ncols - (view->cols - COLS);
1024 else
1025 ncols = view->ncols + (COLS - view->cols);
1027 if (view->child) {
1028 int hs = view->child->begin_y;
1030 if (!view_is_fullscreen(view))
1031 view->child->begin_x = view_split_begin_x(view->begin_x);
1032 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1033 view->child->begin_x == 0) {
1034 ncols = COLS;
1036 view_fullscreen(view->child);
1037 if (view->child->focussed)
1038 show_panel(view->child->panel);
1039 else
1040 show_panel(view->panel);
1041 } else {
1042 ncols = view->child->begin_x;
1044 view_splitscreen(view->child);
1045 show_panel(view->child->panel);
1048 * XXX This is ugly and needs to be moved into the above
1049 * logic but "works" for now and my attempts at moving it
1050 * break either 'tab' or 'F' key maps in horizontal splits.
1052 if (hs) {
1053 err = view_splitscreen(view->child);
1054 if (err)
1055 return err;
1056 if (dif < 0) { /* top split decreased */
1057 err = offset_selection_down(view);
1058 if (err)
1059 return err;
1061 view_border(view);
1062 update_panels();
1063 doupdate();
1064 show_panel(view->child->panel);
1065 nlines = view->nlines;
1067 } else if (view->parent == NULL)
1068 ncols = COLS;
1070 if (view->resize && dif > 0) {
1071 err = view->resize(view, dif);
1072 if (err)
1073 return err;
1076 if (wresize(view->window, nlines, ncols) == ERR)
1077 return got_error_from_errno("wresize");
1078 if (replace_panel(view->panel, view->window) == ERR)
1079 return got_error_from_errno("replace_panel");
1080 wclear(view->window);
1082 view->nlines = nlines;
1083 view->ncols = ncols;
1084 view->lines = LINES;
1085 view->cols = COLS;
1087 return NULL;
1090 static const struct got_error *
1091 resize_log_view(struct tog_view *view, int increase)
1093 struct tog_log_view_state *s = &view->state.log;
1094 const struct got_error *err = NULL;
1095 int n = 0;
1097 if (s->selected_entry)
1098 n = s->selected_entry->idx + view->lines - s->selected;
1101 * Request commits to account for the increased
1102 * height so we have enough to populate the view.
1104 if (s->commits->ncommits < n) {
1105 view->nscrolled = n - s->commits->ncommits + increase + 1;
1106 err = request_log_commits(view);
1109 return err;
1112 static void
1113 view_adjust_offset(struct tog_view *view, int n)
1115 if (n == 0)
1116 return;
1118 if (view->parent && view->parent->offset) {
1119 if (view->parent->offset + n >= 0)
1120 view->parent->offset += n;
1121 else
1122 view->parent->offset = 0;
1123 } else if (view->offset) {
1124 if (view->offset - n >= 0)
1125 view->offset -= n;
1126 else
1127 view->offset = 0;
1131 static const struct got_error *
1132 view_resize_split(struct tog_view *view, int resize)
1134 const struct got_error *err = NULL;
1135 struct tog_view *v = NULL;
1137 if (view->parent)
1138 v = view->parent;
1139 else
1140 v = view;
1142 if (!v->child || !view_is_splitscreen(v->child))
1143 return NULL;
1145 v->resized = v->child->resized = resize; /* lock for resize event */
1147 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1148 if (v->child->resized_y)
1149 v->child->begin_y = v->child->resized_y;
1150 if (view->parent)
1151 v->child->begin_y -= resize;
1152 else
1153 v->child->begin_y += resize;
1154 if (v->child->begin_y < 3) {
1155 view->count = 0;
1156 v->child->begin_y = 3;
1157 } else if (v->child->begin_y > LINES - 1) {
1158 view->count = 0;
1159 v->child->begin_y = LINES - 1;
1161 v->ncols = COLS;
1162 v->child->ncols = COLS;
1163 view_adjust_offset(view, resize);
1164 err = view_init_hsplit(v, v->child->begin_y);
1165 if (err)
1166 return err;
1167 v->child->resized_y = v->child->begin_y;
1168 } else {
1169 if (v->child->resized_x)
1170 v->child->begin_x = v->child->resized_x;
1171 if (view->parent)
1172 v->child->begin_x -= resize;
1173 else
1174 v->child->begin_x += resize;
1175 if (v->child->begin_x < 11) {
1176 view->count = 0;
1177 v->child->begin_x = 11;
1178 } else if (v->child->begin_x > COLS - 1) {
1179 view->count = 0;
1180 v->child->begin_x = COLS - 1;
1182 v->child->resized_x = v->child->begin_x;
1185 v->child->mode = v->mode;
1186 v->child->nlines = v->lines - v->child->begin_y;
1187 v->child->ncols = v->cols - v->child->begin_x;
1188 v->focus_child = 1;
1190 err = view_fullscreen(v);
1191 if (err)
1192 return err;
1193 err = view_splitscreen(v->child);
1194 if (err)
1195 return err;
1197 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1198 err = offset_selection_down(v->child);
1199 if (err)
1200 return err;
1203 if (v->resize)
1204 err = v->resize(v, 0);
1205 else if (v->child->resize)
1206 err = v->child->resize(v->child, 0);
1208 v->resized = v->child->resized = 0;
1210 return err;
1213 static void
1214 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1216 struct tog_view *v = src->child ? src->child : src;
1218 dst->resized_x = v->resized_x;
1219 dst->resized_y = v->resized_y;
1222 static const struct got_error *
1223 view_close_child(struct tog_view *view)
1225 const struct got_error *err = NULL;
1227 if (view->child == NULL)
1228 return NULL;
1230 err = view_close(view->child);
1231 view->child = NULL;
1232 return err;
1235 static const struct got_error *
1236 view_set_child(struct tog_view *view, struct tog_view *child)
1238 const struct got_error *err = NULL;
1240 view->child = child;
1241 child->parent = view;
1243 err = view_resize(view);
1244 if (err)
1245 return err;
1247 if (view->child->resized_x || view->child->resized_y)
1248 err = view_resize_split(view, 0);
1250 return err;
1253 static const struct got_error *view_dispatch_request(struct tog_view **,
1254 struct tog_view *, enum tog_view_type, int, int);
1256 static const struct got_error *
1257 view_request_new(struct tog_view **requested, struct tog_view *view,
1258 enum tog_view_type request)
1260 struct tog_view *new_view = NULL;
1261 const struct got_error *err;
1262 int y = 0, x = 0;
1264 *requested = NULL;
1266 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1267 view_get_split(view, &y, &x);
1269 err = view_dispatch_request(&new_view, view, request, y, x);
1270 if (err)
1271 return err;
1273 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1274 request != TOG_VIEW_HELP) {
1275 err = view_init_hsplit(view, y);
1276 if (err)
1277 return err;
1280 view->focussed = 0;
1281 new_view->focussed = 1;
1282 new_view->mode = view->mode;
1283 new_view->nlines = request == TOG_VIEW_HELP ?
1284 view->lines : view->lines - y;
1286 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1287 view_transfer_size(new_view, view);
1288 err = view_close_child(view);
1289 if (err)
1290 return err;
1291 err = view_set_child(view, new_view);
1292 if (err)
1293 return err;
1294 view->focus_child = 1;
1295 } else
1296 *requested = new_view;
1298 return NULL;
1301 static void
1302 tog_resizeterm(void)
1304 int cols, lines;
1305 struct winsize size;
1307 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1308 cols = 80; /* Default */
1309 lines = 24;
1310 } else {
1311 cols = size.ws_col;
1312 lines = size.ws_row;
1314 resize_term(lines, cols);
1317 static const struct got_error *
1318 view_search_start(struct tog_view *view, int fast_refresh)
1320 const struct got_error *err = NULL;
1321 struct tog_view *v = view;
1322 char pattern[1024];
1323 int ret;
1325 if (view->search_started) {
1326 regfree(&view->regex);
1327 view->searching = 0;
1328 memset(&view->regmatch, 0, sizeof(view->regmatch));
1330 view->search_started = 0;
1332 if (view->nlines < 1)
1333 return NULL;
1335 if (view_is_hsplit_top(view))
1336 v = view->child;
1337 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1338 v = view->parent;
1340 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1341 wclrtoeol(v->window);
1343 nodelay(v->window, FALSE); /* block for search term input */
1344 nocbreak();
1345 echo();
1346 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1347 wrefresh(v->window);
1348 cbreak();
1349 noecho();
1350 nodelay(v->window, TRUE);
1351 if (!fast_refresh && !using_mock_io)
1352 halfdelay(10);
1353 if (ret == ERR)
1354 return NULL;
1356 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1357 err = view->search_start(view);
1358 if (err) {
1359 regfree(&view->regex);
1360 return err;
1362 view->search_started = 1;
1363 view->searching = TOG_SEARCH_FORWARD;
1364 view->search_next_done = 0;
1365 view->search_next(view);
1368 return NULL;
1371 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1372 static const struct got_error *
1373 switch_split(struct tog_view *view)
1375 const struct got_error *err = NULL;
1376 struct tog_view *v = NULL;
1378 if (view->parent)
1379 v = view->parent;
1380 else
1381 v = view;
1383 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1384 v->mode = TOG_VIEW_SPLIT_VERT;
1385 else
1386 v->mode = TOG_VIEW_SPLIT_HRZN;
1388 if (!v->child)
1389 return NULL;
1390 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1391 v->mode = TOG_VIEW_SPLIT_NONE;
1393 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1394 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1395 v->child->begin_y = v->child->resized_y;
1396 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1397 v->child->begin_x = v->child->resized_x;
1400 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1401 v->ncols = COLS;
1402 v->child->ncols = COLS;
1403 v->child->nscrolled = LINES - v->child->nlines;
1405 err = view_init_hsplit(v, v->child->begin_y);
1406 if (err)
1407 return err;
1409 v->child->mode = v->mode;
1410 v->child->nlines = v->lines - v->child->begin_y;
1411 v->focus_child = 1;
1413 err = view_fullscreen(v);
1414 if (err)
1415 return err;
1416 err = view_splitscreen(v->child);
1417 if (err)
1418 return err;
1420 if (v->mode == TOG_VIEW_SPLIT_NONE)
1421 v->mode = TOG_VIEW_SPLIT_VERT;
1422 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1423 err = offset_selection_down(v);
1424 if (err)
1425 return err;
1426 err = offset_selection_down(v->child);
1427 if (err)
1428 return err;
1429 } else {
1430 offset_selection_up(v);
1431 offset_selection_up(v->child);
1433 if (v->resize)
1434 err = v->resize(v, 0);
1435 else if (v->child->resize)
1436 err = v->child->resize(v->child, 0);
1438 return err;
1442 * Strip trailing whitespace from str starting at byte *n;
1443 * if *n < 0, use strlen(str). Return new str length in *n.
1445 static void
1446 strip_trailing_ws(char *str, int *n)
1448 size_t x = *n;
1450 if (str == NULL || *str == '\0')
1451 return;
1453 if (x < 0)
1454 x = strlen(str);
1456 while (x-- > 0 && isspace((unsigned char)str[x]))
1457 str[x] = '\0';
1459 *n = x + 1;
1463 * Extract visible substring of line y from the curses screen
1464 * and strip trailing whitespace. If vline is set, overwrite
1465 * line[vline] with '|' because the ACS_VLINE character is
1466 * written out as 'x'. Write the line to file f.
1468 static const struct got_error *
1469 view_write_line(FILE *f, int y, int vline)
1471 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1472 int r, w;
1474 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1475 if (r == ERR)
1476 return got_error_fmt(GOT_ERR_RANGE,
1477 "failed to extract line %d", y);
1480 * In some views, lines are padded with blanks to COLS width.
1481 * Strip them so we can diff without the -b flag when testing.
1483 strip_trailing_ws(line, &r);
1485 if (vline > 0)
1486 line[vline] = '|';
1488 w = fprintf(f, "%s\n", line);
1489 if (w != r + 1) /* \n */
1490 return got_ferror(f, GOT_ERR_IO);
1492 return NULL;
1496 * Capture the visible curses screen by writing each line to the
1497 * file at the path set via the TOG_SCR_DUMP environment variable.
1499 static const struct got_error *
1500 screendump(struct tog_view *view)
1502 const struct got_error *err;
1503 int i;
1505 err = got_opentemp_truncate(tog_io.sdump);
1506 if (err)
1507 return err;
1509 if ((view->child && view->child->begin_x) ||
1510 (view->parent && view->begin_x)) {
1511 int ncols = view->child ? view->ncols : view->parent->ncols;
1513 /* vertical splitscreen */
1514 for (i = 0; i < view->nlines; ++i) {
1515 err = view_write_line(tog_io.sdump, i, ncols - 1);
1516 if (err)
1517 goto done;
1519 } else {
1520 int hline = 0;
1522 /* fullscreen or horizontal splitscreen */
1523 if ((view->child && view->child->begin_y) ||
1524 (view->parent && view->begin_y)) /* hsplit */
1525 hline = view->child ?
1526 view->child->begin_y : view->begin_y;
1528 for (i = 0; i < view->lines; i++) {
1529 if (hline && i == hline - 1) {
1530 int c;
1532 /* ACS_HLINE writes out as 'q', overwrite it */
1533 for (c = 0; c < view->cols; ++c)
1534 fputc('-', tog_io.sdump);
1535 fputc('\n', tog_io.sdump);
1536 continue;
1539 err = view_write_line(tog_io.sdump, i, 0);
1540 if (err)
1541 goto done;
1545 done:
1546 return err;
1550 * Compute view->count from numeric input. Assign total to view->count and
1551 * return first non-numeric key entered.
1553 static int
1554 get_compound_key(struct tog_view *view, int c)
1556 struct tog_view *v = view;
1557 int x, n = 0;
1559 if (view_is_hsplit_top(view))
1560 v = view->child;
1561 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1562 v = view->parent;
1564 view->count = 0;
1565 cbreak(); /* block for input */
1566 nodelay(view->window, FALSE);
1567 wmove(v->window, v->nlines - 1, 0);
1568 wclrtoeol(v->window);
1569 waddch(v->window, ':');
1571 do {
1572 x = getcurx(v->window);
1573 if (x != ERR && x < view->ncols) {
1574 waddch(v->window, c);
1575 wrefresh(v->window);
1579 * Don't overflow. Max valid request should be the greatest
1580 * between the longest and total lines; cap at 10 million.
1582 if (n >= 9999999)
1583 n = 9999999;
1584 else
1585 n = n * 10 + (c - '0');
1586 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1588 if (c == 'G' || c == 'g') { /* nG key map */
1589 view->gline = view->hiline = n;
1590 n = 0;
1591 c = 0;
1594 /* Massage excessive or inapplicable values at the input handler. */
1595 view->count = n;
1597 return c;
1600 static void
1601 action_report(struct tog_view *view)
1603 struct tog_view *v = view;
1605 if (view_is_hsplit_top(view))
1606 v = view->child;
1607 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1608 v = view->parent;
1610 wmove(v->window, v->nlines - 1, 0);
1611 wclrtoeol(v->window);
1612 wprintw(v->window, ":%s", view->action);
1613 wrefresh(v->window);
1616 * Clear action status report. Only clear in blame view
1617 * once annotating is complete, otherwise it's too fast.
1619 if (view->type == TOG_VIEW_BLAME) {
1620 if (view->state.blame.blame_complete)
1621 view->action = NULL;
1622 } else
1623 view->action = NULL;
1627 * Read the next line from the test script and assign
1628 * key instruction to *ch. If at EOF, set the *done flag.
1630 static const struct got_error *
1631 tog_read_script_key(FILE *script, struct tog_view *view, int *ch, int *done)
1633 const struct got_error *err = NULL;
1634 char *line = NULL;
1635 size_t linesz = 0;
1637 if (view->count && --view->count) {
1638 *ch = view->ch;
1639 return NULL;
1640 } else
1641 *ch = -1;
1643 if (getline(&line, &linesz, script) == -1) {
1644 if (feof(script)) {
1645 *done = 1;
1646 goto done;
1647 } else {
1648 err = got_ferror(script, GOT_ERR_IO);
1649 goto done;
1653 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1654 tog_io.wait_for_ui = 1;
1655 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1656 *ch = KEY_ENTER;
1657 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1658 *ch = KEY_RIGHT;
1659 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1660 *ch = KEY_LEFT;
1661 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1662 *ch = KEY_DOWN;
1663 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1664 *ch = KEY_UP;
1665 else if (strncasecmp(line, "TAB", 3) == 0)
1666 *ch = '\t';
1667 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1668 *ch = TOG_KEY_SCRDUMP;
1669 else if (isdigit((unsigned char)*line)) {
1670 char *t = line;
1672 while (isdigit((unsigned char)*t))
1673 ++t;
1674 view->ch = *ch = *t;
1675 *t = '\0';
1676 /* ignore error, view->count is 0 if instruction is invalid */
1677 view->count = strtonum(line, 0, INT_MAX, NULL);
1678 } else
1679 *ch = *line;
1681 done:
1682 free(line);
1683 return err;
1686 static const struct got_error *
1687 view_input(struct tog_view **new, int *done, struct tog_view *view,
1688 struct tog_view_list_head *views, int fast_refresh)
1690 const struct got_error *err = NULL;
1691 struct tog_view *v;
1692 int ch, errcode;
1694 *new = NULL;
1696 if (view->action)
1697 action_report(view);
1699 /* Clear "no matches" indicator. */
1700 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1701 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1702 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1703 view->count = 0;
1706 if (view->searching && !view->search_next_done) {
1707 errcode = pthread_mutex_unlock(&tog_mutex);
1708 if (errcode)
1709 return got_error_set_errno(errcode,
1710 "pthread_mutex_unlock");
1711 sched_yield();
1712 errcode = pthread_mutex_lock(&tog_mutex);
1713 if (errcode)
1714 return got_error_set_errno(errcode,
1715 "pthread_mutex_lock");
1716 view->search_next(view);
1717 return NULL;
1720 /* Allow threads to make progress while we are waiting for input. */
1721 errcode = pthread_mutex_unlock(&tog_mutex);
1722 if (errcode)
1723 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1725 if (using_mock_io) {
1726 err = tog_read_script_key(tog_io.f, view, &ch, done);
1727 if (err) {
1728 errcode = pthread_mutex_lock(&tog_mutex);
1729 return err;
1731 } else if (view->count && --view->count) {
1732 cbreak();
1733 nodelay(view->window, TRUE);
1734 ch = wgetch(view->window);
1735 /* let C-g or backspace abort unfinished count */
1736 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1737 view->count = 0;
1738 else
1739 ch = view->ch;
1740 } else {
1741 ch = wgetch(view->window);
1742 if (ch >= '1' && ch <= '9')
1743 view->ch = ch = get_compound_key(view, ch);
1745 if (view->hiline && ch != ERR && ch != 0)
1746 view->hiline = 0; /* key pressed, clear line highlight */
1747 nodelay(view->window, TRUE);
1748 errcode = pthread_mutex_lock(&tog_mutex);
1749 if (errcode)
1750 return got_error_set_errno(errcode, "pthread_mutex_lock");
1752 if (tog_sigwinch_received || tog_sigcont_received) {
1753 tog_resizeterm();
1754 tog_sigwinch_received = 0;
1755 tog_sigcont_received = 0;
1756 TAILQ_FOREACH(v, views, entry) {
1757 err = view_resize(v);
1758 if (err)
1759 return err;
1760 err = v->input(new, v, KEY_RESIZE);
1761 if (err)
1762 return err;
1763 if (v->child) {
1764 err = view_resize(v->child);
1765 if (err)
1766 return err;
1767 err = v->child->input(new, v->child,
1768 KEY_RESIZE);
1769 if (err)
1770 return err;
1771 if (v->child->resized_x || v->child->resized_y) {
1772 err = view_resize_split(v, 0);
1773 if (err)
1774 return err;
1780 switch (ch) {
1781 case '?':
1782 case 'H':
1783 case KEY_F(1):
1784 if (view->type == TOG_VIEW_HELP)
1785 err = view->reset(view);
1786 else
1787 err = view_request_new(new, view, TOG_VIEW_HELP);
1788 break;
1789 case '\t':
1790 view->count = 0;
1791 if (view->child) {
1792 view->focussed = 0;
1793 view->child->focussed = 1;
1794 view->focus_child = 1;
1795 } else if (view->parent) {
1796 view->focussed = 0;
1797 view->parent->focussed = 1;
1798 view->parent->focus_child = 0;
1799 if (!view_is_splitscreen(view)) {
1800 if (view->parent->resize) {
1801 err = view->parent->resize(view->parent,
1802 0);
1803 if (err)
1804 return err;
1806 offset_selection_up(view->parent);
1807 err = view_fullscreen(view->parent);
1808 if (err)
1809 return err;
1812 break;
1813 case 'q':
1814 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1815 if (view->parent->resize) {
1816 /* might need more commits to fill fullscreen */
1817 err = view->parent->resize(view->parent, 0);
1818 if (err)
1819 break;
1821 offset_selection_up(view->parent);
1823 err = view->input(new, view, ch);
1824 view->dying = 1;
1825 break;
1826 case 'Q':
1827 *done = 1;
1828 break;
1829 case 'F':
1830 view->count = 0;
1831 if (view_is_parent_view(view)) {
1832 if (view->child == NULL)
1833 break;
1834 if (view_is_splitscreen(view->child)) {
1835 view->focussed = 0;
1836 view->child->focussed = 1;
1837 err = view_fullscreen(view->child);
1838 } else {
1839 err = view_splitscreen(view->child);
1840 if (!err)
1841 err = view_resize_split(view, 0);
1843 if (err)
1844 break;
1845 err = view->child->input(new, view->child,
1846 KEY_RESIZE);
1847 } else {
1848 if (view_is_splitscreen(view)) {
1849 view->parent->focussed = 0;
1850 view->focussed = 1;
1851 err = view_fullscreen(view);
1852 } else {
1853 err = view_splitscreen(view);
1854 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1855 err = view_resize(view->parent);
1856 if (!err)
1857 err = view_resize_split(view, 0);
1859 if (err)
1860 break;
1861 err = view->input(new, view, KEY_RESIZE);
1863 if (err)
1864 break;
1865 if (view->resize) {
1866 err = view->resize(view, 0);
1867 if (err)
1868 break;
1870 if (view->parent) {
1871 if (view->parent->resize) {
1872 err = view->parent->resize(view->parent, 0);
1873 if (err != NULL)
1874 break;
1876 err = offset_selection_down(view->parent);
1877 if (err != NULL)
1878 break;
1880 err = offset_selection_down(view);
1881 break;
1882 case 'S':
1883 view->count = 0;
1884 err = switch_split(view);
1885 break;
1886 case '-':
1887 err = view_resize_split(view, -1);
1888 break;
1889 case '+':
1890 err = view_resize_split(view, 1);
1891 break;
1892 case KEY_RESIZE:
1893 break;
1894 case '/':
1895 view->count = 0;
1896 if (view->search_start)
1897 view_search_start(view, fast_refresh);
1898 else
1899 err = view->input(new, view, ch);
1900 break;
1901 case 'N':
1902 case 'n':
1903 if (view->search_started && view->search_next) {
1904 view->searching = (ch == 'n' ?
1905 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1906 view->search_next_done = 0;
1907 view->search_next(view);
1908 } else
1909 err = view->input(new, view, ch);
1910 break;
1911 case 'A':
1912 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1913 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1914 view->action = "Patience diff algorithm";
1915 } else {
1916 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1917 view->action = "Myers diff algorithm";
1919 TAILQ_FOREACH(v, views, entry) {
1920 if (v->reset) {
1921 err = v->reset(v);
1922 if (err)
1923 return err;
1925 if (v->child && v->child->reset) {
1926 err = v->child->reset(v->child);
1927 if (err)
1928 return err;
1931 break;
1932 case TOG_KEY_SCRDUMP:
1933 err = screendump(view);
1934 break;
1935 default:
1936 err = view->input(new, view, ch);
1937 break;
1940 return err;
1943 static int
1944 view_needs_focus_indication(struct tog_view *view)
1946 if (view_is_parent_view(view)) {
1947 if (view->child == NULL || view->child->focussed)
1948 return 0;
1949 if (!view_is_splitscreen(view->child))
1950 return 0;
1951 } else if (!view_is_splitscreen(view))
1952 return 0;
1954 return view->focussed;
1957 static const struct got_error *
1958 tog_io_close(void)
1960 const struct got_error *err = NULL;
1962 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1963 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1964 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1965 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1966 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1967 err = got_ferror(tog_io.f, GOT_ERR_IO);
1968 if (tog_io.sdump && fclose(tog_io.sdump) == EOF && err == NULL)
1969 err = got_ferror(tog_io.sdump, GOT_ERR_IO);
1971 return err;
1974 static const struct got_error *
1975 view_loop(struct tog_view *view)
1977 const struct got_error *err = NULL;
1978 struct tog_view_list_head views;
1979 struct tog_view *new_view;
1980 char *mode;
1981 int fast_refresh = 10;
1982 int done = 0, errcode;
1984 mode = getenv("TOG_VIEW_SPLIT_MODE");
1985 if (!mode || !(*mode == 'h' || *mode == 'H'))
1986 view->mode = TOG_VIEW_SPLIT_VERT;
1987 else
1988 view->mode = TOG_VIEW_SPLIT_HRZN;
1990 errcode = pthread_mutex_lock(&tog_mutex);
1991 if (errcode)
1992 return got_error_set_errno(errcode, "pthread_mutex_lock");
1994 TAILQ_INIT(&views);
1995 TAILQ_INSERT_HEAD(&views, view, entry);
1997 view->focussed = 1;
1998 err = view->show(view);
1999 if (err)
2000 return err;
2001 update_panels();
2002 doupdate();
2003 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
2004 !tog_fatal_signal_received()) {
2005 /* Refresh fast during initialization, then become slower. */
2006 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
2007 halfdelay(10); /* switch to once per second */
2009 err = view_input(&new_view, &done, view, &views, fast_refresh);
2010 if (err)
2011 break;
2013 if (view->dying && view == TAILQ_FIRST(&views) &&
2014 TAILQ_NEXT(view, entry) == NULL)
2015 done = 1;
2016 if (done) {
2017 struct tog_view *v;
2020 * When we quit, scroll the screen up a single line
2021 * so we don't lose any information.
2023 TAILQ_FOREACH(v, &views, entry) {
2024 wmove(v->window, 0, 0);
2025 wdeleteln(v->window);
2026 wnoutrefresh(v->window);
2027 if (v->child && !view_is_fullscreen(v)) {
2028 wmove(v->child->window, 0, 0);
2029 wdeleteln(v->child->window);
2030 wnoutrefresh(v->child->window);
2033 doupdate();
2036 if (view->dying) {
2037 struct tog_view *v, *prev = NULL;
2039 if (view_is_parent_view(view))
2040 prev = TAILQ_PREV(view, tog_view_list_head,
2041 entry);
2042 else if (view->parent)
2043 prev = view->parent;
2045 if (view->parent) {
2046 view->parent->child = NULL;
2047 view->parent->focus_child = 0;
2048 /* Restore fullscreen line height. */
2049 view->parent->nlines = view->parent->lines;
2050 err = view_resize(view->parent);
2051 if (err)
2052 break;
2053 /* Make resized splits persist. */
2054 view_transfer_size(view->parent, view);
2055 } else
2056 TAILQ_REMOVE(&views, view, entry);
2058 err = view_close(view);
2059 if (err)
2060 goto done;
2062 view = NULL;
2063 TAILQ_FOREACH(v, &views, entry) {
2064 if (v->focussed)
2065 break;
2067 if (view == NULL && new_view == NULL) {
2068 /* No view has focus. Try to pick one. */
2069 if (prev)
2070 view = prev;
2071 else if (!TAILQ_EMPTY(&views)) {
2072 view = TAILQ_LAST(&views,
2073 tog_view_list_head);
2075 if (view) {
2076 if (view->focus_child) {
2077 view->child->focussed = 1;
2078 view = view->child;
2079 } else
2080 view->focussed = 1;
2084 if (new_view) {
2085 struct tog_view *v, *t;
2086 /* Only allow one parent view per type. */
2087 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2088 if (v->type != new_view->type)
2089 continue;
2090 TAILQ_REMOVE(&views, v, entry);
2091 err = view_close(v);
2092 if (err)
2093 goto done;
2094 break;
2096 TAILQ_INSERT_TAIL(&views, new_view, entry);
2097 view = new_view;
2099 if (view && !done) {
2100 if (view_is_parent_view(view)) {
2101 if (view->child && view->child->focussed)
2102 view = view->child;
2103 } else {
2104 if (view->parent && view->parent->focussed)
2105 view = view->parent;
2107 show_panel(view->panel);
2108 if (view->child && view_is_splitscreen(view->child))
2109 show_panel(view->child->panel);
2110 if (view->parent && view_is_splitscreen(view)) {
2111 err = view->parent->show(view->parent);
2112 if (err)
2113 goto done;
2115 err = view->show(view);
2116 if (err)
2117 goto done;
2118 if (view->child) {
2119 err = view->child->show(view->child);
2120 if (err)
2121 goto done;
2123 update_panels();
2124 doupdate();
2127 done:
2128 while (!TAILQ_EMPTY(&views)) {
2129 const struct got_error *close_err;
2130 view = TAILQ_FIRST(&views);
2131 TAILQ_REMOVE(&views, view, entry);
2132 close_err = view_close(view);
2133 if (close_err && err == NULL)
2134 err = close_err;
2137 errcode = pthread_mutex_unlock(&tog_mutex);
2138 if (errcode && err == NULL)
2139 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2141 return err;
2144 __dead static void
2145 usage_log(void)
2147 endwin();
2148 fprintf(stderr,
2149 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2150 getprogname());
2151 exit(1);
2154 /* Create newly allocated wide-character string equivalent to a byte string. */
2155 static const struct got_error *
2156 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2158 char *vis = NULL;
2159 const struct got_error *err = NULL;
2161 *ws = NULL;
2162 *wlen = mbstowcs(NULL, s, 0);
2163 if (*wlen == (size_t)-1) {
2164 int vislen;
2165 if (errno != EILSEQ)
2166 return got_error_from_errno("mbstowcs");
2168 /* byte string invalid in current encoding; try to "fix" it */
2169 err = got_mbsavis(&vis, &vislen, s);
2170 if (err)
2171 return err;
2172 *wlen = mbstowcs(NULL, vis, 0);
2173 if (*wlen == (size_t)-1) {
2174 err = got_error_from_errno("mbstowcs"); /* give up */
2175 goto done;
2179 *ws = calloc(*wlen + 1, sizeof(**ws));
2180 if (*ws == NULL) {
2181 err = got_error_from_errno("calloc");
2182 goto done;
2185 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2186 err = got_error_from_errno("mbstowcs");
2187 done:
2188 free(vis);
2189 if (err) {
2190 free(*ws);
2191 *ws = NULL;
2192 *wlen = 0;
2194 return err;
2197 static const struct got_error *
2198 expand_tab(char **ptr, const char *src)
2200 char *dst;
2201 size_t len, n, idx = 0, sz = 0;
2203 *ptr = NULL;
2204 n = len = strlen(src);
2205 dst = malloc(n + 1);
2206 if (dst == NULL)
2207 return got_error_from_errno("malloc");
2209 while (idx < len && src[idx]) {
2210 const char c = src[idx];
2212 if (c == '\t') {
2213 size_t nb = TABSIZE - sz % TABSIZE;
2214 char *p;
2216 p = realloc(dst, n + nb);
2217 if (p == NULL) {
2218 free(dst);
2219 return got_error_from_errno("realloc");
2222 dst = p;
2223 n += nb;
2224 memset(dst + sz, ' ', nb);
2225 sz += nb;
2226 } else
2227 dst[sz++] = src[idx];
2228 ++idx;
2231 dst[sz] = '\0';
2232 *ptr = dst;
2233 return NULL;
2237 * Advance at most n columns from wline starting at offset off.
2238 * Return the index to the first character after the span operation.
2239 * Return the combined column width of all spanned wide characters in
2240 * *rcol.
2242 static int
2243 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2245 int width, i, cols = 0;
2247 if (n == 0) {
2248 *rcol = cols;
2249 return off;
2252 for (i = off; wline[i] != L'\0'; ++i) {
2253 if (wline[i] == L'\t')
2254 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2255 else
2256 width = wcwidth(wline[i]);
2258 if (width == -1) {
2259 width = 1;
2260 wline[i] = L'.';
2263 if (cols + width > n)
2264 break;
2265 cols += width;
2268 *rcol = cols;
2269 return i;
2273 * Format a line for display, ensuring that it won't overflow a width limit.
2274 * With scrolling, the width returned refers to the scrolled version of the
2275 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2277 static const struct got_error *
2278 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2279 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2281 const struct got_error *err = NULL;
2282 int cols;
2283 wchar_t *wline = NULL;
2284 char *exstr = NULL;
2285 size_t wlen;
2286 int i, scrollx;
2288 *wlinep = NULL;
2289 *widthp = 0;
2291 if (expand) {
2292 err = expand_tab(&exstr, line);
2293 if (err)
2294 return err;
2297 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2298 free(exstr);
2299 if (err)
2300 return err;
2302 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2304 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2305 wline[wlen - 1] = L'\0';
2306 wlen--;
2308 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2309 wline[wlen - 1] = L'\0';
2310 wlen--;
2313 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2314 wline[i] = L'\0';
2316 if (widthp)
2317 *widthp = cols;
2318 if (scrollxp)
2319 *scrollxp = scrollx;
2320 if (err)
2321 free(wline);
2322 else
2323 *wlinep = wline;
2324 return err;
2327 static const struct got_error*
2328 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2329 struct got_object_id *id, struct got_repository *repo)
2331 static const struct got_error *err = NULL;
2332 struct got_reflist_entry *re;
2333 char *s;
2334 const char *name;
2336 *refs_str = NULL;
2338 if (refs == NULL)
2339 return NULL;
2341 TAILQ_FOREACH(re, refs, entry) {
2342 struct got_tag_object *tag = NULL;
2343 struct got_object_id *ref_id;
2344 int cmp;
2346 name = got_ref_get_name(re->ref);
2347 if (strcmp(name, GOT_REF_HEAD) == 0)
2348 continue;
2349 if (strncmp(name, "refs/", 5) == 0)
2350 name += 5;
2351 if (strncmp(name, "got/", 4) == 0)
2352 continue;
2353 if (strncmp(name, "heads/", 6) == 0)
2354 name += 6;
2355 if (strncmp(name, "remotes/", 8) == 0) {
2356 name += 8;
2357 s = strstr(name, "/" GOT_REF_HEAD);
2358 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
2359 continue;
2361 err = got_ref_resolve(&ref_id, repo, re->ref);
2362 if (err)
2363 break;
2364 if (strncmp(name, "tags/", 5) == 0) {
2365 err = got_object_open_as_tag(&tag, repo, ref_id);
2366 if (err) {
2367 if (err->code != GOT_ERR_OBJ_TYPE) {
2368 free(ref_id);
2369 break;
2371 /* Ref points at something other than a tag. */
2372 err = NULL;
2373 tag = NULL;
2376 cmp = got_object_id_cmp(tag ?
2377 got_object_tag_get_object_id(tag) : ref_id, id);
2378 free(ref_id);
2379 if (tag)
2380 got_object_tag_close(tag);
2381 if (cmp != 0)
2382 continue;
2383 s = *refs_str;
2384 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2385 s ? ", " : "", name) == -1) {
2386 err = got_error_from_errno("asprintf");
2387 free(s);
2388 *refs_str = NULL;
2389 break;
2391 free(s);
2394 return err;
2397 static const struct got_error *
2398 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2399 int col_tab_align)
2401 char *smallerthan;
2403 smallerthan = strchr(author, '<');
2404 if (smallerthan && smallerthan[1] != '\0')
2405 author = smallerthan + 1;
2406 author[strcspn(author, "@>")] = '\0';
2407 return format_line(wauthor, author_width, NULL, author, 0, limit,
2408 col_tab_align, 0);
2411 static const struct got_error *
2412 draw_commit(struct tog_view *view, struct commit_queue_entry *entry,
2413 const size_t date_display_cols, int author_display_cols)
2415 struct tog_log_view_state *s = &view->state.log;
2416 const struct got_error *err = NULL;
2417 struct got_commit_object *commit = entry->commit;
2418 struct got_object_id *id = entry->id;
2419 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2420 char *refs_str = NULL;
2421 char *logmsg0 = NULL, *logmsg = NULL;
2422 char *author = NULL;
2423 wchar_t *wrefstr = NULL, *wlogmsg = NULL, *wauthor = NULL;
2424 int author_width, refstr_width, logmsg_width;
2425 char *newline, *line = NULL;
2426 int col, limit, scrollx, logmsg_x;
2427 const int avail = view->ncols, marker_column = author_display_cols + 1;
2428 struct tm tm;
2429 time_t committer_time;
2430 struct tog_color *tc;
2431 struct got_reflist_head *refs;
2433 if (tog_base_commit.id != NULL && tog_base_commit.idx == -1 &&
2434 got_object_id_cmp(id, tog_base_commit.id) == 0)
2435 tog_base_commit.idx = entry->idx;
2437 committer_time = got_object_commit_get_committer_time(commit);
2438 if (gmtime_r(&committer_time, &tm) == NULL)
2439 return got_error_from_errno("gmtime_r");
2440 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2441 return got_error(GOT_ERR_NO_SPACE);
2443 if (avail <= date_display_cols)
2444 limit = MIN(sizeof(datebuf) - 1, avail);
2445 else
2446 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2447 tc = get_color(&s->colors, TOG_COLOR_DATE);
2448 if (tc)
2449 wattr_on(view->window,
2450 COLOR_PAIR(tc->colorpair), NULL);
2451 waddnstr(view->window, datebuf, limit);
2452 if (tc)
2453 wattr_off(view->window,
2454 COLOR_PAIR(tc->colorpair), NULL);
2455 col = limit;
2456 if (col > avail)
2457 goto done;
2459 if (avail >= 120) {
2460 char *id_str;
2461 err = got_object_id_str(&id_str, id);
2462 if (err)
2463 goto done;
2464 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2465 if (tc)
2466 wattr_on(view->window,
2467 COLOR_PAIR(tc->colorpair), NULL);
2468 wprintw(view->window, "%.8s ", id_str);
2469 if (tc)
2470 wattr_off(view->window,
2471 COLOR_PAIR(tc->colorpair), NULL);
2472 free(id_str);
2473 col += 9;
2474 if (col > avail)
2475 goto done;
2478 if (s->use_committer)
2479 author = strdup(got_object_commit_get_committer(commit));
2480 else
2481 author = strdup(got_object_commit_get_author(commit));
2482 if (author == NULL) {
2483 err = got_error_from_errno("strdup");
2484 goto done;
2486 err = format_author(&wauthor, &author_width, author, avail - col, col);
2487 if (err)
2488 goto done;
2489 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2490 if (tc)
2491 wattr_on(view->window,
2492 COLOR_PAIR(tc->colorpair), NULL);
2493 waddwstr(view->window, wauthor);
2494 col += author_width;
2495 while (col < avail && author_width < author_display_cols + 2) {
2496 if (tog_base_commit.marker != GOT_WORKTREE_STATE_UNKNOWN &&
2497 author_width == marker_column &&
2498 entry->idx == tog_base_commit.idx) {
2499 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2500 if (tc)
2501 wattr_on(view->window,
2502 COLOR_PAIR(tc->colorpair), NULL);
2503 waddch(view->window, tog_base_commit.marker);
2504 if (tc)
2505 wattr_off(view->window,
2506 COLOR_PAIR(tc->colorpair), NULL);
2507 } else
2508 waddch(view->window, ' ');
2509 col++;
2510 author_width++;
2512 if (tc)
2513 wattr_off(view->window,
2514 COLOR_PAIR(tc->colorpair), NULL);
2515 if (col > avail)
2516 goto done;
2518 err = got_object_commit_get_logmsg(&logmsg0, commit);
2519 if (err)
2520 goto done;
2521 logmsg = logmsg0;
2522 while (*logmsg == '\n')
2523 logmsg++;
2524 newline = strchr(logmsg, '\n');
2525 if (newline)
2526 *newline = '\0';
2528 limit = avail - col;
2529 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2530 limit--; /* for the border */
2532 /* Prepend reference labels to log message if possible .*/
2533 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, id);
2534 err = build_refs_str(&refs_str, refs, id, s->repo);
2535 if (err)
2536 goto done;
2537 if (refs_str) {
2538 char *rs;
2540 if (asprintf(&rs, "[%s]", refs_str) == -1) {
2541 err = got_error_from_errno("asprintf");
2542 goto done;
2544 err = format_line(&wrefstr, &refstr_width,
2545 &scrollx, rs, view->x, limit, col, 1);
2546 free(rs);
2547 if (err)
2548 goto done;
2549 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2550 if (tc)
2551 wattr_on(view->window,
2552 COLOR_PAIR(tc->colorpair), NULL);
2553 waddwstr(view->window, &wrefstr[scrollx]);
2554 if (tc)
2555 wattr_off(view->window,
2556 COLOR_PAIR(tc->colorpair), NULL);
2557 col += MAX(refstr_width, 0);
2558 if (col > avail)
2559 goto done;
2561 if (col < avail) {
2562 waddch(view->window, ' ');
2563 col++;
2566 if (refstr_width > 0)
2567 logmsg_x = 0;
2568 else {
2569 int unscrolled_refstr_width;
2570 size_t len = wcslen(wrefstr);
2573 * No need to check for -1 return value here since
2574 * unprintables have been replaced by span_wline().
2576 unscrolled_refstr_width = wcswidth(wrefstr, len);
2577 unscrolled_refstr_width += 1; /* trailing space */
2578 logmsg_x = view->x - unscrolled_refstr_width;
2581 limit = avail - col;
2582 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2583 limit--; /* for the border */
2584 } else
2585 logmsg_x = view->x;
2587 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, logmsg_x,
2588 limit, col, 1);
2589 if (err)
2590 goto done;
2591 waddwstr(view->window, &wlogmsg[scrollx]);
2592 col += MAX(logmsg_width, 0);
2593 while (col < avail) {
2594 waddch(view->window, ' ');
2595 col++;
2597 done:
2598 free(logmsg0);
2599 free(wlogmsg);
2600 free(wrefstr);
2601 free(refs_str);
2602 free(author);
2603 free(wauthor);
2604 free(line);
2605 return err;
2608 static struct commit_queue_entry *
2609 alloc_commit_queue_entry(struct got_commit_object *commit,
2610 struct got_object_id *id)
2612 struct commit_queue_entry *entry;
2613 struct got_object_id *dup;
2615 entry = calloc(1, sizeof(*entry));
2616 if (entry == NULL)
2617 return NULL;
2619 dup = got_object_id_dup(id);
2620 if (dup == NULL) {
2621 free(entry);
2622 return NULL;
2625 entry->id = dup;
2626 entry->commit = commit;
2627 return entry;
2630 static void
2631 pop_commit(struct commit_queue *commits)
2633 struct commit_queue_entry *entry;
2635 entry = TAILQ_FIRST(&commits->head);
2636 TAILQ_REMOVE(&commits->head, entry, entry);
2637 got_object_commit_close(entry->commit);
2638 commits->ncommits--;
2639 free(entry->id);
2640 free(entry);
2643 static void
2644 free_commits(struct commit_queue *commits)
2646 while (!TAILQ_EMPTY(&commits->head))
2647 pop_commit(commits);
2650 static const struct got_error *
2651 match_commit(int *have_match, struct got_object_id *id,
2652 struct got_commit_object *commit, regex_t *regex)
2654 const struct got_error *err = NULL;
2655 regmatch_t regmatch;
2656 char *id_str = NULL, *logmsg = NULL;
2658 *have_match = 0;
2660 err = got_object_id_str(&id_str, id);
2661 if (err)
2662 return err;
2664 err = got_object_commit_get_logmsg(&logmsg, commit);
2665 if (err)
2666 goto done;
2668 if (regexec(regex, got_object_commit_get_author(commit), 1,
2669 &regmatch, 0) == 0 ||
2670 regexec(regex, got_object_commit_get_committer(commit), 1,
2671 &regmatch, 0) == 0 ||
2672 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2673 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2674 *have_match = 1;
2675 done:
2676 free(id_str);
2677 free(logmsg);
2678 return err;
2681 static const struct got_error *
2682 queue_commits(struct tog_log_thread_args *a)
2684 const struct got_error *err = NULL;
2687 * We keep all commits open throughout the lifetime of the log
2688 * view in order to avoid having to re-fetch commits from disk
2689 * while updating the display.
2691 do {
2692 struct got_object_id id;
2693 struct got_commit_object *commit;
2694 struct commit_queue_entry *entry;
2695 int limit_match = 0;
2696 int errcode;
2698 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2699 NULL, NULL);
2700 if (err)
2701 break;
2703 err = got_object_open_as_commit(&commit, a->repo, &id);
2704 if (err)
2705 break;
2706 entry = alloc_commit_queue_entry(commit, &id);
2707 if (entry == NULL) {
2708 err = got_error_from_errno("alloc_commit_queue_entry");
2709 break;
2712 errcode = pthread_mutex_lock(&tog_mutex);
2713 if (errcode) {
2714 err = got_error_set_errno(errcode,
2715 "pthread_mutex_lock");
2716 break;
2719 entry->idx = a->real_commits->ncommits;
2720 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2721 a->real_commits->ncommits++;
2723 if (*a->limiting) {
2724 err = match_commit(&limit_match, &id, commit,
2725 a->limit_regex);
2726 if (err)
2727 break;
2729 if (limit_match) {
2730 struct commit_queue_entry *matched;
2732 matched = alloc_commit_queue_entry(
2733 entry->commit, entry->id);
2734 if (matched == NULL) {
2735 err = got_error_from_errno(
2736 "alloc_commit_queue_entry");
2737 break;
2739 matched->commit = entry->commit;
2740 got_object_commit_retain(entry->commit);
2742 matched->idx = a->limit_commits->ncommits;
2743 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2744 matched, entry);
2745 a->limit_commits->ncommits++;
2749 * This is how we signal log_thread() that we
2750 * have found a match, and that it should be
2751 * counted as a new entry for the view.
2753 a->limit_match = limit_match;
2756 if (*a->searching == TOG_SEARCH_FORWARD &&
2757 !*a->search_next_done) {
2758 int have_match;
2759 err = match_commit(&have_match, &id, commit, a->regex);
2760 if (err)
2761 break;
2763 if (*a->limiting) {
2764 if (limit_match && have_match)
2765 *a->search_next_done =
2766 TOG_SEARCH_HAVE_MORE;
2767 } else if (have_match)
2768 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2771 errcode = pthread_mutex_unlock(&tog_mutex);
2772 if (errcode && err == NULL)
2773 err = got_error_set_errno(errcode,
2774 "pthread_mutex_unlock");
2775 if (err)
2776 break;
2777 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2779 return err;
2782 static void
2783 select_commit(struct tog_log_view_state *s)
2785 struct commit_queue_entry *entry;
2786 int ncommits = 0;
2788 entry = s->first_displayed_entry;
2789 while (entry) {
2790 if (ncommits == s->selected) {
2791 s->selected_entry = entry;
2792 break;
2794 entry = TAILQ_NEXT(entry, entry);
2795 ncommits++;
2799 static const struct got_error *
2800 draw_commits(struct tog_view *view)
2802 const struct got_error *err = NULL;
2803 struct tog_log_view_state *s = &view->state.log;
2804 struct commit_queue_entry *entry = s->selected_entry;
2805 int limit = view->nlines;
2806 int width;
2807 int ncommits, author_cols = 4, refstr_cols;
2808 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2809 char *refs_str = NULL;
2810 wchar_t *wline;
2811 struct tog_color *tc;
2812 static const size_t date_display_cols = 12;
2813 struct got_reflist_head *refs;
2815 if (view_is_hsplit_top(view))
2816 --limit; /* account for border */
2818 if (s->selected_entry &&
2819 !(view->searching && view->search_next_done == 0)) {
2820 err = got_object_id_str(&id_str, s->selected_entry->id);
2821 if (err)
2822 return err;
2823 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2824 s->selected_entry->id);
2825 err = build_refs_str(&refs_str, refs, s->selected_entry->id,
2826 s->repo);
2827 if (err)
2828 goto done;
2831 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2832 halfdelay(10); /* disable fast refresh */
2834 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2835 if (asprintf(&ncommits_str, " [%d/%d] %s",
2836 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2837 (view->searching && !view->search_next_done) ?
2838 "searching..." : "loading...") == -1) {
2839 err = got_error_from_errno("asprintf");
2840 goto done;
2842 } else {
2843 const char *search_str = NULL;
2844 const char *limit_str = NULL;
2846 if (view->searching) {
2847 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2848 search_str = "no more matches";
2849 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2850 search_str = "no matches found";
2851 else if (!view->search_next_done)
2852 search_str = "searching...";
2855 if (s->limit_view && s->commits->ncommits == 0)
2856 limit_str = "no matches found";
2858 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2859 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2860 search_str ? search_str : (refs_str ? refs_str : ""),
2861 limit_str ? limit_str : "") == -1) {
2862 err = got_error_from_errno("asprintf");
2863 goto done;
2867 free(refs_str);
2868 refs_str = NULL;
2870 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2871 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2872 "........................................",
2873 s->in_repo_path, ncommits_str) == -1) {
2874 err = got_error_from_errno("asprintf");
2875 header = NULL;
2876 goto done;
2878 } else if (asprintf(&header, "commit %s%s",
2879 id_str ? id_str : "........................................",
2880 ncommits_str) == -1) {
2881 err = got_error_from_errno("asprintf");
2882 header = NULL;
2883 goto done;
2885 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2886 if (err)
2887 goto done;
2889 werase(view->window);
2891 if (view_needs_focus_indication(view))
2892 wstandout(view->window);
2893 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2894 if (tc)
2895 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2896 waddwstr(view->window, wline);
2897 while (width < view->ncols) {
2898 waddch(view->window, ' ');
2899 width++;
2901 if (tc)
2902 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2903 if (view_needs_focus_indication(view))
2904 wstandend(view->window);
2905 free(wline);
2906 if (limit <= 1)
2907 goto done;
2909 /* Grow author column size if necessary, and set view->maxx. */
2910 entry = s->first_displayed_entry;
2911 ncommits = 0;
2912 view->maxx = 0;
2913 while (entry) {
2914 struct got_commit_object *c = entry->commit;
2915 char *author, *eol, *msg, *msg0;
2916 wchar_t *wauthor, *wmsg;
2917 int width;
2918 if (ncommits >= limit - 1)
2919 break;
2920 if (s->use_committer)
2921 author = strdup(got_object_commit_get_committer(c));
2922 else
2923 author = strdup(got_object_commit_get_author(c));
2924 if (author == NULL) {
2925 err = got_error_from_errno("strdup");
2926 goto done;
2928 err = format_author(&wauthor, &width, author, COLS,
2929 date_display_cols);
2930 if (author_cols < width)
2931 author_cols = width;
2932 free(wauthor);
2933 free(author);
2934 if (err)
2935 goto done;
2936 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2937 entry->id);
2938 err = build_refs_str(&refs_str, refs, entry->id, s->repo);
2939 if (err)
2940 goto done;
2941 if (refs_str) {
2942 wchar_t *ws;
2943 err = format_line(&ws, &width, NULL, refs_str,
2944 0, INT_MAX, date_display_cols + author_cols, 0);
2945 free(ws);
2946 free(refs_str);
2947 refs_str = NULL;
2948 if (err)
2949 goto done;
2950 refstr_cols = width + 3; /* account for [ ] + space */
2951 } else
2952 refstr_cols = 0;
2953 err = got_object_commit_get_logmsg(&msg0, c);
2954 if (err)
2955 goto done;
2956 msg = msg0;
2957 while (*msg == '\n')
2958 ++msg;
2959 if ((eol = strchr(msg, '\n')))
2960 *eol = '\0';
2961 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2962 date_display_cols + author_cols + refstr_cols, 0);
2963 if (err)
2964 goto done;
2965 view->maxx = MAX(view->maxx, width + refstr_cols);
2966 free(msg0);
2967 free(wmsg);
2968 ncommits++;
2969 entry = TAILQ_NEXT(entry, entry);
2972 entry = s->first_displayed_entry;
2973 s->last_displayed_entry = s->first_displayed_entry;
2974 ncommits = 0;
2975 while (entry) {
2976 if (ncommits >= limit - 1)
2977 break;
2978 if (ncommits == s->selected)
2979 wstandout(view->window);
2980 err = draw_commit(view, entry, date_display_cols, author_cols);
2981 if (ncommits == s->selected)
2982 wstandend(view->window);
2983 if (err)
2984 goto done;
2985 ncommits++;
2986 s->last_displayed_entry = entry;
2987 entry = TAILQ_NEXT(entry, entry);
2990 view_border(view);
2991 done:
2992 free(id_str);
2993 free(refs_str);
2994 free(ncommits_str);
2995 free(header);
2996 return err;
2999 static void
3000 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
3002 struct commit_queue_entry *entry;
3003 int nscrolled = 0;
3005 entry = TAILQ_FIRST(&s->commits->head);
3006 if (s->first_displayed_entry == entry)
3007 return;
3009 entry = s->first_displayed_entry;
3010 while (entry && nscrolled < maxscroll) {
3011 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3012 if (entry) {
3013 s->first_displayed_entry = entry;
3014 nscrolled++;
3019 static const struct got_error *
3020 trigger_log_thread(struct tog_view *view, int wait)
3022 struct tog_log_thread_args *ta = &view->state.log.thread_args;
3023 int errcode;
3025 if (!using_mock_io)
3026 halfdelay(1); /* fast refresh while loading commits */
3028 while (!ta->log_complete && !tog_thread_error &&
3029 (ta->commits_needed > 0 || ta->load_all)) {
3030 /* Wake the log thread. */
3031 errcode = pthread_cond_signal(&ta->need_commits);
3032 if (errcode)
3033 return got_error_set_errno(errcode,
3034 "pthread_cond_signal");
3037 * The mutex will be released while the view loop waits
3038 * in wgetch(), at which time the log thread will run.
3040 if (!wait)
3041 break;
3043 /* Display progress update in log view. */
3044 show_log_view(view);
3045 update_panels();
3046 doupdate();
3048 /* Wait right here while next commit is being loaded. */
3049 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
3050 if (errcode)
3051 return got_error_set_errno(errcode,
3052 "pthread_cond_wait");
3054 /* Display progress update in log view. */
3055 show_log_view(view);
3056 update_panels();
3057 doupdate();
3060 return NULL;
3063 static const struct got_error *
3064 request_log_commits(struct tog_view *view)
3066 struct tog_log_view_state *state = &view->state.log;
3067 const struct got_error *err = NULL;
3069 if (state->thread_args.log_complete)
3070 return NULL;
3072 state->thread_args.commits_needed += view->nscrolled;
3073 err = trigger_log_thread(view, 1);
3074 view->nscrolled = 0;
3076 return err;
3079 static const struct got_error *
3080 log_scroll_down(struct tog_view *view, int maxscroll)
3082 struct tog_log_view_state *s = &view->state.log;
3083 const struct got_error *err = NULL;
3084 struct commit_queue_entry *pentry;
3085 int nscrolled = 0, ncommits_needed;
3087 if (s->last_displayed_entry == NULL)
3088 return NULL;
3090 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
3091 if (s->commits->ncommits < ncommits_needed &&
3092 !s->thread_args.log_complete) {
3094 * Ask the log thread for required amount of commits.
3096 s->thread_args.commits_needed +=
3097 ncommits_needed - s->commits->ncommits;
3098 err = trigger_log_thread(view, 1);
3099 if (err)
3100 return err;
3103 do {
3104 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
3105 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3106 break;
3108 s->last_displayed_entry = pentry ?
3109 pentry : s->last_displayed_entry;
3111 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3112 if (pentry == NULL)
3113 break;
3114 s->first_displayed_entry = pentry;
3115 } while (++nscrolled < maxscroll);
3117 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3118 view->nscrolled += nscrolled;
3119 else
3120 view->nscrolled = 0;
3122 return err;
3125 static const struct got_error *
3126 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3127 struct got_commit_object *commit, struct got_object_id *commit_id,
3128 struct tog_view *log_view, struct got_repository *repo)
3130 const struct got_error *err;
3131 struct got_object_qid *parent_id;
3132 struct tog_view *diff_view;
3134 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3135 if (diff_view == NULL)
3136 return got_error_from_errno("view_open");
3138 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3139 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3140 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3141 if (err == NULL)
3142 *new_view = diff_view;
3143 return err;
3146 static const struct got_error *
3147 tree_view_visit_subtree(struct tog_tree_view_state *s,
3148 struct got_tree_object *subtree)
3150 struct tog_parent_tree *parent;
3152 parent = calloc(1, sizeof(*parent));
3153 if (parent == NULL)
3154 return got_error_from_errno("calloc");
3156 parent->tree = s->tree;
3157 parent->first_displayed_entry = s->first_displayed_entry;
3158 parent->selected_entry = s->selected_entry;
3159 parent->selected = s->selected;
3160 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3161 s->tree = subtree;
3162 s->selected = 0;
3163 s->first_displayed_entry = NULL;
3164 return NULL;
3167 static const struct got_error *
3168 tree_view_walk_path(struct tog_tree_view_state *s,
3169 struct got_commit_object *commit, const char *path)
3171 const struct got_error *err = NULL;
3172 struct got_tree_object *tree = NULL;
3173 const char *p;
3174 char *slash, *subpath = NULL;
3176 /* Walk the path and open corresponding tree objects. */
3177 p = path;
3178 while (*p) {
3179 struct got_tree_entry *te;
3180 struct got_object_id *tree_id;
3181 char *te_name;
3183 while (p[0] == '/')
3184 p++;
3186 /* Ensure the correct subtree entry is selected. */
3187 slash = strchr(p, '/');
3188 if (slash == NULL)
3189 te_name = strdup(p);
3190 else
3191 te_name = strndup(p, slash - p);
3192 if (te_name == NULL) {
3193 err = got_error_from_errno("strndup");
3194 break;
3196 te = got_object_tree_find_entry(s->tree, te_name);
3197 if (te == NULL) {
3198 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3199 free(te_name);
3200 break;
3202 free(te_name);
3203 s->first_displayed_entry = s->selected_entry = te;
3205 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3206 break; /* jump to this file's entry */
3208 slash = strchr(p, '/');
3209 if (slash)
3210 subpath = strndup(path, slash - path);
3211 else
3212 subpath = strdup(path);
3213 if (subpath == NULL) {
3214 err = got_error_from_errno("strdup");
3215 break;
3218 err = got_object_id_by_path(&tree_id, s->repo, commit,
3219 subpath);
3220 if (err)
3221 break;
3223 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3224 free(tree_id);
3225 if (err)
3226 break;
3228 err = tree_view_visit_subtree(s, tree);
3229 if (err) {
3230 got_object_tree_close(tree);
3231 break;
3233 if (slash == NULL)
3234 break;
3235 free(subpath);
3236 subpath = NULL;
3237 p = slash;
3240 free(subpath);
3241 return err;
3244 static const struct got_error *
3245 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3246 struct commit_queue_entry *entry, const char *path,
3247 const char *head_ref_name, struct got_repository *repo)
3249 const struct got_error *err = NULL;
3250 struct tog_tree_view_state *s;
3251 struct tog_view *tree_view;
3253 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3254 if (tree_view == NULL)
3255 return got_error_from_errno("view_open");
3257 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3258 if (err)
3259 return err;
3260 s = &tree_view->state.tree;
3262 *new_view = tree_view;
3264 if (got_path_is_root_dir(path))
3265 return NULL;
3267 return tree_view_walk_path(s, entry->commit, path);
3270 static const struct got_error *
3271 block_signals_used_by_main_thread(void)
3273 sigset_t sigset;
3274 int errcode;
3276 if (sigemptyset(&sigset) == -1)
3277 return got_error_from_errno("sigemptyset");
3279 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3280 if (sigaddset(&sigset, SIGWINCH) == -1)
3281 return got_error_from_errno("sigaddset");
3282 if (sigaddset(&sigset, SIGCONT) == -1)
3283 return got_error_from_errno("sigaddset");
3284 if (sigaddset(&sigset, SIGINT) == -1)
3285 return got_error_from_errno("sigaddset");
3286 if (sigaddset(&sigset, SIGTERM) == -1)
3287 return got_error_from_errno("sigaddset");
3289 /* ncurses handles SIGTSTP */
3290 if (sigaddset(&sigset, SIGTSTP) == -1)
3291 return got_error_from_errno("sigaddset");
3293 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3294 if (errcode)
3295 return got_error_set_errno(errcode, "pthread_sigmask");
3297 return NULL;
3300 static void *
3301 log_thread(void *arg)
3303 const struct got_error *err = NULL;
3304 int errcode = 0;
3305 struct tog_log_thread_args *a = arg;
3306 int done = 0;
3309 * Sync startup with main thread such that we begin our
3310 * work once view_input() has released the mutex.
3312 errcode = pthread_mutex_lock(&tog_mutex);
3313 if (errcode) {
3314 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3315 return (void *)err;
3318 err = block_signals_used_by_main_thread();
3319 if (err) {
3320 pthread_mutex_unlock(&tog_mutex);
3321 goto done;
3324 while (!done && !err && !tog_fatal_signal_received()) {
3325 errcode = pthread_mutex_unlock(&tog_mutex);
3326 if (errcode) {
3327 err = got_error_set_errno(errcode,
3328 "pthread_mutex_unlock");
3329 goto done;
3331 err = queue_commits(a);
3332 if (err) {
3333 if (err->code != GOT_ERR_ITER_COMPLETED)
3334 goto done;
3335 err = NULL;
3336 done = 1;
3337 a->commits_needed = 0;
3338 } else if (a->commits_needed > 0 && !a->load_all) {
3339 if (*a->limiting) {
3340 if (a->limit_match)
3341 a->commits_needed--;
3342 } else
3343 a->commits_needed--;
3346 errcode = pthread_mutex_lock(&tog_mutex);
3347 if (errcode) {
3348 err = got_error_set_errno(errcode,
3349 "pthread_mutex_lock");
3350 goto done;
3351 } else if (*a->quit)
3352 done = 1;
3353 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3354 *a->first_displayed_entry =
3355 TAILQ_FIRST(&a->limit_commits->head);
3356 *a->selected_entry = *a->first_displayed_entry;
3357 } else if (*a->first_displayed_entry == NULL) {
3358 *a->first_displayed_entry =
3359 TAILQ_FIRST(&a->real_commits->head);
3360 *a->selected_entry = *a->first_displayed_entry;
3363 errcode = pthread_cond_signal(&a->commit_loaded);
3364 if (errcode) {
3365 err = got_error_set_errno(errcode,
3366 "pthread_cond_signal");
3367 pthread_mutex_unlock(&tog_mutex);
3368 goto done;
3371 if (a->commits_needed == 0 &&
3372 a->need_commit_marker && a->worktree) {
3373 errcode = pthread_mutex_unlock(&tog_mutex);
3374 if (errcode) {
3375 err = got_error_set_errno(errcode,
3376 "pthread_mutex_unlock");
3377 goto done;
3379 err = got_worktree_get_state(&tog_base_commit.marker,
3380 a->repo, a->worktree, NULL, NULL);
3381 if (err)
3382 goto done;
3383 errcode = pthread_mutex_lock(&tog_mutex);
3384 if (errcode) {
3385 err = got_error_set_errno(errcode,
3386 "pthread_mutex_lock");
3387 goto done;
3389 a->need_commit_marker = 0;
3391 * The main thread did not close this
3392 * work tree yet. Close it now.
3394 got_worktree_close(a->worktree);
3395 a->worktree = NULL;
3397 if (*a->quit)
3398 done = 1;
3401 if (done)
3402 a->commits_needed = 0;
3403 else {
3404 if (a->commits_needed == 0 && !a->load_all) {
3405 if (tog_io.wait_for_ui) {
3406 errcode = pthread_cond_signal(
3407 &a->log_loaded);
3408 if (errcode && err == NULL)
3409 err = got_error_set_errno(
3410 errcode,
3411 "pthread_cond_signal");
3414 errcode = pthread_cond_wait(&a->need_commits,
3415 &tog_mutex);
3416 if (errcode) {
3417 err = got_error_set_errno(errcode,
3418 "pthread_cond_wait");
3419 pthread_mutex_unlock(&tog_mutex);
3420 goto done;
3422 if (*a->quit)
3423 done = 1;
3427 a->log_complete = 1;
3428 if (tog_io.wait_for_ui) {
3429 errcode = pthread_cond_signal(&a->log_loaded);
3430 if (errcode && err == NULL)
3431 err = got_error_set_errno(errcode,
3432 "pthread_cond_signal");
3435 errcode = pthread_mutex_unlock(&tog_mutex);
3436 if (errcode)
3437 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3438 done:
3439 if (err) {
3440 tog_thread_error = 1;
3441 pthread_cond_signal(&a->commit_loaded);
3442 if (a->worktree) {
3443 got_worktree_close(a->worktree);
3444 a->worktree = NULL;
3447 return (void *)err;
3450 static const struct got_error *
3451 stop_log_thread(struct tog_log_view_state *s)
3453 const struct got_error *err = NULL, *thread_err = NULL;
3454 int errcode;
3456 if (s->thread) {
3457 s->quit = 1;
3458 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3459 if (errcode)
3460 return got_error_set_errno(errcode,
3461 "pthread_cond_signal");
3462 errcode = pthread_mutex_unlock(&tog_mutex);
3463 if (errcode)
3464 return got_error_set_errno(errcode,
3465 "pthread_mutex_unlock");
3466 errcode = pthread_join(s->thread, (void **)&thread_err);
3467 if (errcode)
3468 return got_error_set_errno(errcode, "pthread_join");
3469 errcode = pthread_mutex_lock(&tog_mutex);
3470 if (errcode)
3471 return got_error_set_errno(errcode,
3472 "pthread_mutex_lock");
3473 s->thread = 0; //NULL;
3476 if (s->thread_args.repo) {
3477 err = got_repo_close(s->thread_args.repo);
3478 s->thread_args.repo = NULL;
3481 if (s->thread_args.pack_fds) {
3482 const struct got_error *pack_err =
3483 got_repo_pack_fds_close(s->thread_args.pack_fds);
3484 if (err == NULL)
3485 err = pack_err;
3486 s->thread_args.pack_fds = NULL;
3489 if (s->thread_args.graph) {
3490 got_commit_graph_close(s->thread_args.graph);
3491 s->thread_args.graph = NULL;
3494 return err ? err : thread_err;
3497 static const struct got_error *
3498 close_log_view(struct tog_view *view)
3500 const struct got_error *err = NULL;
3501 struct tog_log_view_state *s = &view->state.log;
3502 int errcode;
3504 err = stop_log_thread(s);
3506 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3507 if (errcode && err == NULL)
3508 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3510 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3511 if (errcode && err == NULL)
3512 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3514 free_commits(&s->limit_commits);
3515 free_commits(&s->real_commits);
3516 free(s->in_repo_path);
3517 s->in_repo_path = NULL;
3518 free(s->start_id);
3519 s->start_id = NULL;
3520 free(s->head_ref_name);
3521 s->head_ref_name = NULL;
3522 return err;
3526 * We use two queues to implement the limit feature: first consists of
3527 * commits matching the current limit_regex; second is the real queue
3528 * of all known commits (real_commits). When the user starts limiting,
3529 * we swap queues such that all movement and displaying functionality
3530 * works with very slight change.
3532 static const struct got_error *
3533 limit_log_view(struct tog_view *view)
3535 struct tog_log_view_state *s = &view->state.log;
3536 struct commit_queue_entry *entry;
3537 struct tog_view *v = view;
3538 const struct got_error *err = NULL;
3539 char pattern[1024];
3540 int ret;
3542 if (view_is_hsplit_top(view))
3543 v = view->child;
3544 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3545 v = view->parent;
3547 /* Get the pattern */
3548 wmove(v->window, v->nlines - 1, 0);
3549 wclrtoeol(v->window);
3550 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3551 nodelay(v->window, FALSE);
3552 nocbreak();
3553 echo();
3554 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3555 cbreak();
3556 noecho();
3557 nodelay(v->window, TRUE);
3558 if (ret == ERR)
3559 return NULL;
3561 if (*pattern == '\0') {
3563 * Safety measure for the situation where the user
3564 * resets limit without previously limiting anything.
3566 if (!s->limit_view)
3567 return NULL;
3570 * User could have pressed Ctrl+L, which refreshed the
3571 * commit queues, it means we can't save previously
3572 * (before limit took place) displayed entries,
3573 * because they would point to already free'ed memory,
3574 * so we are forced to always select first entry of
3575 * the queue.
3577 s->commits = &s->real_commits;
3578 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3579 s->selected_entry = s->first_displayed_entry;
3580 s->selected = 0;
3581 s->limit_view = 0;
3583 return NULL;
3586 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3587 return NULL;
3589 s->limit_view = 1;
3591 /* Clear the screen while loading limit view */
3592 s->first_displayed_entry = NULL;
3593 s->last_displayed_entry = NULL;
3594 s->selected_entry = NULL;
3595 s->commits = &s->limit_commits;
3597 /* Prepare limit queue for new search */
3598 free_commits(&s->limit_commits);
3599 s->limit_commits.ncommits = 0;
3601 /* First process commits, which are in queue already */
3602 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3603 int have_match = 0;
3605 err = match_commit(&have_match, entry->id,
3606 entry->commit, &s->limit_regex);
3607 if (err)
3608 return err;
3610 if (have_match) {
3611 struct commit_queue_entry *matched;
3613 matched = alloc_commit_queue_entry(entry->commit,
3614 entry->id);
3615 if (matched == NULL) {
3616 err = got_error_from_errno(
3617 "alloc_commit_queue_entry");
3618 break;
3620 matched->commit = entry->commit;
3621 got_object_commit_retain(entry->commit);
3623 matched->idx = s->limit_commits.ncommits;
3624 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3625 matched, entry);
3626 s->limit_commits.ncommits++;
3630 /* Second process all the commits, until we fill the screen */
3631 if (s->limit_commits.ncommits < view->nlines - 1 &&
3632 !s->thread_args.log_complete) {
3633 s->thread_args.commits_needed +=
3634 view->nlines - s->limit_commits.ncommits - 1;
3635 err = trigger_log_thread(view, 1);
3636 if (err)
3637 return err;
3640 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3641 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3642 s->selected = 0;
3644 return NULL;
3647 static const struct got_error *
3648 search_start_log_view(struct tog_view *view)
3650 struct tog_log_view_state *s = &view->state.log;
3652 s->matched_entry = NULL;
3653 s->search_entry = NULL;
3654 return NULL;
3657 static const struct got_error *
3658 search_next_log_view(struct tog_view *view)
3660 const struct got_error *err = NULL;
3661 struct tog_log_view_state *s = &view->state.log;
3662 struct commit_queue_entry *entry;
3664 /* Display progress update in log view. */
3665 show_log_view(view);
3666 update_panels();
3667 doupdate();
3669 if (s->search_entry) {
3670 int errcode, ch;
3671 errcode = pthread_mutex_unlock(&tog_mutex);
3672 if (errcode)
3673 return got_error_set_errno(errcode,
3674 "pthread_mutex_unlock");
3675 ch = wgetch(view->window);
3676 errcode = pthread_mutex_lock(&tog_mutex);
3677 if (errcode)
3678 return got_error_set_errno(errcode,
3679 "pthread_mutex_lock");
3680 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3681 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3682 return NULL;
3684 if (view->searching == TOG_SEARCH_FORWARD)
3685 entry = TAILQ_NEXT(s->search_entry, entry);
3686 else
3687 entry = TAILQ_PREV(s->search_entry,
3688 commit_queue_head, entry);
3689 } else if (s->matched_entry) {
3691 * If the user has moved the cursor after we hit a match,
3692 * the position from where we should continue searching
3693 * might have changed.
3695 if (view->searching == TOG_SEARCH_FORWARD)
3696 entry = TAILQ_NEXT(s->selected_entry, entry);
3697 else
3698 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3699 entry);
3700 } else {
3701 entry = s->selected_entry;
3704 while (1) {
3705 int have_match = 0;
3707 if (entry == NULL) {
3708 if (s->thread_args.log_complete ||
3709 view->searching == TOG_SEARCH_BACKWARD) {
3710 view->search_next_done =
3711 (s->matched_entry == NULL ?
3712 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3713 s->search_entry = NULL;
3714 return NULL;
3717 * Poke the log thread for more commits and return,
3718 * allowing the main loop to make progress. Search
3719 * will resume at s->search_entry once we come back.
3721 s->thread_args.commits_needed++;
3722 return trigger_log_thread(view, 0);
3725 err = match_commit(&have_match, entry->id, entry->commit,
3726 &view->regex);
3727 if (err)
3728 break;
3729 if (have_match) {
3730 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3731 s->matched_entry = entry;
3732 break;
3735 s->search_entry = entry;
3736 if (view->searching == TOG_SEARCH_FORWARD)
3737 entry = TAILQ_NEXT(entry, entry);
3738 else
3739 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3742 if (s->matched_entry) {
3743 int cur = s->selected_entry->idx;
3744 while (cur < s->matched_entry->idx) {
3745 err = input_log_view(NULL, view, KEY_DOWN);
3746 if (err)
3747 return err;
3748 cur++;
3750 while (cur > s->matched_entry->idx) {
3751 err = input_log_view(NULL, view, KEY_UP);
3752 if (err)
3753 return err;
3754 cur--;
3758 s->search_entry = NULL;
3760 return NULL;
3763 static const struct got_error *
3764 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3765 struct got_repository *repo, const char *head_ref_name,
3766 const char *in_repo_path, int log_branches,
3767 struct got_worktree *worktree)
3769 const struct got_error *err = NULL;
3770 struct tog_log_view_state *s = &view->state.log;
3771 struct got_repository *thread_repo = NULL;
3772 struct got_commit_graph *thread_graph = NULL;
3773 int errcode;
3775 if (in_repo_path != s->in_repo_path) {
3776 free(s->in_repo_path);
3777 s->in_repo_path = strdup(in_repo_path);
3778 if (s->in_repo_path == NULL) {
3779 err = got_error_from_errno("strdup");
3780 goto done;
3784 /* The commit queue only contains commits being displayed. */
3785 TAILQ_INIT(&s->real_commits.head);
3786 s->real_commits.ncommits = 0;
3787 s->commits = &s->real_commits;
3789 TAILQ_INIT(&s->limit_commits.head);
3790 s->limit_view = 0;
3791 s->limit_commits.ncommits = 0;
3793 s->repo = repo;
3794 if (head_ref_name) {
3795 s->head_ref_name = strdup(head_ref_name);
3796 if (s->head_ref_name == NULL) {
3797 err = got_error_from_errno("strdup");
3798 goto done;
3801 s->start_id = got_object_id_dup(start_id);
3802 if (s->start_id == NULL) {
3803 err = got_error_from_errno("got_object_id_dup");
3804 goto done;
3806 s->log_branches = log_branches;
3807 s->use_committer = 1;
3809 STAILQ_INIT(&s->colors);
3810 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3811 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3812 get_color_value("TOG_COLOR_COMMIT"));
3813 if (err)
3814 goto done;
3815 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3816 get_color_value("TOG_COLOR_AUTHOR"));
3817 if (err) {
3818 free_colors(&s->colors);
3819 goto done;
3821 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3822 get_color_value("TOG_COLOR_DATE"));
3823 if (err) {
3824 free_colors(&s->colors);
3825 goto done;
3829 view->show = show_log_view;
3830 view->input = input_log_view;
3831 view->resize = resize_log_view;
3832 view->close = close_log_view;
3833 view->search_start = search_start_log_view;
3834 view->search_next = search_next_log_view;
3836 if (s->thread_args.pack_fds == NULL) {
3837 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3838 if (err)
3839 goto done;
3841 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3842 s->thread_args.pack_fds);
3843 if (err)
3844 goto done;
3845 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3846 !s->log_branches);
3847 if (err)
3848 goto done;
3849 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3850 s->repo, NULL, NULL);
3851 if (err)
3852 goto done;
3854 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3855 if (errcode) {
3856 err = got_error_set_errno(errcode, "pthread_cond_init");
3857 goto done;
3859 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3860 if (errcode) {
3861 err = got_error_set_errno(errcode, "pthread_cond_init");
3862 goto done;
3865 if (using_mock_io) {
3866 int rc;
3868 rc = pthread_cond_init(&s->thread_args.log_loaded, NULL);
3869 if (rc)
3870 return got_error_set_errno(rc, "pthread_cond_init");
3873 s->thread_args.commits_needed = view->nlines;
3874 s->thread_args.graph = thread_graph;
3875 s->thread_args.real_commits = &s->real_commits;
3876 s->thread_args.limit_commits = &s->limit_commits;
3877 s->thread_args.in_repo_path = s->in_repo_path;
3878 s->thread_args.start_id = s->start_id;
3879 s->thread_args.repo = thread_repo;
3880 s->thread_args.log_complete = 0;
3881 s->thread_args.quit = &s->quit;
3882 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3883 s->thread_args.selected_entry = &s->selected_entry;
3884 s->thread_args.searching = &view->searching;
3885 s->thread_args.search_next_done = &view->search_next_done;
3886 s->thread_args.regex = &view->regex;
3887 s->thread_args.limiting = &s->limit_view;
3888 s->thread_args.limit_regex = &s->limit_regex;
3889 s->thread_args.limit_commits = &s->limit_commits;
3890 s->thread_args.worktree = worktree;
3891 if (worktree)
3892 s->thread_args.need_commit_marker = 1;
3893 done:
3894 if (err) {
3895 if (view->close == NULL)
3896 close_log_view(view);
3897 view_close(view);
3899 return err;
3902 static const struct got_error *
3903 show_log_view(struct tog_view *view)
3905 const struct got_error *err;
3906 struct tog_log_view_state *s = &view->state.log;
3908 if (s->thread == 0) { //NULL) {
3909 int errcode = pthread_create(&s->thread, NULL, log_thread,
3910 &s->thread_args);
3911 if (errcode)
3912 return got_error_set_errno(errcode, "pthread_create");
3913 if (s->thread_args.commits_needed > 0) {
3914 err = trigger_log_thread(view, 1);
3915 if (err)
3916 return err;
3917 if (tog_io.wait_for_ui) {
3918 int rc;
3920 rc = pthread_cond_wait(&s->thread_args.log_loaded,
3921 &tog_mutex);
3922 if (rc)
3923 return got_error_set_errno(rc,
3924 "pthread_cond_wait");
3925 tog_io.wait_for_ui = 0;
3930 return draw_commits(view);
3933 static void
3934 log_move_cursor_up(struct tog_view *view, int page, int home)
3936 struct tog_log_view_state *s = &view->state.log;
3938 if (s->first_displayed_entry == NULL)
3939 return;
3940 if (s->selected_entry->idx == 0)
3941 view->count = 0;
3943 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3944 || home)
3945 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3947 if (!page && !home && s->selected > 0)
3948 --s->selected;
3949 else
3950 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3952 select_commit(s);
3953 return;
3956 static const struct got_error *
3957 log_move_cursor_down(struct tog_view *view, int page)
3959 struct tog_log_view_state *s = &view->state.log;
3960 const struct got_error *err = NULL;
3961 int eos = view->nlines - 2;
3963 if (s->first_displayed_entry == NULL)
3964 return NULL;
3966 if (s->thread_args.log_complete &&
3967 s->selected_entry->idx >= s->commits->ncommits - 1)
3968 return NULL;
3970 if (view_is_hsplit_top(view))
3971 --eos; /* border consumes the last line */
3973 if (!page) {
3974 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3975 ++s->selected;
3976 else
3977 err = log_scroll_down(view, 1);
3978 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3979 struct commit_queue_entry *entry;
3980 int n;
3982 s->selected = 0;
3983 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3984 s->last_displayed_entry = entry;
3985 for (n = 0; n <= eos; n++) {
3986 if (entry == NULL)
3987 break;
3988 s->first_displayed_entry = entry;
3989 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3991 if (n > 0)
3992 s->selected = n - 1;
3993 } else {
3994 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3995 s->thread_args.log_complete)
3996 s->selected += MIN(page,
3997 s->commits->ncommits - s->selected_entry->idx - 1);
3998 else
3999 err = log_scroll_down(view, page);
4001 if (err)
4002 return err;
4005 * We might necessarily overshoot in horizontal
4006 * splits; if so, select the last displayed commit.
4008 if (s->first_displayed_entry && s->last_displayed_entry) {
4009 s->selected = MIN(s->selected,
4010 s->last_displayed_entry->idx -
4011 s->first_displayed_entry->idx);
4014 select_commit(s);
4016 if (s->thread_args.log_complete &&
4017 s->selected_entry->idx == s->commits->ncommits - 1)
4018 view->count = 0;
4020 return NULL;
4023 static void
4024 view_get_split(struct tog_view *view, int *y, int *x)
4026 *x = 0;
4027 *y = 0;
4029 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
4030 if (view->child && view->child->resized_y)
4031 *y = view->child->resized_y;
4032 else if (view->resized_y)
4033 *y = view->resized_y;
4034 else
4035 *y = view_split_begin_y(view->lines);
4036 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
4037 if (view->child && view->child->resized_x)
4038 *x = view->child->resized_x;
4039 else if (view->resized_x)
4040 *x = view->resized_x;
4041 else
4042 *x = view_split_begin_x(view->begin_x);
4046 /* Split view horizontally at y and offset view->state->selected line. */
4047 static const struct got_error *
4048 view_init_hsplit(struct tog_view *view, int y)
4050 const struct got_error *err = NULL;
4052 view->nlines = y;
4053 view->ncols = COLS;
4054 err = view_resize(view);
4055 if (err)
4056 return err;
4058 err = offset_selection_down(view);
4060 return err;
4063 static const struct got_error *
4064 log_goto_line(struct tog_view *view, int nlines)
4066 const struct got_error *err = NULL;
4067 struct tog_log_view_state *s = &view->state.log;
4068 int g, idx = s->selected_entry->idx;
4070 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
4071 return NULL;
4073 g = view->gline;
4074 view->gline = 0;
4076 if (g >= s->first_displayed_entry->idx + 1 &&
4077 g <= s->last_displayed_entry->idx + 1 &&
4078 g - s->first_displayed_entry->idx - 1 < nlines) {
4079 s->selected = g - s->first_displayed_entry->idx - 1;
4080 select_commit(s);
4081 return NULL;
4084 if (idx + 1 < g) {
4085 err = log_move_cursor_down(view, g - idx - 1);
4086 if (!err && g > s->selected_entry->idx + 1)
4087 err = log_move_cursor_down(view,
4088 g - s->first_displayed_entry->idx - 1);
4089 if (err)
4090 return err;
4091 } else if (idx + 1 > g)
4092 log_move_cursor_up(view, idx - g + 1, 0);
4094 if (g < nlines && s->first_displayed_entry->idx == 0)
4095 s->selected = g - 1;
4097 select_commit(s);
4098 return NULL;
4102 static void
4103 horizontal_scroll_input(struct tog_view *view, int ch)
4106 switch (ch) {
4107 case KEY_LEFT:
4108 case 'h':
4109 view->x -= MIN(view->x, 2);
4110 if (view->x <= 0)
4111 view->count = 0;
4112 break;
4113 case KEY_RIGHT:
4114 case 'l':
4115 if (view->x + view->ncols / 2 < view->maxx)
4116 view->x += 2;
4117 else
4118 view->count = 0;
4119 break;
4120 case '0':
4121 view->x = 0;
4122 break;
4123 case '$':
4124 view->x = MAX(view->maxx - view->ncols / 2, 0);
4125 view->count = 0;
4126 break;
4127 default:
4128 break;
4132 static const struct got_error *
4133 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4135 const struct got_error *err = NULL;
4136 struct tog_log_view_state *s = &view->state.log;
4137 int eos, nscroll;
4139 if (s->thread_args.load_all) {
4140 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4141 s->thread_args.load_all = 0;
4142 else if (s->thread_args.log_complete) {
4143 err = log_move_cursor_down(view, s->commits->ncommits);
4144 s->thread_args.load_all = 0;
4146 if (err)
4147 return err;
4150 eos = nscroll = view->nlines - 1;
4151 if (view_is_hsplit_top(view))
4152 --eos; /* border */
4154 if (view->gline)
4155 return log_goto_line(view, eos);
4157 switch (ch) {
4158 case '&':
4159 err = limit_log_view(view);
4160 break;
4161 case 'q':
4162 s->quit = 1;
4163 break;
4164 case '0':
4165 case '$':
4166 case KEY_RIGHT:
4167 case 'l':
4168 case KEY_LEFT:
4169 case 'h':
4170 horizontal_scroll_input(view, ch);
4171 break;
4172 case 'k':
4173 case KEY_UP:
4174 case '<':
4175 case ',':
4176 case CTRL('p'):
4177 log_move_cursor_up(view, 0, 0);
4178 break;
4179 case 'g':
4180 case '=':
4181 case KEY_HOME:
4182 log_move_cursor_up(view, 0, 1);
4183 view->count = 0;
4184 break;
4185 case CTRL('u'):
4186 case 'u':
4187 nscroll /= 2;
4188 /* FALL THROUGH */
4189 case KEY_PPAGE:
4190 case CTRL('b'):
4191 case 'b':
4192 log_move_cursor_up(view, nscroll, 0);
4193 break;
4194 case 'j':
4195 case KEY_DOWN:
4196 case '>':
4197 case '.':
4198 case CTRL('n'):
4199 err = log_move_cursor_down(view, 0);
4200 break;
4201 case '@':
4202 s->use_committer = !s->use_committer;
4203 view->action = s->use_committer ?
4204 "show committer" : "show commit author";
4205 break;
4206 case 'G':
4207 case '*':
4208 case KEY_END: {
4209 /* We don't know yet how many commits, so we're forced to
4210 * traverse them all. */
4211 view->count = 0;
4212 s->thread_args.load_all = 1;
4213 if (!s->thread_args.log_complete)
4214 return trigger_log_thread(view, 0);
4215 err = log_move_cursor_down(view, s->commits->ncommits);
4216 s->thread_args.load_all = 0;
4217 break;
4219 case CTRL('d'):
4220 case 'd':
4221 nscroll /= 2;
4222 /* FALL THROUGH */
4223 case KEY_NPAGE:
4224 case CTRL('f'):
4225 case 'f':
4226 case ' ':
4227 err = log_move_cursor_down(view, nscroll);
4228 break;
4229 case KEY_RESIZE:
4230 if (s->selected > view->nlines - 2)
4231 s->selected = view->nlines - 2;
4232 if (s->selected > s->commits->ncommits - 1)
4233 s->selected = s->commits->ncommits - 1;
4234 select_commit(s);
4235 if (s->commits->ncommits < view->nlines - 1 &&
4236 !s->thread_args.log_complete) {
4237 s->thread_args.commits_needed += (view->nlines - 1) -
4238 s->commits->ncommits;
4239 err = trigger_log_thread(view, 1);
4241 break;
4242 case KEY_ENTER:
4243 case '\r':
4244 view->count = 0;
4245 if (s->selected_entry == NULL)
4246 break;
4247 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4248 break;
4249 case 'T':
4250 view->count = 0;
4251 if (s->selected_entry == NULL)
4252 break;
4253 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4254 break;
4255 case KEY_BACKSPACE:
4256 case CTRL('l'):
4257 case 'B':
4258 view->count = 0;
4259 if (ch == KEY_BACKSPACE &&
4260 got_path_is_root_dir(s->in_repo_path))
4261 break;
4262 err = stop_log_thread(s);
4263 if (err)
4264 return err;
4265 if (ch == KEY_BACKSPACE) {
4266 char *parent_path;
4267 err = got_path_dirname(&parent_path, s->in_repo_path);
4268 if (err)
4269 return err;
4270 free(s->in_repo_path);
4271 s->in_repo_path = parent_path;
4272 s->thread_args.in_repo_path = s->in_repo_path;
4273 } else if (ch == CTRL('l')) {
4274 struct got_object_id *start_id;
4275 err = got_repo_match_object_id(&start_id, NULL,
4276 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4277 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4278 if (err) {
4279 if (s->head_ref_name == NULL ||
4280 err->code != GOT_ERR_NOT_REF)
4281 return err;
4282 /* Try to cope with deleted references. */
4283 free(s->head_ref_name);
4284 s->head_ref_name = NULL;
4285 err = got_repo_match_object_id(&start_id,
4286 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4287 &tog_refs, s->repo);
4288 if (err)
4289 return err;
4291 free(s->start_id);
4292 s->start_id = start_id;
4293 s->thread_args.start_id = s->start_id;
4294 } else /* 'B' */
4295 s->log_branches = !s->log_branches;
4297 if (s->thread_args.pack_fds == NULL) {
4298 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4299 if (err)
4300 return err;
4302 err = got_repo_open(&s->thread_args.repo,
4303 got_repo_get_path(s->repo), NULL,
4304 s->thread_args.pack_fds);
4305 if (err)
4306 return err;
4307 tog_free_refs();
4308 err = tog_load_refs(s->repo, 0);
4309 if (err)
4310 return err;
4311 err = got_commit_graph_open(&s->thread_args.graph,
4312 s->in_repo_path, !s->log_branches);
4313 if (err)
4314 return err;
4315 err = got_commit_graph_iter_start(s->thread_args.graph,
4316 s->start_id, s->repo, NULL, NULL);
4317 if (err)
4318 return err;
4319 free_commits(&s->real_commits);
4320 free_commits(&s->limit_commits);
4321 s->first_displayed_entry = NULL;
4322 s->last_displayed_entry = NULL;
4323 s->selected_entry = NULL;
4324 s->selected = 0;
4325 s->thread_args.log_complete = 0;
4326 s->quit = 0;
4327 s->thread_args.commits_needed = view->lines;
4328 s->matched_entry = NULL;
4329 s->search_entry = NULL;
4330 view->offset = 0;
4331 break;
4332 case 'R':
4333 view->count = 0;
4334 err = view_request_new(new_view, view, TOG_VIEW_REF);
4335 break;
4336 default:
4337 view->count = 0;
4338 break;
4341 return err;
4344 static const struct got_error *
4345 apply_unveil(const char *repo_path, const char *worktree_path)
4347 const struct got_error *error;
4349 #ifdef PROFILE
4350 if (unveil("gmon.out", "rwc") != 0)
4351 return got_error_from_errno2("unveil", "gmon.out");
4352 #endif
4353 if (repo_path && unveil(repo_path, "r") != 0)
4354 return got_error_from_errno2("unveil", repo_path);
4356 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4357 return got_error_from_errno2("unveil", worktree_path);
4359 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4360 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4362 error = got_privsep_unveil_exec_helpers();
4363 if (error != NULL)
4364 return error;
4366 if (unveil(NULL, NULL) != 0)
4367 return got_error_from_errno("unveil");
4369 return NULL;
4372 static const struct got_error *
4373 init_mock_term(const char *test_script_path)
4375 const struct got_error *err = NULL;
4376 const char *screen_dump_path;
4377 int in;
4379 if (test_script_path == NULL || *test_script_path == '\0')
4380 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4382 tog_io.f = fopen(test_script_path, "re");
4383 if (tog_io.f == NULL) {
4384 err = got_error_from_errno_fmt("fopen: %s",
4385 test_script_path);
4386 goto done;
4389 /* test mode, we don't want any output */
4390 tog_io.cout = fopen("/dev/null", "w+");
4391 if (tog_io.cout == NULL) {
4392 err = got_error_from_errno2("fopen", "/dev/null");
4393 goto done;
4396 in = dup(fileno(tog_io.cout));
4397 if (in == -1) {
4398 err = got_error_from_errno("dup");
4399 goto done;
4401 tog_io.cin = fdopen(in, "r");
4402 if (tog_io.cin == NULL) {
4403 err = got_error_from_errno("fdopen");
4404 close(in);
4405 goto done;
4408 screen_dump_path = getenv("TOG_SCR_DUMP");
4409 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4410 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4411 tog_io.sdump = fopen(screen_dump_path, "we");
4412 if (tog_io.sdump == NULL) {
4413 err = got_error_from_errno2("fopen", screen_dump_path);
4414 goto done;
4417 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4418 err = got_error_from_errno("fseeko");
4419 goto done;
4422 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4423 err = got_error_msg(GOT_ERR_IO,
4424 "newterm: failed to initialise curses");
4426 using_mock_io = 1;
4428 done:
4429 if (err)
4430 tog_io_close();
4431 return err;
4434 static void
4435 init_curses(void)
4438 * Override default signal handlers before starting ncurses.
4439 * This should prevent ncurses from installing its own
4440 * broken cleanup() signal handler.
4442 signal(SIGWINCH, tog_sigwinch);
4443 signal(SIGPIPE, tog_sigpipe);
4444 signal(SIGCONT, tog_sigcont);
4445 signal(SIGINT, tog_sigint);
4446 signal(SIGTERM, tog_sigterm);
4448 if (using_mock_io) /* In test mode we use a fake terminal */
4449 return;
4451 initscr();
4453 cbreak();
4454 halfdelay(1); /* Fast refresh while initial view is loading. */
4455 noecho();
4456 nonl();
4457 intrflush(stdscr, FALSE);
4458 keypad(stdscr, TRUE);
4459 curs_set(0);
4460 if (getenv("TOG_COLORS") != NULL) {
4461 start_color();
4462 use_default_colors();
4465 return;
4468 static const struct got_error *
4469 set_tog_base_commit(struct got_repository *repo, struct got_worktree *worktree)
4471 tog_base_commit.id = got_object_id_dup(
4472 got_worktree_get_base_commit_id(worktree));
4473 if (tog_base_commit.id == NULL)
4474 return got_error_from_errno( "got_object_id_dup");
4476 return NULL;
4479 static const struct got_error *
4480 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4481 struct got_repository *repo, struct got_worktree *worktree)
4483 const struct got_error *err = NULL;
4485 if (argc == 0) {
4486 *in_repo_path = strdup("/");
4487 if (*in_repo_path == NULL)
4488 return got_error_from_errno("strdup");
4489 return NULL;
4492 if (worktree) {
4493 const char *prefix = got_worktree_get_path_prefix(worktree);
4494 char *p;
4496 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4497 if (err)
4498 return err;
4499 if (asprintf(in_repo_path, "%s%s%s", prefix,
4500 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4501 p) == -1) {
4502 err = got_error_from_errno("asprintf");
4503 *in_repo_path = NULL;
4505 free(p);
4506 } else
4507 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4509 return err;
4512 static const struct got_error *
4513 cmd_log(int argc, char *argv[])
4515 const struct got_error *error;
4516 struct got_repository *repo = NULL;
4517 struct got_worktree *worktree = NULL;
4518 struct got_object_id *start_id = NULL;
4519 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4520 char *keyword_idstr = NULL, *start_commit = NULL, *label = NULL;
4521 struct got_reference *ref = NULL;
4522 const char *head_ref_name = NULL;
4523 int ch, log_branches = 0;
4524 struct tog_view *view;
4525 int *pack_fds = NULL;
4527 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4528 switch (ch) {
4529 case 'b':
4530 log_branches = 1;
4531 break;
4532 case 'c':
4533 start_commit = optarg;
4534 break;
4535 case 'r':
4536 repo_path = realpath(optarg, NULL);
4537 if (repo_path == NULL)
4538 return got_error_from_errno2("realpath",
4539 optarg);
4540 break;
4541 default:
4542 usage_log();
4543 /* NOTREACHED */
4547 argc -= optind;
4548 argv += optind;
4550 if (argc > 1)
4551 usage_log();
4553 error = got_repo_pack_fds_open(&pack_fds);
4554 if (error != NULL)
4555 goto done;
4557 if (repo_path == NULL) {
4558 cwd = getcwd(NULL, 0);
4559 if (cwd == NULL) {
4560 error = got_error_from_errno("getcwd");
4561 goto done;
4563 error = got_worktree_open(&worktree, cwd, NULL);
4564 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4565 goto done;
4566 if (worktree)
4567 repo_path =
4568 strdup(got_worktree_get_repo_path(worktree));
4569 else
4570 repo_path = strdup(cwd);
4571 if (repo_path == NULL) {
4572 error = got_error_from_errno("strdup");
4573 goto done;
4577 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4578 if (error != NULL)
4579 goto done;
4581 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4582 repo, worktree);
4583 if (error)
4584 goto done;
4586 init_curses();
4588 error = apply_unveil(got_repo_get_path(repo),
4589 worktree ? got_worktree_get_root_path(worktree) : NULL);
4590 if (error)
4591 goto done;
4593 /* already loaded by tog_log_with_path()? */
4594 if (TAILQ_EMPTY(&tog_refs)) {
4595 error = tog_load_refs(repo, 0);
4596 if (error)
4597 goto done;
4600 if (start_commit == NULL) {
4601 error = got_repo_match_object_id(&start_id, &label,
4602 worktree ? got_worktree_get_head_ref_name(worktree) :
4603 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4604 if (error)
4605 goto done;
4606 head_ref_name = label;
4607 } else {
4608 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4609 repo, worktree);
4610 if (error != NULL)
4611 goto done;
4612 if (keyword_idstr != NULL)
4613 start_commit = keyword_idstr;
4615 error = got_ref_open(&ref, repo, start_commit, 0);
4616 if (error == NULL)
4617 head_ref_name = got_ref_get_name(ref);
4618 else if (error->code != GOT_ERR_NOT_REF)
4619 goto done;
4620 error = got_repo_match_object_id(&start_id, NULL,
4621 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4622 if (error)
4623 goto done;
4626 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4627 if (view == NULL) {
4628 error = got_error_from_errno("view_open");
4629 goto done;
4632 if (worktree) {
4633 error = set_tog_base_commit(repo, worktree);
4634 if (error != NULL)
4635 goto done;
4638 error = open_log_view(view, start_id, repo, head_ref_name,
4639 in_repo_path, log_branches, worktree);
4640 if (error)
4641 goto done;
4643 if (worktree) {
4644 /* The work tree will be closed by the log thread. */
4645 worktree = NULL;
4648 error = view_loop(view);
4650 done:
4651 free(tog_base_commit.id);
4652 free(keyword_idstr);
4653 free(in_repo_path);
4654 free(repo_path);
4655 free(cwd);
4656 free(start_id);
4657 free(label);
4658 if (ref)
4659 got_ref_close(ref);
4660 if (repo) {
4661 const struct got_error *close_err = got_repo_close(repo);
4662 if (error == NULL)
4663 error = close_err;
4665 if (worktree)
4666 got_worktree_close(worktree);
4667 if (pack_fds) {
4668 const struct got_error *pack_err =
4669 got_repo_pack_fds_close(pack_fds);
4670 if (error == NULL)
4671 error = pack_err;
4673 tog_free_refs();
4674 return error;
4677 __dead static void
4678 usage_diff(void)
4680 endwin();
4681 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4682 "object1 object2\n", getprogname());
4683 exit(1);
4686 static int
4687 match_line(const char *line, regex_t *regex, size_t nmatch,
4688 regmatch_t *regmatch)
4690 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4693 static struct tog_color *
4694 match_color(struct tog_colors *colors, const char *line)
4696 struct tog_color *tc = NULL;
4698 STAILQ_FOREACH(tc, colors, entry) {
4699 if (match_line(line, &tc->regex, 0, NULL))
4700 return tc;
4703 return NULL;
4706 static const struct got_error *
4707 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4708 WINDOW *window, int skipcol, regmatch_t *regmatch)
4710 const struct got_error *err = NULL;
4711 char *exstr = NULL;
4712 wchar_t *wline = NULL;
4713 int rme, rms, n, width, scrollx;
4714 int width0 = 0, width1 = 0, width2 = 0;
4715 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4717 *wtotal = 0;
4719 rms = regmatch->rm_so;
4720 rme = regmatch->rm_eo;
4722 err = expand_tab(&exstr, line);
4723 if (err)
4724 return err;
4726 /* Split the line into 3 segments, according to match offsets. */
4727 seg0 = strndup(exstr, rms);
4728 if (seg0 == NULL) {
4729 err = got_error_from_errno("strndup");
4730 goto done;
4732 seg1 = strndup(exstr + rms, rme - rms);
4733 if (seg1 == NULL) {
4734 err = got_error_from_errno("strndup");
4735 goto done;
4737 seg2 = strdup(exstr + rme);
4738 if (seg2 == NULL) {
4739 err = got_error_from_errno("strndup");
4740 goto done;
4743 /* draw up to matched token if we haven't scrolled past it */
4744 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4745 col_tab_align, 1);
4746 if (err)
4747 goto done;
4748 n = MAX(width0 - skipcol, 0);
4749 if (n) {
4750 free(wline);
4751 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4752 wlimit, col_tab_align, 1);
4753 if (err)
4754 goto done;
4755 waddwstr(window, &wline[scrollx]);
4756 wlimit -= width;
4757 *wtotal += width;
4760 if (wlimit > 0) {
4761 int i = 0, w = 0;
4762 size_t wlen;
4764 free(wline);
4765 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4766 col_tab_align, 1);
4767 if (err)
4768 goto done;
4769 wlen = wcslen(wline);
4770 while (i < wlen) {
4771 width = wcwidth(wline[i]);
4772 if (width == -1) {
4773 /* should not happen, tabs are expanded */
4774 err = got_error(GOT_ERR_RANGE);
4775 goto done;
4777 if (width0 + w + width > skipcol)
4778 break;
4779 w += width;
4780 i++;
4782 /* draw (visible part of) matched token (if scrolled into it) */
4783 if (width1 - w > 0) {
4784 wattron(window, A_STANDOUT);
4785 waddwstr(window, &wline[i]);
4786 wattroff(window, A_STANDOUT);
4787 wlimit -= (width1 - w);
4788 *wtotal += (width1 - w);
4792 if (wlimit > 0) { /* draw rest of line */
4793 free(wline);
4794 if (skipcol > width0 + width1) {
4795 err = format_line(&wline, &width2, &scrollx, seg2,
4796 skipcol - (width0 + width1), wlimit,
4797 col_tab_align, 1);
4798 if (err)
4799 goto done;
4800 waddwstr(window, &wline[scrollx]);
4801 } else {
4802 err = format_line(&wline, &width2, NULL, seg2, 0,
4803 wlimit, col_tab_align, 1);
4804 if (err)
4805 goto done;
4806 waddwstr(window, wline);
4808 *wtotal += width2;
4810 done:
4811 free(wline);
4812 free(exstr);
4813 free(seg0);
4814 free(seg1);
4815 free(seg2);
4816 return err;
4819 static int
4820 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4822 FILE *f = NULL;
4823 int *eof, *first, *selected;
4825 if (view->type == TOG_VIEW_DIFF) {
4826 struct tog_diff_view_state *s = &view->state.diff;
4828 first = &s->first_displayed_line;
4829 selected = first;
4830 eof = &s->eof;
4831 f = s->f;
4832 } else if (view->type == TOG_VIEW_HELP) {
4833 struct tog_help_view_state *s = &view->state.help;
4835 first = &s->first_displayed_line;
4836 selected = first;
4837 eof = &s->eof;
4838 f = s->f;
4839 } else if (view->type == TOG_VIEW_BLAME) {
4840 struct tog_blame_view_state *s = &view->state.blame;
4842 first = &s->first_displayed_line;
4843 selected = &s->selected_line;
4844 eof = &s->eof;
4845 f = s->blame.f;
4846 } else
4847 return 0;
4849 /* Center gline in the middle of the page like vi(1). */
4850 if (*lineno < view->gline - (view->nlines - 3) / 2)
4851 return 0;
4852 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4853 rewind(f);
4854 *eof = 0;
4855 *first = 1;
4856 *lineno = 0;
4857 *nprinted = 0;
4858 return 0;
4861 *selected = view->gline <= (view->nlines - 3) / 2 ?
4862 view->gline : (view->nlines - 3) / 2 + 1;
4863 view->gline = 0;
4865 return 1;
4868 static const struct got_error *
4869 draw_file(struct tog_view *view, const char *header)
4871 struct tog_diff_view_state *s = &view->state.diff;
4872 regmatch_t *regmatch = &view->regmatch;
4873 const struct got_error *err;
4874 int nprinted = 0;
4875 char *line;
4876 size_t linesize = 0;
4877 ssize_t linelen;
4878 wchar_t *wline;
4879 int width;
4880 int max_lines = view->nlines;
4881 int nlines = s->nlines;
4882 off_t line_offset;
4884 s->lineno = s->first_displayed_line - 1;
4885 line_offset = s->lines[s->first_displayed_line - 1].offset;
4886 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4887 return got_error_from_errno("fseek");
4889 werase(view->window);
4891 if (view->gline > s->nlines - 1)
4892 view->gline = s->nlines - 1;
4894 if (header) {
4895 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4896 1 : view->gline - (view->nlines - 3) / 2 :
4897 s->lineno + s->selected_line;
4899 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4900 return got_error_from_errno("asprintf");
4901 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4902 0, 0);
4903 free(line);
4904 if (err)
4905 return err;
4907 if (view_needs_focus_indication(view))
4908 wstandout(view->window);
4909 waddwstr(view->window, wline);
4910 free(wline);
4911 wline = NULL;
4912 while (width++ < view->ncols)
4913 waddch(view->window, ' ');
4914 if (view_needs_focus_indication(view))
4915 wstandend(view->window);
4917 if (max_lines <= 1)
4918 return NULL;
4919 max_lines--;
4922 s->eof = 0;
4923 view->maxx = 0;
4924 line = NULL;
4925 while (max_lines > 0 && nprinted < max_lines) {
4926 enum got_diff_line_type linetype;
4927 attr_t attr = 0;
4929 linelen = getline(&line, &linesize, s->f);
4930 if (linelen == -1) {
4931 if (feof(s->f)) {
4932 s->eof = 1;
4933 break;
4935 free(line);
4936 return got_ferror(s->f, GOT_ERR_IO);
4939 if (++s->lineno < s->first_displayed_line)
4940 continue;
4941 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4942 continue;
4943 if (s->lineno == view->hiline)
4944 attr = A_STANDOUT;
4946 /* Set view->maxx based on full line length. */
4947 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4948 view->x ? 1 : 0);
4949 if (err) {
4950 free(line);
4951 return err;
4953 view->maxx = MAX(view->maxx, width);
4954 free(wline);
4955 wline = NULL;
4957 linetype = s->lines[s->lineno].type;
4958 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4959 linetype < GOT_DIFF_LINE_CONTEXT)
4960 attr |= COLOR_PAIR(linetype);
4961 if (attr)
4962 wattron(view->window, attr);
4963 if (s->first_displayed_line + nprinted == s->matched_line &&
4964 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4965 err = add_matched_line(&width, line, view->ncols, 0,
4966 view->window, view->x, regmatch);
4967 if (err) {
4968 free(line);
4969 return err;
4971 } else {
4972 int skip;
4973 err = format_line(&wline, &width, &skip, line,
4974 view->x, view->ncols, 0, view->x ? 1 : 0);
4975 if (err) {
4976 free(line);
4977 return err;
4979 waddwstr(view->window, &wline[skip]);
4980 free(wline);
4981 wline = NULL;
4983 if (s->lineno == view->hiline) {
4984 /* highlight full gline length */
4985 while (width++ < view->ncols)
4986 waddch(view->window, ' ');
4987 } else {
4988 if (width <= view->ncols - 1)
4989 waddch(view->window, '\n');
4991 if (attr)
4992 wattroff(view->window, attr);
4993 if (++nprinted == 1)
4994 s->first_displayed_line = s->lineno;
4996 free(line);
4997 if (nprinted >= 1)
4998 s->last_displayed_line = s->first_displayed_line +
4999 (nprinted - 1);
5000 else
5001 s->last_displayed_line = s->first_displayed_line;
5003 view_border(view);
5005 if (s->eof) {
5006 while (nprinted < view->nlines) {
5007 waddch(view->window, '\n');
5008 nprinted++;
5011 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
5012 view->ncols, 0, 0);
5013 if (err) {
5014 return err;
5017 wstandout(view->window);
5018 waddwstr(view->window, wline);
5019 free(wline);
5020 wline = NULL;
5021 wstandend(view->window);
5024 return NULL;
5027 static char *
5028 get_datestr(time_t *time, char *datebuf)
5030 struct tm mytm, *tm;
5031 char *p, *s;
5033 tm = gmtime_r(time, &mytm);
5034 if (tm == NULL)
5035 return NULL;
5036 s = asctime_r(tm, datebuf);
5037 if (s == NULL)
5038 return NULL;
5039 p = strchr(s, '\n');
5040 if (p)
5041 *p = '\0';
5042 return s;
5045 static const struct got_error *
5046 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
5047 off_t off, uint8_t type)
5049 struct got_diff_line *p;
5051 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
5052 if (p == NULL)
5053 return got_error_from_errno("reallocarray");
5054 *lines = p;
5055 (*lines)[*nlines].offset = off;
5056 (*lines)[*nlines].type = type;
5057 (*nlines)++;
5059 return NULL;
5062 static const struct got_error *
5063 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
5064 struct got_diff_line *s_lines, size_t s_nlines)
5066 struct got_diff_line *p;
5067 char buf[BUFSIZ];
5068 size_t i, r;
5070 if (fseeko(src, 0L, SEEK_SET) == -1)
5071 return got_error_from_errno("fseeko");
5073 for (;;) {
5074 r = fread(buf, 1, sizeof(buf), src);
5075 if (r == 0) {
5076 if (ferror(src))
5077 return got_error_from_errno("fread");
5078 if (feof(src))
5079 break;
5081 if (fwrite(buf, 1, r, dst) != r)
5082 return got_ferror(dst, GOT_ERR_IO);
5085 if (s_nlines == 0 && *d_nlines == 0)
5086 return NULL;
5089 * If commit info was in dst, increment line offsets
5090 * of the appended diff content, but skip s_lines[0]
5091 * because offset zero is already in *d_lines.
5093 if (*d_nlines > 0) {
5094 for (i = 1; i < s_nlines; ++i)
5095 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
5097 if (s_nlines > 0) {
5098 --s_nlines;
5099 ++s_lines;
5103 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
5104 if (p == NULL) {
5105 /* d_lines is freed in close_diff_view() */
5106 return got_error_from_errno("reallocarray");
5109 *d_lines = p;
5111 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
5112 *d_nlines += s_nlines;
5114 return NULL;
5117 static const struct got_error *
5118 write_commit_info(struct got_diff_line **lines, size_t *nlines,
5119 struct got_object_id *commit_id, struct got_reflist_head *refs,
5120 struct got_repository *repo, int ignore_ws, int force_text_diff,
5121 struct got_diffstat_cb_arg *dsa, FILE *outfile)
5123 const struct got_error *err = NULL;
5124 char datebuf[26], *datestr;
5125 struct got_commit_object *commit;
5126 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
5127 time_t committer_time;
5128 const char *author, *committer;
5129 char *refs_str = NULL;
5130 struct got_pathlist_entry *pe;
5131 off_t outoff = 0;
5132 int n;
5134 err = build_refs_str(&refs_str, refs, commit_id, repo);
5135 if (err)
5136 return err;
5138 err = got_object_open_as_commit(&commit, repo, commit_id);
5139 if (err)
5140 return err;
5142 err = got_object_id_str(&id_str, commit_id);
5143 if (err) {
5144 err = got_error_from_errno("got_object_id_str");
5145 goto done;
5148 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
5149 if (err)
5150 goto done;
5152 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
5153 refs_str ? refs_str : "", refs_str ? ")" : "");
5154 if (n < 0) {
5155 err = got_error_from_errno("fprintf");
5156 goto done;
5158 outoff += n;
5159 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
5160 if (err)
5161 goto done;
5163 n = fprintf(outfile, "from: %s\n",
5164 got_object_commit_get_author(commit));
5165 if (n < 0) {
5166 err = got_error_from_errno("fprintf");
5167 goto done;
5169 outoff += n;
5170 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5171 if (err)
5172 goto done;
5174 author = got_object_commit_get_author(commit);
5175 committer = got_object_commit_get_committer(commit);
5176 if (strcmp(author, committer) != 0) {
5177 n = fprintf(outfile, "via: %s\n", committer);
5178 if (n < 0) {
5179 err = got_error_from_errno("fprintf");
5180 goto done;
5182 outoff += n;
5183 err = add_line_metadata(lines, nlines, outoff,
5184 GOT_DIFF_LINE_AUTHOR);
5185 if (err)
5186 goto done;
5188 committer_time = got_object_commit_get_committer_time(commit);
5189 datestr = get_datestr(&committer_time, datebuf);
5190 if (datestr) {
5191 n = fprintf(outfile, "date: %s UTC\n", datestr);
5192 if (n < 0) {
5193 err = got_error_from_errno("fprintf");
5194 goto done;
5196 outoff += n;
5197 err = add_line_metadata(lines, nlines, outoff,
5198 GOT_DIFF_LINE_DATE);
5199 if (err)
5200 goto done;
5202 if (got_object_commit_get_nparents(commit) > 1) {
5203 const struct got_object_id_queue *parent_ids;
5204 struct got_object_qid *qid;
5205 int pn = 1;
5206 parent_ids = got_object_commit_get_parent_ids(commit);
5207 STAILQ_FOREACH(qid, parent_ids, entry) {
5208 err = got_object_id_str(&id_str, &qid->id);
5209 if (err)
5210 goto done;
5211 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5212 if (n < 0) {
5213 err = got_error_from_errno("fprintf");
5214 goto done;
5216 outoff += n;
5217 err = add_line_metadata(lines, nlines, outoff,
5218 GOT_DIFF_LINE_META);
5219 if (err)
5220 goto done;
5221 free(id_str);
5222 id_str = NULL;
5226 err = got_object_commit_get_logmsg(&logmsg, commit);
5227 if (err)
5228 goto done;
5229 s = logmsg;
5230 while ((line = strsep(&s, "\n")) != NULL) {
5231 n = fprintf(outfile, "%s\n", line);
5232 if (n < 0) {
5233 err = got_error_from_errno("fprintf");
5234 goto done;
5236 outoff += n;
5237 err = add_line_metadata(lines, nlines, outoff,
5238 GOT_DIFF_LINE_LOGMSG);
5239 if (err)
5240 goto done;
5243 TAILQ_FOREACH(pe, dsa->paths, entry) {
5244 struct got_diff_changed_path *cp = pe->data;
5245 int pad = dsa->max_path_len - pe->path_len + 1;
5247 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5248 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5249 dsa->rm_cols + 1, cp->rm);
5250 if (n < 0) {
5251 err = got_error_from_errno("fprintf");
5252 goto done;
5254 outoff += n;
5255 err = add_line_metadata(lines, nlines, outoff,
5256 GOT_DIFF_LINE_CHANGES);
5257 if (err)
5258 goto done;
5261 fputc('\n', outfile);
5262 outoff++;
5263 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5264 if (err)
5265 goto done;
5267 n = fprintf(outfile,
5268 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5269 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5270 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5271 if (n < 0) {
5272 err = got_error_from_errno("fprintf");
5273 goto done;
5275 outoff += n;
5276 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5277 if (err)
5278 goto done;
5280 fputc('\n', outfile);
5281 outoff++;
5282 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5283 done:
5284 free(id_str);
5285 free(logmsg);
5286 free(refs_str);
5287 got_object_commit_close(commit);
5288 if (err) {
5289 free(*lines);
5290 *lines = NULL;
5291 *nlines = 0;
5293 return err;
5296 static const struct got_error *
5297 create_diff(struct tog_diff_view_state *s)
5299 const struct got_error *err = NULL;
5300 FILE *f = NULL, *tmp_diff_file = NULL;
5301 int obj_type;
5302 struct got_diff_line *lines = NULL;
5303 struct got_pathlist_head changed_paths;
5305 TAILQ_INIT(&changed_paths);
5307 free(s->lines);
5308 s->lines = malloc(sizeof(*s->lines));
5309 if (s->lines == NULL)
5310 return got_error_from_errno("malloc");
5311 s->nlines = 0;
5313 f = got_opentemp();
5314 if (f == NULL) {
5315 err = got_error_from_errno("got_opentemp");
5316 goto done;
5318 tmp_diff_file = got_opentemp();
5319 if (tmp_diff_file == NULL) {
5320 err = got_error_from_errno("got_opentemp");
5321 goto done;
5323 if (s->f && fclose(s->f) == EOF) {
5324 err = got_error_from_errno("fclose");
5325 goto done;
5327 s->f = f;
5329 if (s->id1)
5330 err = got_object_get_type(&obj_type, s->repo, s->id1);
5331 else
5332 err = got_object_get_type(&obj_type, s->repo, s->id2);
5333 if (err)
5334 goto done;
5336 switch (obj_type) {
5337 case GOT_OBJ_TYPE_BLOB:
5338 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5339 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5340 s->label1, s->label2, tog_diff_algo, s->diff_context,
5341 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5342 s->f);
5343 break;
5344 case GOT_OBJ_TYPE_TREE:
5345 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5346 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5347 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5348 s->force_text_diff, NULL, s->repo, s->f);
5349 break;
5350 case GOT_OBJ_TYPE_COMMIT: {
5351 const struct got_object_id_queue *parent_ids;
5352 struct got_object_qid *pid;
5353 struct got_commit_object *commit2;
5354 struct got_reflist_head *refs;
5355 size_t nlines = 0;
5356 struct got_diffstat_cb_arg dsa = {
5357 0, 0, 0, 0, 0, 0,
5358 &changed_paths,
5359 s->ignore_whitespace,
5360 s->force_text_diff,
5361 tog_diff_algo
5364 lines = malloc(sizeof(*lines));
5365 if (lines == NULL) {
5366 err = got_error_from_errno("malloc");
5367 goto done;
5370 /* build diff first in tmp file then append to commit info */
5371 err = got_diff_objects_as_commits(&lines, &nlines,
5372 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5373 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5374 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5375 if (err)
5376 break;
5378 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5379 if (err)
5380 goto done;
5381 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5382 /* Show commit info if we're diffing to a parent/root commit. */
5383 if (s->id1 == NULL) {
5384 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5385 refs, s->repo, s->ignore_whitespace,
5386 s->force_text_diff, &dsa, s->f);
5387 if (err)
5388 goto done;
5389 } else {
5390 parent_ids = got_object_commit_get_parent_ids(commit2);
5391 STAILQ_FOREACH(pid, parent_ids, entry) {
5392 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5393 err = write_commit_info(&s->lines,
5394 &s->nlines, s->id2, refs, s->repo,
5395 s->ignore_whitespace,
5396 s->force_text_diff, &dsa, s->f);
5397 if (err)
5398 goto done;
5399 break;
5403 got_object_commit_close(commit2);
5405 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5406 lines, nlines);
5407 break;
5409 default:
5410 err = got_error(GOT_ERR_OBJ_TYPE);
5411 break;
5413 done:
5414 free(lines);
5415 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5416 if (s->f && fflush(s->f) != 0 && err == NULL)
5417 err = got_error_from_errno("fflush");
5418 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5419 err = got_error_from_errno("fclose");
5420 return err;
5423 static void
5424 diff_view_indicate_progress(struct tog_view *view)
5426 mvwaddstr(view->window, 0, 0, "diffing...");
5427 update_panels();
5428 doupdate();
5431 static const struct got_error *
5432 search_start_diff_view(struct tog_view *view)
5434 struct tog_diff_view_state *s = &view->state.diff;
5436 s->matched_line = 0;
5437 return NULL;
5440 static void
5441 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5442 size_t *nlines, int **first, int **last, int **match, int **selected)
5444 struct tog_diff_view_state *s = &view->state.diff;
5446 *f = s->f;
5447 *nlines = s->nlines;
5448 *line_offsets = NULL;
5449 *match = &s->matched_line;
5450 *first = &s->first_displayed_line;
5451 *last = &s->last_displayed_line;
5452 *selected = &s->selected_line;
5455 static const struct got_error *
5456 search_next_view_match(struct tog_view *view)
5458 const struct got_error *err = NULL;
5459 FILE *f;
5460 int lineno;
5461 char *line = NULL;
5462 size_t linesize = 0;
5463 ssize_t linelen;
5464 off_t *line_offsets;
5465 size_t nlines = 0;
5466 int *first, *last, *match, *selected;
5468 if (!view->search_setup)
5469 return got_error_msg(GOT_ERR_NOT_IMPL,
5470 "view search not supported");
5471 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5472 &match, &selected);
5474 if (!view->searching) {
5475 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5476 return NULL;
5479 if (*match) {
5480 if (view->searching == TOG_SEARCH_FORWARD)
5481 lineno = *first + 1;
5482 else
5483 lineno = *first - 1;
5484 } else
5485 lineno = *first - 1 + *selected;
5487 while (1) {
5488 off_t offset;
5490 if (lineno <= 0 || lineno > nlines) {
5491 if (*match == 0) {
5492 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5493 break;
5496 if (view->searching == TOG_SEARCH_FORWARD)
5497 lineno = 1;
5498 else
5499 lineno = nlines;
5502 offset = view->type == TOG_VIEW_DIFF ?
5503 view->state.diff.lines[lineno - 1].offset :
5504 line_offsets[lineno - 1];
5505 if (fseeko(f, offset, SEEK_SET) != 0) {
5506 free(line);
5507 return got_error_from_errno("fseeko");
5509 linelen = getline(&line, &linesize, f);
5510 if (linelen != -1) {
5511 char *exstr;
5512 err = expand_tab(&exstr, line);
5513 if (err)
5514 break;
5515 if (match_line(exstr, &view->regex, 1,
5516 &view->regmatch)) {
5517 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5518 *match = lineno;
5519 free(exstr);
5520 break;
5522 free(exstr);
5524 if (view->searching == TOG_SEARCH_FORWARD)
5525 lineno++;
5526 else
5527 lineno--;
5529 free(line);
5531 if (*match) {
5532 *first = *match;
5533 *selected = 1;
5536 return err;
5539 static const struct got_error *
5540 close_diff_view(struct tog_view *view)
5542 const struct got_error *err = NULL;
5543 struct tog_diff_view_state *s = &view->state.diff;
5545 free(s->id1);
5546 s->id1 = NULL;
5547 free(s->id2);
5548 s->id2 = NULL;
5549 if (s->f && fclose(s->f) == EOF)
5550 err = got_error_from_errno("fclose");
5551 s->f = NULL;
5552 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5553 err = got_error_from_errno("fclose");
5554 s->f1 = NULL;
5555 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5556 err = got_error_from_errno("fclose");
5557 s->f2 = NULL;
5558 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5559 err = got_error_from_errno("close");
5560 s->fd1 = -1;
5561 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5562 err = got_error_from_errno("close");
5563 s->fd2 = -1;
5564 free(s->lines);
5565 s->lines = NULL;
5566 s->nlines = 0;
5567 return err;
5570 static const struct got_error *
5571 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5572 struct got_object_id *id2, const char *label1, const char *label2,
5573 int diff_context, int ignore_whitespace, int force_text_diff,
5574 struct tog_view *parent_view, struct got_repository *repo)
5576 const struct got_error *err;
5577 struct tog_diff_view_state *s = &view->state.diff;
5579 memset(s, 0, sizeof(*s));
5580 s->fd1 = -1;
5581 s->fd2 = -1;
5583 if (id1 != NULL && id2 != NULL) {
5584 int type1, type2;
5586 err = got_object_get_type(&type1, repo, id1);
5587 if (err)
5588 goto done;
5589 err = got_object_get_type(&type2, repo, id2);
5590 if (err)
5591 goto done;
5593 if (type1 != type2) {
5594 err = got_error(GOT_ERR_OBJ_TYPE);
5595 goto done;
5598 s->first_displayed_line = 1;
5599 s->last_displayed_line = view->nlines;
5600 s->selected_line = 1;
5601 s->repo = repo;
5602 s->id1 = id1;
5603 s->id2 = id2;
5604 s->label1 = label1;
5605 s->label2 = label2;
5607 if (id1) {
5608 s->id1 = got_object_id_dup(id1);
5609 if (s->id1 == NULL) {
5610 err = got_error_from_errno("got_object_id_dup");
5611 goto done;
5613 } else
5614 s->id1 = NULL;
5616 s->id2 = got_object_id_dup(id2);
5617 if (s->id2 == NULL) {
5618 err = got_error_from_errno("got_object_id_dup");
5619 goto done;
5622 s->f1 = got_opentemp();
5623 if (s->f1 == NULL) {
5624 err = got_error_from_errno("got_opentemp");
5625 goto done;
5628 s->f2 = got_opentemp();
5629 if (s->f2 == NULL) {
5630 err = got_error_from_errno("got_opentemp");
5631 goto done;
5634 s->fd1 = got_opentempfd();
5635 if (s->fd1 == -1) {
5636 err = got_error_from_errno("got_opentempfd");
5637 goto done;
5640 s->fd2 = got_opentempfd();
5641 if (s->fd2 == -1) {
5642 err = got_error_from_errno("got_opentempfd");
5643 goto done;
5646 s->diff_context = diff_context;
5647 s->ignore_whitespace = ignore_whitespace;
5648 s->force_text_diff = force_text_diff;
5649 s->parent_view = parent_view;
5650 s->repo = repo;
5652 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5653 int rc;
5655 rc = init_pair(GOT_DIFF_LINE_MINUS,
5656 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5657 if (rc != ERR)
5658 rc = init_pair(GOT_DIFF_LINE_PLUS,
5659 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5660 if (rc != ERR)
5661 rc = init_pair(GOT_DIFF_LINE_HUNK,
5662 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5663 if (rc != ERR)
5664 rc = init_pair(GOT_DIFF_LINE_META,
5665 get_color_value("TOG_COLOR_DIFF_META"), -1);
5666 if (rc != ERR)
5667 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5668 get_color_value("TOG_COLOR_DIFF_META"), -1);
5669 if (rc != ERR)
5670 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5671 get_color_value("TOG_COLOR_DIFF_META"), -1);
5672 if (rc != ERR)
5673 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5674 get_color_value("TOG_COLOR_DIFF_META"), -1);
5675 if (rc != ERR)
5676 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5677 get_color_value("TOG_COLOR_AUTHOR"), -1);
5678 if (rc != ERR)
5679 rc = init_pair(GOT_DIFF_LINE_DATE,
5680 get_color_value("TOG_COLOR_DATE"), -1);
5681 if (rc == ERR) {
5682 err = got_error(GOT_ERR_RANGE);
5683 goto done;
5687 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5688 view_is_splitscreen(view))
5689 show_log_view(parent_view); /* draw border */
5690 diff_view_indicate_progress(view);
5692 err = create_diff(s);
5694 view->show = show_diff_view;
5695 view->input = input_diff_view;
5696 view->reset = reset_diff_view;
5697 view->close = close_diff_view;
5698 view->search_start = search_start_diff_view;
5699 view->search_setup = search_setup_diff_view;
5700 view->search_next = search_next_view_match;
5701 done:
5702 if (err) {
5703 if (view->close == NULL)
5704 close_diff_view(view);
5705 view_close(view);
5707 return err;
5710 static const struct got_error *
5711 show_diff_view(struct tog_view *view)
5713 const struct got_error *err;
5714 struct tog_diff_view_state *s = &view->state.diff;
5715 char *id_str1 = NULL, *id_str2, *header;
5716 const char *label1, *label2;
5718 if (s->id1) {
5719 err = got_object_id_str(&id_str1, s->id1);
5720 if (err)
5721 return err;
5722 label1 = s->label1 ? s->label1 : id_str1;
5723 } else
5724 label1 = "/dev/null";
5726 err = got_object_id_str(&id_str2, s->id2);
5727 if (err)
5728 return err;
5729 label2 = s->label2 ? s->label2 : id_str2;
5731 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5732 err = got_error_from_errno("asprintf");
5733 free(id_str1);
5734 free(id_str2);
5735 return err;
5737 free(id_str1);
5738 free(id_str2);
5740 err = draw_file(view, header);
5741 free(header);
5742 return err;
5745 static const struct got_error *
5746 set_selected_commit(struct tog_diff_view_state *s,
5747 struct commit_queue_entry *entry)
5749 const struct got_error *err;
5750 const struct got_object_id_queue *parent_ids;
5751 struct got_commit_object *selected_commit;
5752 struct got_object_qid *pid;
5754 free(s->id2);
5755 s->id2 = got_object_id_dup(entry->id);
5756 if (s->id2 == NULL)
5757 return got_error_from_errno("got_object_id_dup");
5759 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5760 if (err)
5761 return err;
5762 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5763 free(s->id1);
5764 pid = STAILQ_FIRST(parent_ids);
5765 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5766 got_object_commit_close(selected_commit);
5767 return NULL;
5770 static const struct got_error *
5771 reset_diff_view(struct tog_view *view)
5773 struct tog_diff_view_state *s = &view->state.diff;
5775 view->count = 0;
5776 wclear(view->window);
5777 s->first_displayed_line = 1;
5778 s->last_displayed_line = view->nlines;
5779 s->matched_line = 0;
5780 diff_view_indicate_progress(view);
5781 return create_diff(s);
5784 static void
5785 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5787 int start, i;
5789 i = start = s->first_displayed_line - 1;
5791 while (s->lines[i].type != type) {
5792 if (i == 0)
5793 i = s->nlines - 1;
5794 if (--i == start)
5795 return; /* do nothing, requested type not in file */
5798 s->selected_line = 1;
5799 s->first_displayed_line = i;
5802 static void
5803 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5805 int start, i;
5807 i = start = s->first_displayed_line + 1;
5809 while (s->lines[i].type != type) {
5810 if (i == s->nlines - 1)
5811 i = 0;
5812 if (++i == start)
5813 return; /* do nothing, requested type not in file */
5816 s->selected_line = 1;
5817 s->first_displayed_line = i;
5820 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5821 int, int, int);
5822 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5823 int, int);
5825 static const struct got_error *
5826 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5828 const struct got_error *err = NULL;
5829 struct tog_diff_view_state *s = &view->state.diff;
5830 struct tog_log_view_state *ls;
5831 struct commit_queue_entry *old_selected_entry;
5832 char *line = NULL;
5833 size_t linesize = 0;
5834 ssize_t linelen;
5835 int i, nscroll = view->nlines - 1, up = 0;
5837 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5839 switch (ch) {
5840 case '0':
5841 case '$':
5842 case KEY_RIGHT:
5843 case 'l':
5844 case KEY_LEFT:
5845 case 'h':
5846 horizontal_scroll_input(view, ch);
5847 break;
5848 case 'a':
5849 case 'w':
5850 if (ch == 'a') {
5851 s->force_text_diff = !s->force_text_diff;
5852 view->action = s->force_text_diff ?
5853 "force ASCII text enabled" :
5854 "force ASCII text disabled";
5856 else if (ch == 'w') {
5857 s->ignore_whitespace = !s->ignore_whitespace;
5858 view->action = s->ignore_whitespace ?
5859 "ignore whitespace enabled" :
5860 "ignore whitespace disabled";
5862 err = reset_diff_view(view);
5863 break;
5864 case 'g':
5865 case KEY_HOME:
5866 s->first_displayed_line = 1;
5867 view->count = 0;
5868 break;
5869 case 'G':
5870 case KEY_END:
5871 view->count = 0;
5872 if (s->eof)
5873 break;
5875 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5876 s->eof = 1;
5877 break;
5878 case 'k':
5879 case KEY_UP:
5880 case CTRL('p'):
5881 if (s->first_displayed_line > 1)
5882 s->first_displayed_line--;
5883 else
5884 view->count = 0;
5885 break;
5886 case CTRL('u'):
5887 case 'u':
5888 nscroll /= 2;
5889 /* FALL THROUGH */
5890 case KEY_PPAGE:
5891 case CTRL('b'):
5892 case 'b':
5893 if (s->first_displayed_line == 1) {
5894 view->count = 0;
5895 break;
5897 i = 0;
5898 while (i++ < nscroll && s->first_displayed_line > 1)
5899 s->first_displayed_line--;
5900 break;
5901 case 'j':
5902 case KEY_DOWN:
5903 case CTRL('n'):
5904 if (!s->eof)
5905 s->first_displayed_line++;
5906 else
5907 view->count = 0;
5908 break;
5909 case CTRL('d'):
5910 case 'd':
5911 nscroll /= 2;
5912 /* FALL THROUGH */
5913 case KEY_NPAGE:
5914 case CTRL('f'):
5915 case 'f':
5916 case ' ':
5917 if (s->eof) {
5918 view->count = 0;
5919 break;
5921 i = 0;
5922 while (!s->eof && i++ < nscroll) {
5923 linelen = getline(&line, &linesize, s->f);
5924 s->first_displayed_line++;
5925 if (linelen == -1) {
5926 if (feof(s->f)) {
5927 s->eof = 1;
5928 } else
5929 err = got_ferror(s->f, GOT_ERR_IO);
5930 break;
5933 free(line);
5934 break;
5935 case '(':
5936 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5937 break;
5938 case ')':
5939 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5940 break;
5941 case '{':
5942 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5943 break;
5944 case '}':
5945 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5946 break;
5947 case '[':
5948 if (s->diff_context > 0) {
5949 s->diff_context--;
5950 s->matched_line = 0;
5951 diff_view_indicate_progress(view);
5952 err = create_diff(s);
5953 if (s->first_displayed_line + view->nlines - 1 >
5954 s->nlines) {
5955 s->first_displayed_line = 1;
5956 s->last_displayed_line = view->nlines;
5958 } else
5959 view->count = 0;
5960 break;
5961 case ']':
5962 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5963 s->diff_context++;
5964 s->matched_line = 0;
5965 diff_view_indicate_progress(view);
5966 err = create_diff(s);
5967 } else
5968 view->count = 0;
5969 break;
5970 case '<':
5971 case ',':
5972 case 'K':
5973 up = 1;
5974 /* FALL THROUGH */
5975 case '>':
5976 case '.':
5977 case 'J':
5978 if (s->parent_view == NULL) {
5979 view->count = 0;
5980 break;
5982 s->parent_view->count = view->count;
5984 if (s->parent_view->type == TOG_VIEW_LOG) {
5985 ls = &s->parent_view->state.log;
5986 old_selected_entry = ls->selected_entry;
5988 err = input_log_view(NULL, s->parent_view,
5989 up ? KEY_UP : KEY_DOWN);
5990 if (err)
5991 break;
5992 view->count = s->parent_view->count;
5994 if (old_selected_entry == ls->selected_entry)
5995 break;
5997 err = set_selected_commit(s, ls->selected_entry);
5998 if (err)
5999 break;
6000 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
6001 struct tog_blame_view_state *bs;
6002 struct got_object_id *id, *prev_id;
6004 bs = &s->parent_view->state.blame;
6005 prev_id = get_annotation_for_line(bs->blame.lines,
6006 bs->blame.nlines, bs->last_diffed_line);
6008 err = input_blame_view(&view, s->parent_view,
6009 up ? KEY_UP : KEY_DOWN);
6010 if (err)
6011 break;
6012 view->count = s->parent_view->count;
6014 if (prev_id == NULL)
6015 break;
6016 id = get_selected_commit_id(bs->blame.lines,
6017 bs->blame.nlines, bs->first_displayed_line,
6018 bs->selected_line);
6019 if (id == NULL)
6020 break;
6022 if (!got_object_id_cmp(prev_id, id))
6023 break;
6025 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
6026 if (err)
6027 break;
6029 s->first_displayed_line = 1;
6030 s->last_displayed_line = view->nlines;
6031 s->matched_line = 0;
6032 view->x = 0;
6034 diff_view_indicate_progress(view);
6035 err = create_diff(s);
6036 break;
6037 default:
6038 view->count = 0;
6039 break;
6042 return err;
6045 static const struct got_error *
6046 cmd_diff(int argc, char *argv[])
6048 const struct got_error *error;
6049 struct got_repository *repo = NULL;
6050 struct got_worktree *worktree = NULL;
6051 struct got_object_id *id1 = NULL, *id2 = NULL;
6052 char *repo_path = NULL, *cwd = NULL;
6053 char *id_str1 = NULL, *id_str2 = NULL;
6054 char *keyword_idstr1 = NULL, *keyword_idstr2 = NULL;
6055 char *label1 = NULL, *label2 = NULL;
6056 int diff_context = 3, ignore_whitespace = 0;
6057 int ch, force_text_diff = 0;
6058 const char *errstr;
6059 struct tog_view *view;
6060 int *pack_fds = NULL;
6062 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
6063 switch (ch) {
6064 case 'a':
6065 force_text_diff = 1;
6066 break;
6067 case 'C':
6068 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
6069 &errstr);
6070 if (errstr != NULL)
6071 errx(1, "number of context lines is %s: %s",
6072 errstr, errstr);
6073 break;
6074 case 'r':
6075 repo_path = realpath(optarg, NULL);
6076 if (repo_path == NULL)
6077 return got_error_from_errno2("realpath",
6078 optarg);
6079 got_path_strip_trailing_slashes(repo_path);
6080 break;
6081 case 'w':
6082 ignore_whitespace = 1;
6083 break;
6084 default:
6085 usage_diff();
6086 /* NOTREACHED */
6090 argc -= optind;
6091 argv += optind;
6093 if (argc == 0) {
6094 usage_diff(); /* TODO show local worktree changes */
6095 } else if (argc == 2) {
6096 id_str1 = argv[0];
6097 id_str2 = argv[1];
6098 } else
6099 usage_diff();
6101 error = got_repo_pack_fds_open(&pack_fds);
6102 if (error)
6103 goto done;
6105 if (repo_path == NULL) {
6106 cwd = getcwd(NULL, 0);
6107 if (cwd == NULL)
6108 return got_error_from_errno("getcwd");
6109 error = got_worktree_open(&worktree, cwd, NULL);
6110 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6111 goto done;
6112 if (worktree)
6113 repo_path =
6114 strdup(got_worktree_get_repo_path(worktree));
6115 else
6116 repo_path = strdup(cwd);
6117 if (repo_path == NULL) {
6118 error = got_error_from_errno("strdup");
6119 goto done;
6123 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6124 if (error)
6125 goto done;
6127 init_curses();
6129 error = apply_unveil(got_repo_get_path(repo), NULL);
6130 if (error)
6131 goto done;
6133 error = tog_load_refs(repo, 0);
6134 if (error)
6135 goto done;
6137 if (id_str1 != NULL) {
6138 error = got_keyword_to_idstr(&keyword_idstr1, id_str1,
6139 repo, worktree);
6140 if (error != NULL)
6141 goto done;
6142 if (keyword_idstr1 != NULL)
6143 id_str1 = keyword_idstr1;
6145 if (id_str2 != NULL) {
6146 error = got_keyword_to_idstr(&keyword_idstr2, id_str2,
6147 repo, worktree);
6148 if (error != NULL)
6149 goto done;
6150 if (keyword_idstr2 != NULL)
6151 id_str2 = keyword_idstr2;
6154 error = got_repo_match_object_id(&id1, &label1, id_str1,
6155 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6156 if (error)
6157 goto done;
6159 error = got_repo_match_object_id(&id2, &label2, id_str2,
6160 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6161 if (error)
6162 goto done;
6164 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
6165 if (view == NULL) {
6166 error = got_error_from_errno("view_open");
6167 goto done;
6169 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
6170 ignore_whitespace, force_text_diff, NULL, repo);
6171 if (error)
6172 goto done;
6174 if (worktree) {
6175 error = set_tog_base_commit(repo, worktree);
6176 if (error != NULL)
6177 goto done;
6180 error = view_loop(view);
6182 done:
6183 free(tog_base_commit.id);
6184 free(keyword_idstr1);
6185 free(keyword_idstr2);
6186 free(label1);
6187 free(label2);
6188 free(repo_path);
6189 free(cwd);
6190 if (repo) {
6191 const struct got_error *close_err = got_repo_close(repo);
6192 if (error == NULL)
6193 error = close_err;
6195 if (worktree)
6196 got_worktree_close(worktree);
6197 if (pack_fds) {
6198 const struct got_error *pack_err =
6199 got_repo_pack_fds_close(pack_fds);
6200 if (error == NULL)
6201 error = pack_err;
6203 tog_free_refs();
6204 return error;
6207 __dead static void
6208 usage_blame(void)
6210 endwin();
6211 fprintf(stderr,
6212 "usage: %s blame [-c commit] [-r repository-path] path\n",
6213 getprogname());
6214 exit(1);
6217 struct tog_blame_line {
6218 int annotated;
6219 struct got_object_id *id;
6222 static const struct got_error *
6223 draw_blame(struct tog_view *view)
6225 struct tog_blame_view_state *s = &view->state.blame;
6226 struct tog_blame *blame = &s->blame;
6227 regmatch_t *regmatch = &view->regmatch;
6228 const struct got_error *err;
6229 int lineno = 0, nprinted = 0;
6230 char *line = NULL;
6231 size_t linesize = 0;
6232 ssize_t linelen;
6233 wchar_t *wline;
6234 int width;
6235 struct tog_blame_line *blame_line;
6236 struct got_object_id *prev_id = NULL;
6237 char *id_str;
6238 struct tog_color *tc;
6240 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6241 if (err)
6242 return err;
6244 rewind(blame->f);
6245 werase(view->window);
6247 if (asprintf(&line, "commit %s", id_str) == -1) {
6248 err = got_error_from_errno("asprintf");
6249 free(id_str);
6250 return err;
6253 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6254 free(line);
6255 line = NULL;
6256 if (err)
6257 return err;
6258 if (view_needs_focus_indication(view))
6259 wstandout(view->window);
6260 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6261 if (tc)
6262 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6263 waddwstr(view->window, wline);
6264 while (width++ < view->ncols)
6265 waddch(view->window, ' ');
6266 if (tc)
6267 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6268 if (view_needs_focus_indication(view))
6269 wstandend(view->window);
6270 free(wline);
6271 wline = NULL;
6273 if (view->gline > blame->nlines)
6274 view->gline = blame->nlines;
6276 if (tog_io.wait_for_ui) {
6277 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6278 int rc;
6280 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6281 if (rc)
6282 return got_error_set_errno(rc, "pthread_cond_wait");
6283 tog_io.wait_for_ui = 0;
6286 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6287 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6288 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6289 free(id_str);
6290 return got_error_from_errno("asprintf");
6292 free(id_str);
6293 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6294 free(line);
6295 line = NULL;
6296 if (err)
6297 return err;
6298 waddwstr(view->window, wline);
6299 free(wline);
6300 wline = NULL;
6301 if (width < view->ncols - 1)
6302 waddch(view->window, '\n');
6304 s->eof = 0;
6305 view->maxx = 0;
6306 while (nprinted < view->nlines - 2) {
6307 linelen = getline(&line, &linesize, blame->f);
6308 if (linelen == -1) {
6309 if (feof(blame->f)) {
6310 s->eof = 1;
6311 break;
6313 free(line);
6314 return got_ferror(blame->f, GOT_ERR_IO);
6316 if (++lineno < s->first_displayed_line)
6317 continue;
6318 if (view->gline && !gotoline(view, &lineno, &nprinted))
6319 continue;
6321 /* Set view->maxx based on full line length. */
6322 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6323 if (err) {
6324 free(line);
6325 return err;
6327 free(wline);
6328 wline = NULL;
6329 view->maxx = MAX(view->maxx, width);
6331 if (nprinted == s->selected_line - 1)
6332 wstandout(view->window);
6334 if (blame->nlines > 0) {
6335 blame_line = &blame->lines[lineno - 1];
6336 if (blame_line->annotated && prev_id &&
6337 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6338 !(nprinted == s->selected_line - 1)) {
6339 waddstr(view->window, " ");
6340 } else if (blame_line->annotated) {
6341 char *id_str;
6342 err = got_object_id_str(&id_str,
6343 blame_line->id);
6344 if (err) {
6345 free(line);
6346 return err;
6348 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6349 if (tc)
6350 wattr_on(view->window,
6351 COLOR_PAIR(tc->colorpair), NULL);
6352 wprintw(view->window, "%.8s", id_str);
6353 if (tc)
6354 wattr_off(view->window,
6355 COLOR_PAIR(tc->colorpair), NULL);
6356 free(id_str);
6357 prev_id = blame_line->id;
6358 } else {
6359 waddstr(view->window, "........");
6360 prev_id = NULL;
6362 } else {
6363 waddstr(view->window, "........");
6364 prev_id = NULL;
6367 if (nprinted == s->selected_line - 1)
6368 wstandend(view->window);
6369 waddstr(view->window, " ");
6371 if (view->ncols <= 9) {
6372 width = 9;
6373 } else if (s->first_displayed_line + nprinted ==
6374 s->matched_line &&
6375 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6376 err = add_matched_line(&width, line, view->ncols - 9, 9,
6377 view->window, view->x, regmatch);
6378 if (err) {
6379 free(line);
6380 return err;
6382 width += 9;
6383 } else {
6384 int skip;
6385 err = format_line(&wline, &width, &skip, line,
6386 view->x, view->ncols - 9, 9, 1);
6387 if (err) {
6388 free(line);
6389 return err;
6391 waddwstr(view->window, &wline[skip]);
6392 width += 9;
6393 free(wline);
6394 wline = NULL;
6397 if (width <= view->ncols - 1)
6398 waddch(view->window, '\n');
6399 if (++nprinted == 1)
6400 s->first_displayed_line = lineno;
6402 free(line);
6403 s->last_displayed_line = lineno;
6405 view_border(view);
6407 return NULL;
6410 static const struct got_error *
6411 blame_cb(void *arg, int nlines, int lineno,
6412 struct got_commit_object *commit, struct got_object_id *id)
6414 const struct got_error *err = NULL;
6415 struct tog_blame_cb_args *a = arg;
6416 struct tog_blame_line *line;
6417 int errcode;
6419 if (nlines != a->nlines ||
6420 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6421 return got_error(GOT_ERR_RANGE);
6423 errcode = pthread_mutex_lock(&tog_mutex);
6424 if (errcode)
6425 return got_error_set_errno(errcode, "pthread_mutex_lock");
6427 if (*a->quit) { /* user has quit the blame view */
6428 err = got_error(GOT_ERR_ITER_COMPLETED);
6429 goto done;
6432 if (lineno == -1)
6433 goto done; /* no change in this commit */
6435 line = &a->lines[lineno - 1];
6436 if (line->annotated)
6437 goto done;
6439 line->id = got_object_id_dup(id);
6440 if (line->id == NULL) {
6441 err = got_error_from_errno("got_object_id_dup");
6442 goto done;
6444 line->annotated = 1;
6445 done:
6446 errcode = pthread_mutex_unlock(&tog_mutex);
6447 if (errcode)
6448 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6449 return err;
6452 static void *
6453 blame_thread(void *arg)
6455 const struct got_error *err, *close_err;
6456 struct tog_blame_thread_args *ta = arg;
6457 struct tog_blame_cb_args *a = ta->cb_args;
6458 int errcode, fd1 = -1, fd2 = -1;
6459 FILE *f1 = NULL, *f2 = NULL;
6461 fd1 = got_opentempfd();
6462 if (fd1 == -1)
6463 return (void *)got_error_from_errno("got_opentempfd");
6465 fd2 = got_opentempfd();
6466 if (fd2 == -1) {
6467 err = got_error_from_errno("got_opentempfd");
6468 goto done;
6471 f1 = got_opentemp();
6472 if (f1 == NULL) {
6473 err = (void *)got_error_from_errno("got_opentemp");
6474 goto done;
6476 f2 = got_opentemp();
6477 if (f2 == NULL) {
6478 err = (void *)got_error_from_errno("got_opentemp");
6479 goto done;
6482 err = block_signals_used_by_main_thread();
6483 if (err)
6484 goto done;
6486 err = got_blame(ta->path, a->commit_id, ta->repo,
6487 tog_diff_algo, blame_cb, ta->cb_args,
6488 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6489 if (err && err->code == GOT_ERR_CANCELLED)
6490 err = NULL;
6492 errcode = pthread_mutex_lock(&tog_mutex);
6493 if (errcode) {
6494 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6495 goto done;
6498 close_err = got_repo_close(ta->repo);
6499 if (err == NULL)
6500 err = close_err;
6501 ta->repo = NULL;
6502 *ta->complete = 1;
6504 if (tog_io.wait_for_ui) {
6505 errcode = pthread_cond_signal(&ta->blame_complete);
6506 if (errcode && err == NULL)
6507 err = got_error_set_errno(errcode,
6508 "pthread_cond_signal");
6511 errcode = pthread_mutex_unlock(&tog_mutex);
6512 if (errcode && err == NULL)
6513 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6515 done:
6516 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6517 err = got_error_from_errno("close");
6518 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6519 err = got_error_from_errno("close");
6520 if (f1 && fclose(f1) == EOF && err == NULL)
6521 err = got_error_from_errno("fclose");
6522 if (f2 && fclose(f2) == EOF && err == NULL)
6523 err = got_error_from_errno("fclose");
6525 return (void *)err;
6528 static struct got_object_id *
6529 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6530 int first_displayed_line, int selected_line)
6532 struct tog_blame_line *line;
6534 if (nlines <= 0)
6535 return NULL;
6537 line = &lines[first_displayed_line - 1 + selected_line - 1];
6538 if (!line->annotated)
6539 return NULL;
6541 return line->id;
6544 static struct got_object_id *
6545 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6546 int lineno)
6548 struct tog_blame_line *line;
6550 if (nlines <= 0 || lineno >= nlines)
6551 return NULL;
6553 line = &lines[lineno - 1];
6554 if (!line->annotated)
6555 return NULL;
6557 return line->id;
6560 static const struct got_error *
6561 stop_blame(struct tog_blame *blame)
6563 const struct got_error *err = NULL;
6564 int i;
6566 if (blame->thread) {
6567 int errcode;
6568 errcode = pthread_mutex_unlock(&tog_mutex);
6569 if (errcode)
6570 return got_error_set_errno(errcode,
6571 "pthread_mutex_unlock");
6572 errcode = pthread_join(blame->thread, (void **)&err);
6573 if (errcode)
6574 return got_error_set_errno(errcode, "pthread_join");
6575 errcode = pthread_mutex_lock(&tog_mutex);
6576 if (errcode)
6577 return got_error_set_errno(errcode,
6578 "pthread_mutex_lock");
6579 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6580 err = NULL;
6581 blame->thread = 0; //NULL;
6583 if (blame->thread_args.repo) {
6584 const struct got_error *close_err;
6585 close_err = got_repo_close(blame->thread_args.repo);
6586 if (err == NULL)
6587 err = close_err;
6588 blame->thread_args.repo = NULL;
6590 if (blame->f) {
6591 if (fclose(blame->f) == EOF && err == NULL)
6592 err = got_error_from_errno("fclose");
6593 blame->f = NULL;
6595 if (blame->lines) {
6596 for (i = 0; i < blame->nlines; i++)
6597 free(blame->lines[i].id);
6598 free(blame->lines);
6599 blame->lines = NULL;
6601 free(blame->cb_args.commit_id);
6602 blame->cb_args.commit_id = NULL;
6603 if (blame->pack_fds) {
6604 const struct got_error *pack_err =
6605 got_repo_pack_fds_close(blame->pack_fds);
6606 if (err == NULL)
6607 err = pack_err;
6608 blame->pack_fds = NULL;
6610 return err;
6613 static const struct got_error *
6614 cancel_blame_view(void *arg)
6616 const struct got_error *err = NULL;
6617 int *done = arg;
6618 int errcode;
6620 errcode = pthread_mutex_lock(&tog_mutex);
6621 if (errcode)
6622 return got_error_set_errno(errcode,
6623 "pthread_mutex_unlock");
6625 if (*done)
6626 err = got_error(GOT_ERR_CANCELLED);
6628 errcode = pthread_mutex_unlock(&tog_mutex);
6629 if (errcode)
6630 return got_error_set_errno(errcode,
6631 "pthread_mutex_lock");
6633 return err;
6636 static const struct got_error *
6637 run_blame(struct tog_view *view)
6639 struct tog_blame_view_state *s = &view->state.blame;
6640 struct tog_blame *blame = &s->blame;
6641 const struct got_error *err = NULL;
6642 struct got_commit_object *commit = NULL;
6643 struct got_blob_object *blob = NULL;
6644 struct got_repository *thread_repo = NULL;
6645 struct got_object_id *obj_id = NULL;
6646 int obj_type, fd = -1;
6647 int *pack_fds = NULL;
6649 err = got_object_open_as_commit(&commit, s->repo,
6650 &s->blamed_commit->id);
6651 if (err)
6652 return err;
6654 fd = got_opentempfd();
6655 if (fd == -1) {
6656 err = got_error_from_errno("got_opentempfd");
6657 goto done;
6660 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6661 if (err)
6662 goto done;
6664 err = got_object_get_type(&obj_type, s->repo, obj_id);
6665 if (err)
6666 goto done;
6668 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6669 err = got_error(GOT_ERR_OBJ_TYPE);
6670 goto done;
6673 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6674 if (err)
6675 goto done;
6676 blame->f = got_opentemp();
6677 if (blame->f == NULL) {
6678 err = got_error_from_errno("got_opentemp");
6679 goto done;
6681 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6682 &blame->line_offsets, blame->f, blob);
6683 if (err)
6684 goto done;
6685 if (blame->nlines == 0) {
6686 s->blame_complete = 1;
6687 goto done;
6690 /* Don't include \n at EOF in the blame line count. */
6691 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6692 blame->nlines--;
6694 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6695 if (blame->lines == NULL) {
6696 err = got_error_from_errno("calloc");
6697 goto done;
6700 err = got_repo_pack_fds_open(&pack_fds);
6701 if (err)
6702 goto done;
6703 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6704 pack_fds);
6705 if (err)
6706 goto done;
6708 blame->pack_fds = pack_fds;
6709 blame->cb_args.view = view;
6710 blame->cb_args.lines = blame->lines;
6711 blame->cb_args.nlines = blame->nlines;
6712 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6713 if (blame->cb_args.commit_id == NULL) {
6714 err = got_error_from_errno("got_object_id_dup");
6715 goto done;
6717 blame->cb_args.quit = &s->done;
6719 blame->thread_args.path = s->path;
6720 blame->thread_args.repo = thread_repo;
6721 blame->thread_args.cb_args = &blame->cb_args;
6722 blame->thread_args.complete = &s->blame_complete;
6723 blame->thread_args.cancel_cb = cancel_blame_view;
6724 blame->thread_args.cancel_arg = &s->done;
6725 s->blame_complete = 0;
6727 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6728 s->first_displayed_line = 1;
6729 s->last_displayed_line = view->nlines;
6730 s->selected_line = 1;
6732 s->matched_line = 0;
6734 done:
6735 if (commit)
6736 got_object_commit_close(commit);
6737 if (fd != -1 && close(fd) == -1 && err == NULL)
6738 err = got_error_from_errno("close");
6739 if (blob)
6740 got_object_blob_close(blob);
6741 free(obj_id);
6742 if (err)
6743 stop_blame(blame);
6744 return err;
6747 static const struct got_error *
6748 open_blame_view(struct tog_view *view, char *path,
6749 struct got_object_id *commit_id, struct got_repository *repo)
6751 const struct got_error *err = NULL;
6752 struct tog_blame_view_state *s = &view->state.blame;
6754 STAILQ_INIT(&s->blamed_commits);
6756 s->path = strdup(path);
6757 if (s->path == NULL)
6758 return got_error_from_errno("strdup");
6760 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6761 if (err) {
6762 free(s->path);
6763 return err;
6766 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6767 s->first_displayed_line = 1;
6768 s->last_displayed_line = view->nlines;
6769 s->selected_line = 1;
6770 s->blame_complete = 0;
6771 s->repo = repo;
6772 s->commit_id = commit_id;
6773 memset(&s->blame, 0, sizeof(s->blame));
6775 STAILQ_INIT(&s->colors);
6776 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6777 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6778 get_color_value("TOG_COLOR_COMMIT"));
6779 if (err)
6780 return err;
6783 view->show = show_blame_view;
6784 view->input = input_blame_view;
6785 view->reset = reset_blame_view;
6786 view->close = close_blame_view;
6787 view->search_start = search_start_blame_view;
6788 view->search_setup = search_setup_blame_view;
6789 view->search_next = search_next_view_match;
6791 if (using_mock_io) {
6792 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6793 int rc;
6795 rc = pthread_cond_init(&bta->blame_complete, NULL);
6796 if (rc)
6797 return got_error_set_errno(rc, "pthread_cond_init");
6800 return run_blame(view);
6803 static const struct got_error *
6804 close_blame_view(struct tog_view *view)
6806 const struct got_error *err = NULL;
6807 struct tog_blame_view_state *s = &view->state.blame;
6809 if (s->blame.thread)
6810 err = stop_blame(&s->blame);
6812 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6813 struct got_object_qid *blamed_commit;
6814 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6815 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6816 got_object_qid_free(blamed_commit);
6819 if (using_mock_io) {
6820 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6821 int rc;
6823 rc = pthread_cond_destroy(&bta->blame_complete);
6824 if (rc && err == NULL)
6825 err = got_error_set_errno(rc, "pthread_cond_destroy");
6828 free(s->path);
6829 free_colors(&s->colors);
6830 return err;
6833 static const struct got_error *
6834 search_start_blame_view(struct tog_view *view)
6836 struct tog_blame_view_state *s = &view->state.blame;
6838 s->matched_line = 0;
6839 return NULL;
6842 static void
6843 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6844 size_t *nlines, int **first, int **last, int **match, int **selected)
6846 struct tog_blame_view_state *s = &view->state.blame;
6848 *f = s->blame.f;
6849 *nlines = s->blame.nlines;
6850 *line_offsets = s->blame.line_offsets;
6851 *match = &s->matched_line;
6852 *first = &s->first_displayed_line;
6853 *last = &s->last_displayed_line;
6854 *selected = &s->selected_line;
6857 static const struct got_error *
6858 show_blame_view(struct tog_view *view)
6860 const struct got_error *err = NULL;
6861 struct tog_blame_view_state *s = &view->state.blame;
6862 int errcode;
6864 if (s->blame.thread == 0 && !s->blame_complete) {
6865 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6866 &s->blame.thread_args);
6867 if (errcode)
6868 return got_error_set_errno(errcode, "pthread_create");
6870 if (!using_mock_io)
6871 halfdelay(1); /* fast refresh while annotating */
6874 if (s->blame_complete && !using_mock_io)
6875 halfdelay(10); /* disable fast refresh */
6877 err = draw_blame(view);
6879 view_border(view);
6880 return err;
6883 static const struct got_error *
6884 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6885 struct got_repository *repo, struct got_object_id *id)
6887 struct tog_view *log_view;
6888 const struct got_error *err = NULL;
6890 *new_view = NULL;
6892 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6893 if (log_view == NULL)
6894 return got_error_from_errno("view_open");
6896 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0, NULL);
6897 if (err)
6898 view_close(log_view);
6899 else
6900 *new_view = log_view;
6902 return err;
6905 static const struct got_error *
6906 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6908 const struct got_error *err = NULL, *thread_err = NULL;
6909 struct tog_view *diff_view;
6910 struct tog_blame_view_state *s = &view->state.blame;
6911 int eos, nscroll, begin_y = 0, begin_x = 0;
6913 eos = nscroll = view->nlines - 2;
6914 if (view_is_hsplit_top(view))
6915 --eos; /* border */
6917 switch (ch) {
6918 case '0':
6919 case '$':
6920 case KEY_RIGHT:
6921 case 'l':
6922 case KEY_LEFT:
6923 case 'h':
6924 horizontal_scroll_input(view, ch);
6925 break;
6926 case 'q':
6927 s->done = 1;
6928 break;
6929 case 'g':
6930 case KEY_HOME:
6931 s->selected_line = 1;
6932 s->first_displayed_line = 1;
6933 view->count = 0;
6934 break;
6935 case 'G':
6936 case KEY_END:
6937 if (s->blame.nlines < eos) {
6938 s->selected_line = s->blame.nlines;
6939 s->first_displayed_line = 1;
6940 } else {
6941 s->selected_line = eos;
6942 s->first_displayed_line = s->blame.nlines - (eos - 1);
6944 view->count = 0;
6945 break;
6946 case 'k':
6947 case KEY_UP:
6948 case CTRL('p'):
6949 if (s->selected_line > 1)
6950 s->selected_line--;
6951 else if (s->selected_line == 1 &&
6952 s->first_displayed_line > 1)
6953 s->first_displayed_line--;
6954 else
6955 view->count = 0;
6956 break;
6957 case CTRL('u'):
6958 case 'u':
6959 nscroll /= 2;
6960 /* FALL THROUGH */
6961 case KEY_PPAGE:
6962 case CTRL('b'):
6963 case 'b':
6964 if (s->first_displayed_line == 1) {
6965 if (view->count > 1)
6966 nscroll += nscroll;
6967 s->selected_line = MAX(1, s->selected_line - nscroll);
6968 view->count = 0;
6969 break;
6971 if (s->first_displayed_line > nscroll)
6972 s->first_displayed_line -= nscroll;
6973 else
6974 s->first_displayed_line = 1;
6975 break;
6976 case 'j':
6977 case KEY_DOWN:
6978 case CTRL('n'):
6979 if (s->selected_line < eos && s->first_displayed_line +
6980 s->selected_line <= s->blame.nlines)
6981 s->selected_line++;
6982 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6983 s->first_displayed_line++;
6984 else
6985 view->count = 0;
6986 break;
6987 case 'c':
6988 case 'p': {
6989 struct got_object_id *id = NULL;
6991 view->count = 0;
6992 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6993 s->first_displayed_line, s->selected_line);
6994 if (id == NULL)
6995 break;
6996 if (ch == 'p') {
6997 struct got_commit_object *commit, *pcommit;
6998 struct got_object_qid *pid;
6999 struct got_object_id *blob_id = NULL;
7000 int obj_type;
7001 err = got_object_open_as_commit(&commit,
7002 s->repo, id);
7003 if (err)
7004 break;
7005 pid = STAILQ_FIRST(
7006 got_object_commit_get_parent_ids(commit));
7007 if (pid == NULL) {
7008 got_object_commit_close(commit);
7009 break;
7011 /* Check if path history ends here. */
7012 err = got_object_open_as_commit(&pcommit,
7013 s->repo, &pid->id);
7014 if (err)
7015 break;
7016 err = got_object_id_by_path(&blob_id, s->repo,
7017 pcommit, s->path);
7018 got_object_commit_close(pcommit);
7019 if (err) {
7020 if (err->code == GOT_ERR_NO_TREE_ENTRY)
7021 err = NULL;
7022 got_object_commit_close(commit);
7023 break;
7025 err = got_object_get_type(&obj_type, s->repo,
7026 blob_id);
7027 free(blob_id);
7028 /* Can't blame non-blob type objects. */
7029 if (obj_type != GOT_OBJ_TYPE_BLOB) {
7030 got_object_commit_close(commit);
7031 break;
7033 err = got_object_qid_alloc(&s->blamed_commit,
7034 &pid->id);
7035 got_object_commit_close(commit);
7036 } else {
7037 if (got_object_id_cmp(id,
7038 &s->blamed_commit->id) == 0)
7039 break;
7040 err = got_object_qid_alloc(&s->blamed_commit,
7041 id);
7043 if (err)
7044 break;
7045 s->done = 1;
7046 thread_err = stop_blame(&s->blame);
7047 s->done = 0;
7048 if (thread_err)
7049 break;
7050 STAILQ_INSERT_HEAD(&s->blamed_commits,
7051 s->blamed_commit, entry);
7052 err = run_blame(view);
7053 if (err)
7054 break;
7055 break;
7057 case 'C': {
7058 struct got_object_qid *first;
7060 view->count = 0;
7061 first = STAILQ_FIRST(&s->blamed_commits);
7062 if (!got_object_id_cmp(&first->id, s->commit_id))
7063 break;
7064 s->done = 1;
7065 thread_err = stop_blame(&s->blame);
7066 s->done = 0;
7067 if (thread_err)
7068 break;
7069 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
7070 got_object_qid_free(s->blamed_commit);
7071 s->blamed_commit =
7072 STAILQ_FIRST(&s->blamed_commits);
7073 err = run_blame(view);
7074 if (err)
7075 break;
7076 break;
7078 case 'L':
7079 view->count = 0;
7080 s->id_to_log = get_selected_commit_id(s->blame.lines,
7081 s->blame.nlines, s->first_displayed_line, s->selected_line);
7082 if (s->id_to_log)
7083 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7084 break;
7085 case KEY_ENTER:
7086 case '\r': {
7087 struct got_object_id *id = NULL;
7088 struct got_object_qid *pid;
7089 struct got_commit_object *commit = NULL;
7091 view->count = 0;
7092 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7093 s->first_displayed_line, s->selected_line);
7094 if (id == NULL)
7095 break;
7096 err = got_object_open_as_commit(&commit, s->repo, id);
7097 if (err)
7098 break;
7099 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7100 if (*new_view) {
7101 /* traversed from diff view, release diff resources */
7102 err = close_diff_view(*new_view);
7103 if (err)
7104 break;
7105 diff_view = *new_view;
7106 } else {
7107 if (view_is_parent_view(view))
7108 view_get_split(view, &begin_y, &begin_x);
7110 diff_view = view_open(0, 0, begin_y, begin_x,
7111 TOG_VIEW_DIFF);
7112 if (diff_view == NULL) {
7113 got_object_commit_close(commit);
7114 err = got_error_from_errno("view_open");
7115 break;
7118 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
7119 id, NULL, NULL, 3, 0, 0, view, s->repo);
7120 got_object_commit_close(commit);
7121 if (err)
7122 break;
7123 s->last_diffed_line = s->first_displayed_line - 1 +
7124 s->selected_line;
7125 if (*new_view)
7126 break; /* still open from active diff view */
7127 if (view_is_parent_view(view) &&
7128 view->mode == TOG_VIEW_SPLIT_HRZN) {
7129 err = view_init_hsplit(view, begin_y);
7130 if (err)
7131 break;
7134 view->focussed = 0;
7135 diff_view->focussed = 1;
7136 diff_view->mode = view->mode;
7137 diff_view->nlines = view->lines - begin_y;
7138 if (view_is_parent_view(view)) {
7139 view_transfer_size(diff_view, view);
7140 err = view_close_child(view);
7141 if (err)
7142 break;
7143 err = view_set_child(view, diff_view);
7144 if (err)
7145 break;
7146 view->focus_child = 1;
7147 } else
7148 *new_view = diff_view;
7149 if (err)
7150 break;
7151 break;
7153 case CTRL('d'):
7154 case 'd':
7155 nscroll /= 2;
7156 /* FALL THROUGH */
7157 case KEY_NPAGE:
7158 case CTRL('f'):
7159 case 'f':
7160 case ' ':
7161 if (s->last_displayed_line >= s->blame.nlines &&
7162 s->selected_line >= MIN(s->blame.nlines,
7163 view->nlines - 2)) {
7164 view->count = 0;
7165 break;
7167 if (s->last_displayed_line >= s->blame.nlines &&
7168 s->selected_line < view->nlines - 2) {
7169 s->selected_line +=
7170 MIN(nscroll, s->last_displayed_line -
7171 s->first_displayed_line - s->selected_line + 1);
7173 if (s->last_displayed_line + nscroll <= s->blame.nlines)
7174 s->first_displayed_line += nscroll;
7175 else
7176 s->first_displayed_line =
7177 s->blame.nlines - (view->nlines - 3);
7178 break;
7179 case KEY_RESIZE:
7180 if (s->selected_line > view->nlines - 2) {
7181 s->selected_line = MIN(s->blame.nlines,
7182 view->nlines - 2);
7184 break;
7185 default:
7186 view->count = 0;
7187 break;
7189 return thread_err ? thread_err : err;
7192 static const struct got_error *
7193 reset_blame_view(struct tog_view *view)
7195 const struct got_error *err;
7196 struct tog_blame_view_state *s = &view->state.blame;
7198 view->count = 0;
7199 s->done = 1;
7200 err = stop_blame(&s->blame);
7201 s->done = 0;
7202 if (err)
7203 return err;
7204 return run_blame(view);
7207 static const struct got_error *
7208 cmd_blame(int argc, char *argv[])
7210 const struct got_error *error;
7211 struct got_repository *repo = NULL;
7212 struct got_worktree *worktree = NULL;
7213 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7214 char *link_target = NULL;
7215 struct got_object_id *commit_id = NULL;
7216 struct got_commit_object *commit = NULL;
7217 char *keyword_idstr = NULL, *commit_id_str = NULL;
7218 int ch;
7219 struct tog_view *view = NULL;
7220 int *pack_fds = NULL;
7222 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7223 switch (ch) {
7224 case 'c':
7225 commit_id_str = optarg;
7226 break;
7227 case 'r':
7228 repo_path = realpath(optarg, NULL);
7229 if (repo_path == NULL)
7230 return got_error_from_errno2("realpath",
7231 optarg);
7232 break;
7233 default:
7234 usage_blame();
7235 /* NOTREACHED */
7239 argc -= optind;
7240 argv += optind;
7242 if (argc != 1)
7243 usage_blame();
7245 error = got_repo_pack_fds_open(&pack_fds);
7246 if (error != NULL)
7247 goto done;
7249 if (repo_path == NULL) {
7250 cwd = getcwd(NULL, 0);
7251 if (cwd == NULL)
7252 return got_error_from_errno("getcwd");
7253 error = got_worktree_open(&worktree, cwd, NULL);
7254 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7255 goto done;
7256 if (worktree)
7257 repo_path =
7258 strdup(got_worktree_get_repo_path(worktree));
7259 else
7260 repo_path = strdup(cwd);
7261 if (repo_path == NULL) {
7262 error = got_error_from_errno("strdup");
7263 goto done;
7267 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7268 if (error != NULL)
7269 goto done;
7271 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7272 worktree);
7273 if (error)
7274 goto done;
7276 init_curses();
7278 error = apply_unveil(got_repo_get_path(repo), NULL);
7279 if (error)
7280 goto done;
7282 error = tog_load_refs(repo, 0);
7283 if (error)
7284 goto done;
7286 if (commit_id_str == NULL) {
7287 struct got_reference *head_ref;
7288 error = got_ref_open(&head_ref, repo, worktree ?
7289 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7290 if (error != NULL)
7291 goto done;
7292 error = got_ref_resolve(&commit_id, repo, head_ref);
7293 got_ref_close(head_ref);
7294 } else {
7295 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
7296 repo, worktree);
7297 if (error != NULL)
7298 goto done;
7299 if (keyword_idstr != NULL)
7300 commit_id_str = keyword_idstr;
7302 error = got_repo_match_object_id(&commit_id, NULL,
7303 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7305 if (error != NULL)
7306 goto done;
7308 error = got_object_open_as_commit(&commit, repo, commit_id);
7309 if (error)
7310 goto done;
7312 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7313 commit, repo);
7314 if (error)
7315 goto done;
7317 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7318 if (view == NULL) {
7319 error = got_error_from_errno("view_open");
7320 goto done;
7322 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7323 commit_id, repo);
7324 if (error != NULL) {
7325 if (view->close == NULL)
7326 close_blame_view(view);
7327 view_close(view);
7328 goto done;
7331 if (worktree) {
7332 error = set_tog_base_commit(repo, worktree);
7333 if (error != NULL)
7334 goto done;
7336 /* Release work tree lock. */
7337 got_worktree_close(worktree);
7338 worktree = NULL;
7341 error = view_loop(view);
7343 done:
7344 free(tog_base_commit.id);
7345 free(repo_path);
7346 free(in_repo_path);
7347 free(link_target);
7348 free(cwd);
7349 free(commit_id);
7350 free(keyword_idstr);
7351 if (commit)
7352 got_object_commit_close(commit);
7353 if (worktree)
7354 got_worktree_close(worktree);
7355 if (repo) {
7356 const struct got_error *close_err = got_repo_close(repo);
7357 if (error == NULL)
7358 error = close_err;
7360 if (pack_fds) {
7361 const struct got_error *pack_err =
7362 got_repo_pack_fds_close(pack_fds);
7363 if (error == NULL)
7364 error = pack_err;
7366 tog_free_refs();
7367 return error;
7370 static const struct got_error *
7371 draw_tree_entries(struct tog_view *view, const char *parent_path)
7373 struct tog_tree_view_state *s = &view->state.tree;
7374 const struct got_error *err = NULL;
7375 struct got_tree_entry *te;
7376 wchar_t *wline;
7377 char *index = NULL;
7378 struct tog_color *tc;
7379 int width, n, nentries, scrollx, i = 1;
7380 int limit = view->nlines;
7382 s->ndisplayed = 0;
7383 if (view_is_hsplit_top(view))
7384 --limit; /* border */
7386 werase(view->window);
7388 if (limit == 0)
7389 return NULL;
7391 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7392 0, 0);
7393 if (err)
7394 return err;
7395 if (view_needs_focus_indication(view))
7396 wstandout(view->window);
7397 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7398 if (tc)
7399 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7400 waddwstr(view->window, wline);
7401 free(wline);
7402 wline = NULL;
7403 while (width++ < view->ncols)
7404 waddch(view->window, ' ');
7405 if (tc)
7406 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7407 if (view_needs_focus_indication(view))
7408 wstandend(view->window);
7409 if (--limit <= 0)
7410 return NULL;
7412 i += s->selected;
7413 if (s->first_displayed_entry) {
7414 i += got_tree_entry_get_index(s->first_displayed_entry);
7415 if (s->tree != s->root)
7416 ++i; /* account for ".." entry */
7418 nentries = got_object_tree_get_nentries(s->tree);
7419 if (asprintf(&index, "[%d/%d] %s",
7420 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7421 return got_error_from_errno("asprintf");
7422 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7423 free(index);
7424 if (err)
7425 return err;
7426 waddwstr(view->window, wline);
7427 free(wline);
7428 wline = NULL;
7429 if (width < view->ncols - 1)
7430 waddch(view->window, '\n');
7431 if (--limit <= 0)
7432 return NULL;
7433 waddch(view->window, '\n');
7434 if (--limit <= 0)
7435 return NULL;
7437 if (s->first_displayed_entry == NULL) {
7438 te = got_object_tree_get_first_entry(s->tree);
7439 if (s->selected == 0) {
7440 if (view->focussed)
7441 wstandout(view->window);
7442 s->selected_entry = NULL;
7444 waddstr(view->window, " ..\n"); /* parent directory */
7445 if (s->selected == 0 && view->focussed)
7446 wstandend(view->window);
7447 s->ndisplayed++;
7448 if (--limit <= 0)
7449 return NULL;
7450 n = 1;
7451 } else {
7452 n = 0;
7453 te = s->first_displayed_entry;
7456 view->maxx = 0;
7457 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7458 char *line = NULL, *id_str = NULL, *link_target = NULL;
7459 const char *modestr = "";
7460 mode_t mode;
7462 te = got_object_tree_get_entry(s->tree, i);
7463 mode = got_tree_entry_get_mode(te);
7465 if (s->show_ids) {
7466 err = got_object_id_str(&id_str,
7467 got_tree_entry_get_id(te));
7468 if (err)
7469 return got_error_from_errno(
7470 "got_object_id_str");
7472 if (got_object_tree_entry_is_submodule(te))
7473 modestr = "$";
7474 else if (S_ISLNK(mode)) {
7475 int i;
7477 err = got_tree_entry_get_symlink_target(&link_target,
7478 te, s->repo);
7479 if (err) {
7480 free(id_str);
7481 return err;
7483 for (i = 0; link_target[i] != '\0'; i++) {
7484 if (!isprint((unsigned char)link_target[i]))
7485 link_target[i] = '?';
7487 modestr = "@";
7489 else if (S_ISDIR(mode))
7490 modestr = "/";
7491 else if (mode & S_IXUSR)
7492 modestr = "*";
7493 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7494 got_tree_entry_get_name(te), modestr,
7495 link_target ? " -> ": "",
7496 link_target ? link_target : "") == -1) {
7497 free(id_str);
7498 free(link_target);
7499 return got_error_from_errno("asprintf");
7501 free(id_str);
7502 free(link_target);
7504 /* use full line width to determine view->maxx */
7505 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7506 if (err) {
7507 free(line);
7508 break;
7510 view->maxx = MAX(view->maxx, width);
7511 free(wline);
7512 wline = NULL;
7514 err = format_line(&wline, &width, &scrollx, line, view->x,
7515 view->ncols, 0, 0);
7516 if (err) {
7517 free(line);
7518 break;
7520 if (n == s->selected) {
7521 if (view->focussed)
7522 wstandout(view->window);
7523 s->selected_entry = te;
7525 tc = match_color(&s->colors, line);
7526 if (tc)
7527 wattr_on(view->window,
7528 COLOR_PAIR(tc->colorpair), NULL);
7529 waddwstr(view->window, &wline[scrollx]);
7530 if (tc)
7531 wattr_off(view->window,
7532 COLOR_PAIR(tc->colorpair), NULL);
7533 if (width < view->ncols)
7534 waddch(view->window, '\n');
7535 if (n == s->selected && view->focussed)
7536 wstandend(view->window);
7537 free(line);
7538 free(wline);
7539 wline = NULL;
7540 n++;
7541 s->ndisplayed++;
7542 s->last_displayed_entry = te;
7543 if (--limit <= 0)
7544 break;
7547 return err;
7550 static void
7551 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7553 struct got_tree_entry *te;
7554 int isroot = s->tree == s->root;
7555 int i = 0;
7557 if (s->first_displayed_entry == NULL)
7558 return;
7560 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7561 while (i++ < maxscroll) {
7562 if (te == NULL) {
7563 if (!isroot)
7564 s->first_displayed_entry = NULL;
7565 break;
7567 s->first_displayed_entry = te;
7568 te = got_tree_entry_get_prev(s->tree, te);
7572 static const struct got_error *
7573 tree_scroll_down(struct tog_view *view, int maxscroll)
7575 struct tog_tree_view_state *s = &view->state.tree;
7576 struct got_tree_entry *next, *last;
7577 int n = 0;
7579 if (s->first_displayed_entry)
7580 next = got_tree_entry_get_next(s->tree,
7581 s->first_displayed_entry);
7582 else
7583 next = got_object_tree_get_first_entry(s->tree);
7585 last = s->last_displayed_entry;
7586 while (next && n++ < maxscroll) {
7587 if (last) {
7588 s->last_displayed_entry = last;
7589 last = got_tree_entry_get_next(s->tree, last);
7591 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7592 s->first_displayed_entry = next;
7593 next = got_tree_entry_get_next(s->tree, next);
7597 return NULL;
7600 static const struct got_error *
7601 tree_entry_path(char **path, struct tog_parent_trees *parents,
7602 struct got_tree_entry *te)
7604 const struct got_error *err = NULL;
7605 struct tog_parent_tree *pt;
7606 size_t len = 2; /* for leading slash and NUL */
7608 TAILQ_FOREACH(pt, parents, entry)
7609 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7610 + 1 /* slash */;
7611 if (te)
7612 len += strlen(got_tree_entry_get_name(te));
7614 *path = calloc(1, len);
7615 if (path == NULL)
7616 return got_error_from_errno("calloc");
7618 (*path)[0] = '/';
7619 pt = TAILQ_LAST(parents, tog_parent_trees);
7620 while (pt) {
7621 const char *name = got_tree_entry_get_name(pt->selected_entry);
7622 if (strlcat(*path, name, len) >= len) {
7623 err = got_error(GOT_ERR_NO_SPACE);
7624 goto done;
7626 if (strlcat(*path, "/", len) >= len) {
7627 err = got_error(GOT_ERR_NO_SPACE);
7628 goto done;
7630 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7632 if (te) {
7633 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7634 err = got_error(GOT_ERR_NO_SPACE);
7635 goto done;
7638 done:
7639 if (err) {
7640 free(*path);
7641 *path = NULL;
7643 return err;
7646 static const struct got_error *
7647 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7648 struct got_tree_entry *te, struct tog_parent_trees *parents,
7649 struct got_object_id *commit_id, struct got_repository *repo)
7651 const struct got_error *err = NULL;
7652 char *path;
7653 struct tog_view *blame_view;
7655 *new_view = NULL;
7657 err = tree_entry_path(&path, parents, te);
7658 if (err)
7659 return err;
7661 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7662 if (blame_view == NULL) {
7663 err = got_error_from_errno("view_open");
7664 goto done;
7667 err = open_blame_view(blame_view, path, commit_id, repo);
7668 if (err) {
7669 if (err->code == GOT_ERR_CANCELLED)
7670 err = NULL;
7671 view_close(blame_view);
7672 } else
7673 *new_view = blame_view;
7674 done:
7675 free(path);
7676 return err;
7679 static const struct got_error *
7680 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7681 struct tog_tree_view_state *s)
7683 struct tog_view *log_view;
7684 const struct got_error *err = NULL;
7685 char *path;
7687 *new_view = NULL;
7689 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7690 if (log_view == NULL)
7691 return got_error_from_errno("view_open");
7693 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7694 if (err)
7695 return err;
7697 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7698 path, 0, NULL);
7699 if (err)
7700 view_close(log_view);
7701 else
7702 *new_view = log_view;
7703 free(path);
7704 return err;
7707 static const struct got_error *
7708 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7709 const char *head_ref_name, struct got_repository *repo)
7711 const struct got_error *err = NULL;
7712 char *commit_id_str = NULL;
7713 struct tog_tree_view_state *s = &view->state.tree;
7714 struct got_commit_object *commit = NULL;
7716 TAILQ_INIT(&s->parents);
7717 STAILQ_INIT(&s->colors);
7719 s->commit_id = got_object_id_dup(commit_id);
7720 if (s->commit_id == NULL) {
7721 err = got_error_from_errno("got_object_id_dup");
7722 goto done;
7725 err = got_object_open_as_commit(&commit, repo, commit_id);
7726 if (err)
7727 goto done;
7730 * The root is opened here and will be closed when the view is closed.
7731 * Any visited subtrees and their path-wise parents are opened and
7732 * closed on demand.
7734 err = got_object_open_as_tree(&s->root, repo,
7735 got_object_commit_get_tree_id(commit));
7736 if (err)
7737 goto done;
7738 s->tree = s->root;
7740 err = got_object_id_str(&commit_id_str, commit_id);
7741 if (err != NULL)
7742 goto done;
7744 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7745 err = got_error_from_errno("asprintf");
7746 goto done;
7749 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7750 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7751 if (head_ref_name) {
7752 s->head_ref_name = strdup(head_ref_name);
7753 if (s->head_ref_name == NULL) {
7754 err = got_error_from_errno("strdup");
7755 goto done;
7758 s->repo = repo;
7760 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7761 err = add_color(&s->colors, "\\$$",
7762 TOG_COLOR_TREE_SUBMODULE,
7763 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7764 if (err)
7765 goto done;
7766 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7767 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7768 if (err)
7769 goto done;
7770 err = add_color(&s->colors, "/$",
7771 TOG_COLOR_TREE_DIRECTORY,
7772 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7773 if (err)
7774 goto done;
7776 err = add_color(&s->colors, "\\*$",
7777 TOG_COLOR_TREE_EXECUTABLE,
7778 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7779 if (err)
7780 goto done;
7782 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7783 get_color_value("TOG_COLOR_COMMIT"));
7784 if (err)
7785 goto done;
7788 view->show = show_tree_view;
7789 view->input = input_tree_view;
7790 view->close = close_tree_view;
7791 view->search_start = search_start_tree_view;
7792 view->search_next = search_next_tree_view;
7793 done:
7794 free(commit_id_str);
7795 if (commit)
7796 got_object_commit_close(commit);
7797 if (err) {
7798 if (view->close == NULL)
7799 close_tree_view(view);
7800 view_close(view);
7802 return err;
7805 static const struct got_error *
7806 close_tree_view(struct tog_view *view)
7808 struct tog_tree_view_state *s = &view->state.tree;
7810 free_colors(&s->colors);
7811 free(s->tree_label);
7812 s->tree_label = NULL;
7813 free(s->commit_id);
7814 s->commit_id = NULL;
7815 free(s->head_ref_name);
7816 s->head_ref_name = NULL;
7817 while (!TAILQ_EMPTY(&s->parents)) {
7818 struct tog_parent_tree *parent;
7819 parent = TAILQ_FIRST(&s->parents);
7820 TAILQ_REMOVE(&s->parents, parent, entry);
7821 if (parent->tree != s->root)
7822 got_object_tree_close(parent->tree);
7823 free(parent);
7826 if (s->tree != NULL && s->tree != s->root)
7827 got_object_tree_close(s->tree);
7828 if (s->root)
7829 got_object_tree_close(s->root);
7830 return NULL;
7833 static const struct got_error *
7834 search_start_tree_view(struct tog_view *view)
7836 struct tog_tree_view_state *s = &view->state.tree;
7838 s->matched_entry = NULL;
7839 return NULL;
7842 static int
7843 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7845 regmatch_t regmatch;
7847 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7848 0) == 0;
7851 static const struct got_error *
7852 search_next_tree_view(struct tog_view *view)
7854 struct tog_tree_view_state *s = &view->state.tree;
7855 struct got_tree_entry *te = NULL;
7857 if (!view->searching) {
7858 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7859 return NULL;
7862 if (s->matched_entry) {
7863 if (view->searching == TOG_SEARCH_FORWARD) {
7864 if (s->selected_entry)
7865 te = got_tree_entry_get_next(s->tree,
7866 s->selected_entry);
7867 else
7868 te = got_object_tree_get_first_entry(s->tree);
7869 } else {
7870 if (s->selected_entry == NULL)
7871 te = got_object_tree_get_last_entry(s->tree);
7872 else
7873 te = got_tree_entry_get_prev(s->tree,
7874 s->selected_entry);
7876 } else {
7877 if (s->selected_entry)
7878 te = s->selected_entry;
7879 else if (view->searching == TOG_SEARCH_FORWARD)
7880 te = got_object_tree_get_first_entry(s->tree);
7881 else
7882 te = got_object_tree_get_last_entry(s->tree);
7885 while (1) {
7886 if (te == NULL) {
7887 if (s->matched_entry == NULL) {
7888 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7889 return NULL;
7891 if (view->searching == TOG_SEARCH_FORWARD)
7892 te = got_object_tree_get_first_entry(s->tree);
7893 else
7894 te = got_object_tree_get_last_entry(s->tree);
7897 if (match_tree_entry(te, &view->regex)) {
7898 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7899 s->matched_entry = te;
7900 break;
7903 if (view->searching == TOG_SEARCH_FORWARD)
7904 te = got_tree_entry_get_next(s->tree, te);
7905 else
7906 te = got_tree_entry_get_prev(s->tree, te);
7909 if (s->matched_entry) {
7910 s->first_displayed_entry = s->matched_entry;
7911 s->selected = 0;
7914 return NULL;
7917 static const struct got_error *
7918 show_tree_view(struct tog_view *view)
7920 const struct got_error *err = NULL;
7921 struct tog_tree_view_state *s = &view->state.tree;
7922 char *parent_path;
7924 err = tree_entry_path(&parent_path, &s->parents, NULL);
7925 if (err)
7926 return err;
7928 err = draw_tree_entries(view, parent_path);
7929 free(parent_path);
7931 view_border(view);
7932 return err;
7935 static const struct got_error *
7936 tree_goto_line(struct tog_view *view, int nlines)
7938 const struct got_error *err = NULL;
7939 struct tog_tree_view_state *s = &view->state.tree;
7940 struct got_tree_entry **fte, **lte, **ste;
7941 int g, last, first = 1, i = 1;
7942 int root = s->tree == s->root;
7943 int off = root ? 1 : 2;
7945 g = view->gline;
7946 view->gline = 0;
7948 if (g == 0)
7949 g = 1;
7950 else if (g > got_object_tree_get_nentries(s->tree))
7951 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7953 fte = &s->first_displayed_entry;
7954 lte = &s->last_displayed_entry;
7955 ste = &s->selected_entry;
7957 if (*fte != NULL) {
7958 first = got_tree_entry_get_index(*fte);
7959 first += off; /* account for ".." */
7961 last = got_tree_entry_get_index(*lte);
7962 last += off;
7964 if (g >= first && g <= last && g - first < nlines) {
7965 s->selected = g - first;
7966 return NULL; /* gline is on the current page */
7969 if (*ste != NULL) {
7970 i = got_tree_entry_get_index(*ste);
7971 i += off;
7974 if (i < g) {
7975 err = tree_scroll_down(view, g - i);
7976 if (err)
7977 return err;
7978 if (got_tree_entry_get_index(*lte) >=
7979 got_object_tree_get_nentries(s->tree) - 1 &&
7980 first + s->selected < g &&
7981 s->selected < s->ndisplayed - 1) {
7982 first = got_tree_entry_get_index(*fte);
7983 first += off;
7984 s->selected = g - first;
7986 } else if (i > g)
7987 tree_scroll_up(s, i - g);
7989 if (g < nlines &&
7990 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7991 s->selected = g - 1;
7993 return NULL;
7996 static const struct got_error *
7997 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7999 const struct got_error *err = NULL;
8000 struct tog_tree_view_state *s = &view->state.tree;
8001 struct got_tree_entry *te;
8002 int n, nscroll = view->nlines - 3;
8004 if (view->gline)
8005 return tree_goto_line(view, nscroll);
8007 switch (ch) {
8008 case '0':
8009 case '$':
8010 case KEY_RIGHT:
8011 case 'l':
8012 case KEY_LEFT:
8013 case 'h':
8014 horizontal_scroll_input(view, ch);
8015 break;
8016 case 'i':
8017 s->show_ids = !s->show_ids;
8018 view->count = 0;
8019 break;
8020 case 'L':
8021 view->count = 0;
8022 if (!s->selected_entry)
8023 break;
8024 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8025 break;
8026 case 'R':
8027 view->count = 0;
8028 err = view_request_new(new_view, view, TOG_VIEW_REF);
8029 break;
8030 case 'g':
8031 case '=':
8032 case KEY_HOME:
8033 s->selected = 0;
8034 view->count = 0;
8035 if (s->tree == s->root)
8036 s->first_displayed_entry =
8037 got_object_tree_get_first_entry(s->tree);
8038 else
8039 s->first_displayed_entry = NULL;
8040 break;
8041 case 'G':
8042 case '*':
8043 case KEY_END: {
8044 int eos = view->nlines - 3;
8046 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8047 --eos; /* border */
8048 s->selected = 0;
8049 view->count = 0;
8050 te = got_object_tree_get_last_entry(s->tree);
8051 for (n = 0; n < eos; n++) {
8052 if (te == NULL) {
8053 if (s->tree != s->root) {
8054 s->first_displayed_entry = NULL;
8055 n++;
8057 break;
8059 s->first_displayed_entry = te;
8060 te = got_tree_entry_get_prev(s->tree, te);
8062 if (n > 0)
8063 s->selected = n - 1;
8064 break;
8066 case 'k':
8067 case KEY_UP:
8068 case CTRL('p'):
8069 if (s->selected > 0) {
8070 s->selected--;
8071 break;
8073 tree_scroll_up(s, 1);
8074 if (s->selected_entry == NULL ||
8075 (s->tree == s->root && s->selected_entry ==
8076 got_object_tree_get_first_entry(s->tree)))
8077 view->count = 0;
8078 break;
8079 case CTRL('u'):
8080 case 'u':
8081 nscroll /= 2;
8082 /* FALL THROUGH */
8083 case KEY_PPAGE:
8084 case CTRL('b'):
8085 case 'b':
8086 if (s->tree == s->root) {
8087 if (got_object_tree_get_first_entry(s->tree) ==
8088 s->first_displayed_entry)
8089 s->selected -= MIN(s->selected, nscroll);
8090 } else {
8091 if (s->first_displayed_entry == NULL)
8092 s->selected -= MIN(s->selected, nscroll);
8094 tree_scroll_up(s, MAX(0, nscroll));
8095 if (s->selected_entry == NULL ||
8096 (s->tree == s->root && s->selected_entry ==
8097 got_object_tree_get_first_entry(s->tree)))
8098 view->count = 0;
8099 break;
8100 case 'j':
8101 case KEY_DOWN:
8102 case CTRL('n'):
8103 if (s->selected < s->ndisplayed - 1) {
8104 s->selected++;
8105 break;
8107 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8108 == NULL) {
8109 /* can't scroll any further */
8110 view->count = 0;
8111 break;
8113 tree_scroll_down(view, 1);
8114 break;
8115 case CTRL('d'):
8116 case 'd':
8117 nscroll /= 2;
8118 /* FALL THROUGH */
8119 case KEY_NPAGE:
8120 case CTRL('f'):
8121 case 'f':
8122 case ' ':
8123 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8124 == NULL) {
8125 /* can't scroll any further; move cursor down */
8126 if (s->selected < s->ndisplayed - 1)
8127 s->selected += MIN(nscroll,
8128 s->ndisplayed - s->selected - 1);
8129 else
8130 view->count = 0;
8131 break;
8133 tree_scroll_down(view, nscroll);
8134 break;
8135 case KEY_ENTER:
8136 case '\r':
8137 case KEY_BACKSPACE:
8138 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
8139 struct tog_parent_tree *parent;
8140 /* user selected '..' */
8141 if (s->tree == s->root) {
8142 view->count = 0;
8143 break;
8145 parent = TAILQ_FIRST(&s->parents);
8146 TAILQ_REMOVE(&s->parents, parent,
8147 entry);
8148 got_object_tree_close(s->tree);
8149 s->tree = parent->tree;
8150 s->first_displayed_entry =
8151 parent->first_displayed_entry;
8152 s->selected_entry =
8153 parent->selected_entry;
8154 s->selected = parent->selected;
8155 if (s->selected > view->nlines - 3) {
8156 err = offset_selection_down(view);
8157 if (err)
8158 break;
8160 free(parent);
8161 } else if (S_ISDIR(got_tree_entry_get_mode(
8162 s->selected_entry))) {
8163 struct got_tree_object *subtree;
8164 view->count = 0;
8165 err = got_object_open_as_tree(&subtree, s->repo,
8166 got_tree_entry_get_id(s->selected_entry));
8167 if (err)
8168 break;
8169 err = tree_view_visit_subtree(s, subtree);
8170 if (err) {
8171 got_object_tree_close(subtree);
8172 break;
8174 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
8175 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
8176 break;
8177 case KEY_RESIZE:
8178 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
8179 s->selected = view->nlines - 4;
8180 view->count = 0;
8181 break;
8182 default:
8183 view->count = 0;
8184 break;
8187 return err;
8190 __dead static void
8191 usage_tree(void)
8193 endwin();
8194 fprintf(stderr,
8195 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
8196 getprogname());
8197 exit(1);
8200 static const struct got_error *
8201 cmd_tree(int argc, char *argv[])
8203 const struct got_error *error;
8204 struct got_repository *repo = NULL;
8205 struct got_worktree *worktree = NULL;
8206 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8207 struct got_object_id *commit_id = NULL;
8208 struct got_commit_object *commit = NULL;
8209 const char *commit_id_arg = NULL;
8210 char *keyword_idstr = NULL, *label = NULL;
8211 struct got_reference *ref = NULL;
8212 const char *head_ref_name = NULL;
8213 int ch;
8214 struct tog_view *view;
8215 int *pack_fds = NULL;
8217 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
8218 switch (ch) {
8219 case 'c':
8220 commit_id_arg = optarg;
8221 break;
8222 case 'r':
8223 repo_path = realpath(optarg, NULL);
8224 if (repo_path == NULL)
8225 return got_error_from_errno2("realpath",
8226 optarg);
8227 break;
8228 default:
8229 usage_tree();
8230 /* NOTREACHED */
8234 argc -= optind;
8235 argv += optind;
8237 if (argc > 1)
8238 usage_tree();
8240 error = got_repo_pack_fds_open(&pack_fds);
8241 if (error != NULL)
8242 goto done;
8244 if (repo_path == NULL) {
8245 cwd = getcwd(NULL, 0);
8246 if (cwd == NULL)
8247 return got_error_from_errno("getcwd");
8248 error = got_worktree_open(&worktree, cwd, NULL);
8249 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8250 goto done;
8251 if (worktree)
8252 repo_path =
8253 strdup(got_worktree_get_repo_path(worktree));
8254 else
8255 repo_path = strdup(cwd);
8256 if (repo_path == NULL) {
8257 error = got_error_from_errno("strdup");
8258 goto done;
8262 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8263 if (error != NULL)
8264 goto done;
8266 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8267 repo, worktree);
8268 if (error)
8269 goto done;
8271 init_curses();
8273 error = apply_unveil(got_repo_get_path(repo), NULL);
8274 if (error)
8275 goto done;
8277 error = tog_load_refs(repo, 0);
8278 if (error)
8279 goto done;
8281 if (commit_id_arg == NULL) {
8282 error = got_repo_match_object_id(&commit_id, &label,
8283 worktree ? got_worktree_get_head_ref_name(worktree) :
8284 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8285 if (error)
8286 goto done;
8287 head_ref_name = label;
8288 } else {
8289 error = got_keyword_to_idstr(&keyword_idstr, commit_id_arg,
8290 repo, worktree);
8291 if (error != NULL)
8292 goto done;
8293 if (keyword_idstr != NULL)
8294 commit_id_arg = keyword_idstr;
8296 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8297 if (error == NULL)
8298 head_ref_name = got_ref_get_name(ref);
8299 else if (error->code != GOT_ERR_NOT_REF)
8300 goto done;
8301 error = got_repo_match_object_id(&commit_id, NULL,
8302 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8303 if (error)
8304 goto done;
8307 error = got_object_open_as_commit(&commit, repo, commit_id);
8308 if (error)
8309 goto done;
8311 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8312 if (view == NULL) {
8313 error = got_error_from_errno("view_open");
8314 goto done;
8316 error = open_tree_view(view, commit_id, head_ref_name, repo);
8317 if (error)
8318 goto done;
8319 if (!got_path_is_root_dir(in_repo_path)) {
8320 error = tree_view_walk_path(&view->state.tree, commit,
8321 in_repo_path);
8322 if (error)
8323 goto done;
8326 if (worktree) {
8327 error = set_tog_base_commit(repo, worktree);
8328 if (error != NULL)
8329 goto done;
8331 /* Release work tree lock. */
8332 got_worktree_close(worktree);
8333 worktree = NULL;
8336 error = view_loop(view);
8338 done:
8339 free(tog_base_commit.id);
8340 free(keyword_idstr);
8341 free(repo_path);
8342 free(cwd);
8343 free(commit_id);
8344 free(label);
8345 if (ref)
8346 got_ref_close(ref);
8347 if (worktree != NULL)
8348 got_worktree_close(worktree);
8349 if (repo) {
8350 const struct got_error *close_err = got_repo_close(repo);
8351 if (error == NULL)
8352 error = close_err;
8354 if (pack_fds) {
8355 const struct got_error *pack_err =
8356 got_repo_pack_fds_close(pack_fds);
8357 if (error == NULL)
8358 error = pack_err;
8360 tog_free_refs();
8361 return error;
8364 static const struct got_error *
8365 ref_view_load_refs(struct tog_ref_view_state *s)
8367 struct got_reflist_entry *sre;
8368 struct tog_reflist_entry *re;
8370 s->nrefs = 0;
8371 TAILQ_FOREACH(sre, &tog_refs, entry) {
8372 if (strncmp(got_ref_get_name(sre->ref),
8373 "refs/got/", 9) == 0 &&
8374 strncmp(got_ref_get_name(sre->ref),
8375 "refs/got/backup/", 16) != 0)
8376 continue;
8378 re = malloc(sizeof(*re));
8379 if (re == NULL)
8380 return got_error_from_errno("malloc");
8382 re->ref = got_ref_dup(sre->ref);
8383 if (re->ref == NULL)
8384 return got_error_from_errno("got_ref_dup");
8385 re->idx = s->nrefs++;
8386 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8389 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8390 return NULL;
8393 static void
8394 ref_view_free_refs(struct tog_ref_view_state *s)
8396 struct tog_reflist_entry *re;
8398 while (!TAILQ_EMPTY(&s->refs)) {
8399 re = TAILQ_FIRST(&s->refs);
8400 TAILQ_REMOVE(&s->refs, re, entry);
8401 got_ref_close(re->ref);
8402 free(re);
8406 static const struct got_error *
8407 open_ref_view(struct tog_view *view, struct got_repository *repo)
8409 const struct got_error *err = NULL;
8410 struct tog_ref_view_state *s = &view->state.ref;
8412 s->selected_entry = 0;
8413 s->repo = repo;
8415 TAILQ_INIT(&s->refs);
8416 STAILQ_INIT(&s->colors);
8418 err = ref_view_load_refs(s);
8419 if (err)
8420 goto done;
8422 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8423 err = add_color(&s->colors, "^refs/heads/",
8424 TOG_COLOR_REFS_HEADS,
8425 get_color_value("TOG_COLOR_REFS_HEADS"));
8426 if (err)
8427 goto done;
8429 err = add_color(&s->colors, "^refs/tags/",
8430 TOG_COLOR_REFS_TAGS,
8431 get_color_value("TOG_COLOR_REFS_TAGS"));
8432 if (err)
8433 goto done;
8435 err = add_color(&s->colors, "^refs/remotes/",
8436 TOG_COLOR_REFS_REMOTES,
8437 get_color_value("TOG_COLOR_REFS_REMOTES"));
8438 if (err)
8439 goto done;
8441 err = add_color(&s->colors, "^refs/got/backup/",
8442 TOG_COLOR_REFS_BACKUP,
8443 get_color_value("TOG_COLOR_REFS_BACKUP"));
8444 if (err)
8445 goto done;
8448 view->show = show_ref_view;
8449 view->input = input_ref_view;
8450 view->close = close_ref_view;
8451 view->search_start = search_start_ref_view;
8452 view->search_next = search_next_ref_view;
8453 done:
8454 if (err) {
8455 if (view->close == NULL)
8456 close_ref_view(view);
8457 view_close(view);
8459 return err;
8462 static const struct got_error *
8463 close_ref_view(struct tog_view *view)
8465 struct tog_ref_view_state *s = &view->state.ref;
8467 ref_view_free_refs(s);
8468 free_colors(&s->colors);
8470 return NULL;
8473 static const struct got_error *
8474 resolve_reflist_entry(struct got_object_id **commit_id,
8475 struct tog_reflist_entry *re, struct got_repository *repo)
8477 const struct got_error *err = NULL;
8478 struct got_object_id *obj_id;
8479 struct got_tag_object *tag = NULL;
8480 int obj_type;
8482 *commit_id = NULL;
8484 err = got_ref_resolve(&obj_id, repo, re->ref);
8485 if (err)
8486 return err;
8488 err = got_object_get_type(&obj_type, repo, obj_id);
8489 if (err)
8490 goto done;
8492 switch (obj_type) {
8493 case GOT_OBJ_TYPE_COMMIT:
8494 *commit_id = obj_id;
8495 break;
8496 case GOT_OBJ_TYPE_TAG:
8497 err = got_object_open_as_tag(&tag, repo, obj_id);
8498 if (err)
8499 goto done;
8500 free(obj_id);
8501 err = got_object_get_type(&obj_type, repo,
8502 got_object_tag_get_object_id(tag));
8503 if (err)
8504 goto done;
8505 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8506 err = got_error(GOT_ERR_OBJ_TYPE);
8507 goto done;
8509 *commit_id = got_object_id_dup(
8510 got_object_tag_get_object_id(tag));
8511 if (*commit_id == NULL) {
8512 err = got_error_from_errno("got_object_id_dup");
8513 goto done;
8515 break;
8516 default:
8517 err = got_error(GOT_ERR_OBJ_TYPE);
8518 break;
8521 done:
8522 if (tag)
8523 got_object_tag_close(tag);
8524 if (err) {
8525 free(*commit_id);
8526 *commit_id = NULL;
8528 return err;
8531 static const struct got_error *
8532 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8533 struct tog_reflist_entry *re, struct got_repository *repo)
8535 struct tog_view *log_view;
8536 const struct got_error *err = NULL;
8537 struct got_object_id *commit_id = NULL;
8539 *new_view = NULL;
8541 err = resolve_reflist_entry(&commit_id, re, repo);
8542 if (err) {
8543 if (err->code != GOT_ERR_OBJ_TYPE)
8544 return err;
8545 else
8546 return NULL;
8549 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8550 if (log_view == NULL) {
8551 err = got_error_from_errno("view_open");
8552 goto done;
8555 err = open_log_view(log_view, commit_id, repo,
8556 got_ref_get_name(re->ref), "", 0, NULL);
8557 done:
8558 if (err)
8559 view_close(log_view);
8560 else
8561 *new_view = log_view;
8562 free(commit_id);
8563 return err;
8566 static void
8567 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8569 struct tog_reflist_entry *re;
8570 int i = 0;
8572 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8573 return;
8575 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8576 while (i++ < maxscroll) {
8577 if (re == NULL)
8578 break;
8579 s->first_displayed_entry = re;
8580 re = TAILQ_PREV(re, tog_reflist_head, entry);
8584 static const struct got_error *
8585 ref_scroll_down(struct tog_view *view, int maxscroll)
8587 struct tog_ref_view_state *s = &view->state.ref;
8588 struct tog_reflist_entry *next, *last;
8589 int n = 0;
8591 if (s->first_displayed_entry)
8592 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8593 else
8594 next = TAILQ_FIRST(&s->refs);
8596 last = s->last_displayed_entry;
8597 while (next && n++ < maxscroll) {
8598 if (last) {
8599 s->last_displayed_entry = last;
8600 last = TAILQ_NEXT(last, entry);
8602 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8603 s->first_displayed_entry = next;
8604 next = TAILQ_NEXT(next, entry);
8608 return NULL;
8611 static const struct got_error *
8612 search_start_ref_view(struct tog_view *view)
8614 struct tog_ref_view_state *s = &view->state.ref;
8616 s->matched_entry = NULL;
8617 return NULL;
8620 static int
8621 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8623 regmatch_t regmatch;
8625 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8626 0) == 0;
8629 static const struct got_error *
8630 search_next_ref_view(struct tog_view *view)
8632 struct tog_ref_view_state *s = &view->state.ref;
8633 struct tog_reflist_entry *re = NULL;
8635 if (!view->searching) {
8636 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8637 return NULL;
8640 if (s->matched_entry) {
8641 if (view->searching == TOG_SEARCH_FORWARD) {
8642 if (s->selected_entry)
8643 re = TAILQ_NEXT(s->selected_entry, entry);
8644 else
8645 re = TAILQ_PREV(s->selected_entry,
8646 tog_reflist_head, entry);
8647 } else {
8648 if (s->selected_entry == NULL)
8649 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8650 else
8651 re = TAILQ_PREV(s->selected_entry,
8652 tog_reflist_head, entry);
8654 } else {
8655 if (s->selected_entry)
8656 re = s->selected_entry;
8657 else if (view->searching == TOG_SEARCH_FORWARD)
8658 re = TAILQ_FIRST(&s->refs);
8659 else
8660 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8663 while (1) {
8664 if (re == NULL) {
8665 if (s->matched_entry == NULL) {
8666 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8667 return NULL;
8669 if (view->searching == TOG_SEARCH_FORWARD)
8670 re = TAILQ_FIRST(&s->refs);
8671 else
8672 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8675 if (match_reflist_entry(re, &view->regex)) {
8676 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8677 s->matched_entry = re;
8678 break;
8681 if (view->searching == TOG_SEARCH_FORWARD)
8682 re = TAILQ_NEXT(re, entry);
8683 else
8684 re = TAILQ_PREV(re, tog_reflist_head, entry);
8687 if (s->matched_entry) {
8688 s->first_displayed_entry = s->matched_entry;
8689 s->selected = 0;
8692 return NULL;
8695 static const struct got_error *
8696 show_ref_view(struct tog_view *view)
8698 const struct got_error *err = NULL;
8699 struct tog_ref_view_state *s = &view->state.ref;
8700 struct tog_reflist_entry *re;
8701 char *line = NULL;
8702 wchar_t *wline;
8703 struct tog_color *tc;
8704 int width, n, scrollx;
8705 int limit = view->nlines;
8707 werase(view->window);
8709 s->ndisplayed = 0;
8710 if (view_is_hsplit_top(view))
8711 --limit; /* border */
8713 if (limit == 0)
8714 return NULL;
8716 re = s->first_displayed_entry;
8718 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8719 s->nrefs) == -1)
8720 return got_error_from_errno("asprintf");
8722 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8723 if (err) {
8724 free(line);
8725 return err;
8727 if (view_needs_focus_indication(view))
8728 wstandout(view->window);
8729 waddwstr(view->window, wline);
8730 while (width++ < view->ncols)
8731 waddch(view->window, ' ');
8732 if (view_needs_focus_indication(view))
8733 wstandend(view->window);
8734 free(wline);
8735 wline = NULL;
8736 free(line);
8737 line = NULL;
8738 if (--limit <= 0)
8739 return NULL;
8741 n = 0;
8742 view->maxx = 0;
8743 while (re && limit > 0) {
8744 char *line = NULL;
8745 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8747 if (s->show_date) {
8748 struct got_commit_object *ci;
8749 struct got_tag_object *tag;
8750 struct got_object_id *id;
8751 struct tm tm;
8752 time_t t;
8754 err = got_ref_resolve(&id, s->repo, re->ref);
8755 if (err)
8756 return err;
8757 err = got_object_open_as_tag(&tag, s->repo, id);
8758 if (err) {
8759 if (err->code != GOT_ERR_OBJ_TYPE) {
8760 free(id);
8761 return err;
8763 err = got_object_open_as_commit(&ci, s->repo,
8764 id);
8765 if (err) {
8766 free(id);
8767 return err;
8769 t = got_object_commit_get_committer_time(ci);
8770 got_object_commit_close(ci);
8771 } else {
8772 t = got_object_tag_get_tagger_time(tag);
8773 got_object_tag_close(tag);
8775 free(id);
8776 if (gmtime_r(&t, &tm) == NULL)
8777 return got_error_from_errno("gmtime_r");
8778 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8779 return got_error(GOT_ERR_NO_SPACE);
8781 if (got_ref_is_symbolic(re->ref)) {
8782 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8783 ymd : "", got_ref_get_name(re->ref),
8784 got_ref_get_symref_target(re->ref)) == -1)
8785 return got_error_from_errno("asprintf");
8786 } else if (s->show_ids) {
8787 struct got_object_id *id;
8788 char *id_str;
8789 err = got_ref_resolve(&id, s->repo, re->ref);
8790 if (err)
8791 return err;
8792 err = got_object_id_str(&id_str, id);
8793 if (err) {
8794 free(id);
8795 return err;
8797 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8798 got_ref_get_name(re->ref), id_str) == -1) {
8799 err = got_error_from_errno("asprintf");
8800 free(id);
8801 free(id_str);
8802 return err;
8804 free(id);
8805 free(id_str);
8806 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8807 got_ref_get_name(re->ref)) == -1)
8808 return got_error_from_errno("asprintf");
8810 /* use full line width to determine view->maxx */
8811 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8812 if (err) {
8813 free(line);
8814 return err;
8816 view->maxx = MAX(view->maxx, width);
8817 free(wline);
8818 wline = NULL;
8820 err = format_line(&wline, &width, &scrollx, line, view->x,
8821 view->ncols, 0, 0);
8822 if (err) {
8823 free(line);
8824 return err;
8826 if (n == s->selected) {
8827 if (view->focussed)
8828 wstandout(view->window);
8829 s->selected_entry = re;
8831 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8832 if (tc)
8833 wattr_on(view->window,
8834 COLOR_PAIR(tc->colorpair), NULL);
8835 waddwstr(view->window, &wline[scrollx]);
8836 if (tc)
8837 wattr_off(view->window,
8838 COLOR_PAIR(tc->colorpair), NULL);
8839 if (width < view->ncols)
8840 waddch(view->window, '\n');
8841 if (n == s->selected && view->focussed)
8842 wstandend(view->window);
8843 free(line);
8844 free(wline);
8845 wline = NULL;
8846 n++;
8847 s->ndisplayed++;
8848 s->last_displayed_entry = re;
8850 limit--;
8851 re = TAILQ_NEXT(re, entry);
8854 view_border(view);
8855 return err;
8858 static const struct got_error *
8859 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8860 struct tog_reflist_entry *re, struct got_repository *repo)
8862 const struct got_error *err = NULL;
8863 struct got_object_id *commit_id = NULL;
8864 struct tog_view *tree_view;
8866 *new_view = NULL;
8868 err = resolve_reflist_entry(&commit_id, re, repo);
8869 if (err) {
8870 if (err->code != GOT_ERR_OBJ_TYPE)
8871 return err;
8872 else
8873 return NULL;
8877 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8878 if (tree_view == NULL) {
8879 err = got_error_from_errno("view_open");
8880 goto done;
8883 err = open_tree_view(tree_view, commit_id,
8884 got_ref_get_name(re->ref), repo);
8885 if (err)
8886 goto done;
8888 *new_view = tree_view;
8889 done:
8890 free(commit_id);
8891 return err;
8894 static const struct got_error *
8895 ref_goto_line(struct tog_view *view, int nlines)
8897 const struct got_error *err = NULL;
8898 struct tog_ref_view_state *s = &view->state.ref;
8899 int g, idx = s->selected_entry->idx;
8901 g = view->gline;
8902 view->gline = 0;
8904 if (g == 0)
8905 g = 1;
8906 else if (g > s->nrefs)
8907 g = s->nrefs;
8909 if (g >= s->first_displayed_entry->idx + 1 &&
8910 g <= s->last_displayed_entry->idx + 1 &&
8911 g - s->first_displayed_entry->idx - 1 < nlines) {
8912 s->selected = g - s->first_displayed_entry->idx - 1;
8913 return NULL;
8916 if (idx + 1 < g) {
8917 err = ref_scroll_down(view, g - idx - 1);
8918 if (err)
8919 return err;
8920 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8921 s->first_displayed_entry->idx + s->selected < g &&
8922 s->selected < s->ndisplayed - 1)
8923 s->selected = g - s->first_displayed_entry->idx - 1;
8924 } else if (idx + 1 > g)
8925 ref_scroll_up(s, idx - g + 1);
8927 if (g < nlines && s->first_displayed_entry->idx == 0)
8928 s->selected = g - 1;
8930 return NULL;
8934 static const struct got_error *
8935 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8937 const struct got_error *err = NULL;
8938 struct tog_ref_view_state *s = &view->state.ref;
8939 struct tog_reflist_entry *re;
8940 int n, nscroll = view->nlines - 1;
8942 if (view->gline)
8943 return ref_goto_line(view, nscroll);
8945 switch (ch) {
8946 case '0':
8947 case '$':
8948 case KEY_RIGHT:
8949 case 'l':
8950 case KEY_LEFT:
8951 case 'h':
8952 horizontal_scroll_input(view, ch);
8953 break;
8954 case 'i':
8955 s->show_ids = !s->show_ids;
8956 view->count = 0;
8957 break;
8958 case 'm':
8959 s->show_date = !s->show_date;
8960 view->count = 0;
8961 break;
8962 case 'o':
8963 s->sort_by_date = !s->sort_by_date;
8964 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8965 view->count = 0;
8966 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8967 got_ref_cmp_by_commit_timestamp_descending :
8968 tog_ref_cmp_by_name, s->repo);
8969 if (err)
8970 break;
8971 got_reflist_object_id_map_free(tog_refs_idmap);
8972 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8973 &tog_refs, s->repo);
8974 if (err)
8975 break;
8976 ref_view_free_refs(s);
8977 err = ref_view_load_refs(s);
8978 break;
8979 case KEY_ENTER:
8980 case '\r':
8981 view->count = 0;
8982 if (!s->selected_entry)
8983 break;
8984 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8985 break;
8986 case 'T':
8987 view->count = 0;
8988 if (!s->selected_entry)
8989 break;
8990 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8991 break;
8992 case 'g':
8993 case '=':
8994 case KEY_HOME:
8995 s->selected = 0;
8996 view->count = 0;
8997 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8998 break;
8999 case 'G':
9000 case '*':
9001 case KEY_END: {
9002 int eos = view->nlines - 1;
9004 if (view->mode == TOG_VIEW_SPLIT_HRZN)
9005 --eos; /* border */
9006 s->selected = 0;
9007 view->count = 0;
9008 re = TAILQ_LAST(&s->refs, tog_reflist_head);
9009 for (n = 0; n < eos; n++) {
9010 if (re == NULL)
9011 break;
9012 s->first_displayed_entry = re;
9013 re = TAILQ_PREV(re, tog_reflist_head, entry);
9015 if (n > 0)
9016 s->selected = n - 1;
9017 break;
9019 case 'k':
9020 case KEY_UP:
9021 case CTRL('p'):
9022 if (s->selected > 0) {
9023 s->selected--;
9024 break;
9026 ref_scroll_up(s, 1);
9027 if (s->selected_entry == TAILQ_FIRST(&s->refs))
9028 view->count = 0;
9029 break;
9030 case CTRL('u'):
9031 case 'u':
9032 nscroll /= 2;
9033 /* FALL THROUGH */
9034 case KEY_PPAGE:
9035 case CTRL('b'):
9036 case 'b':
9037 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
9038 s->selected -= MIN(nscroll, s->selected);
9039 ref_scroll_up(s, MAX(0, nscroll));
9040 if (s->selected_entry == TAILQ_FIRST(&s->refs))
9041 view->count = 0;
9042 break;
9043 case 'j':
9044 case KEY_DOWN:
9045 case CTRL('n'):
9046 if (s->selected < s->ndisplayed - 1) {
9047 s->selected++;
9048 break;
9050 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
9051 /* can't scroll any further */
9052 view->count = 0;
9053 break;
9055 ref_scroll_down(view, 1);
9056 break;
9057 case CTRL('d'):
9058 case 'd':
9059 nscroll /= 2;
9060 /* FALL THROUGH */
9061 case KEY_NPAGE:
9062 case CTRL('f'):
9063 case 'f':
9064 case ' ':
9065 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
9066 /* can't scroll any further; move cursor down */
9067 if (s->selected < s->ndisplayed - 1)
9068 s->selected += MIN(nscroll,
9069 s->ndisplayed - s->selected - 1);
9070 if (view->count > 1 && s->selected < s->ndisplayed - 1)
9071 s->selected += s->ndisplayed - s->selected - 1;
9072 view->count = 0;
9073 break;
9075 ref_scroll_down(view, nscroll);
9076 break;
9077 case CTRL('l'):
9078 view->count = 0;
9079 tog_free_refs();
9080 err = tog_load_refs(s->repo, s->sort_by_date);
9081 if (err)
9082 break;
9083 ref_view_free_refs(s);
9084 err = ref_view_load_refs(s);
9085 break;
9086 case KEY_RESIZE:
9087 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
9088 s->selected = view->nlines - 2;
9089 break;
9090 default:
9091 view->count = 0;
9092 break;
9095 return err;
9098 __dead static void
9099 usage_ref(void)
9101 endwin();
9102 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
9103 getprogname());
9104 exit(1);
9107 static const struct got_error *
9108 cmd_ref(int argc, char *argv[])
9110 const struct got_error *error;
9111 struct got_repository *repo = NULL;
9112 struct got_worktree *worktree = NULL;
9113 char *cwd = NULL, *repo_path = NULL;
9114 int ch;
9115 struct tog_view *view;
9116 int *pack_fds = NULL;
9118 while ((ch = getopt(argc, argv, "r:")) != -1) {
9119 switch (ch) {
9120 case 'r':
9121 repo_path = realpath(optarg, NULL);
9122 if (repo_path == NULL)
9123 return got_error_from_errno2("realpath",
9124 optarg);
9125 break;
9126 default:
9127 usage_ref();
9128 /* NOTREACHED */
9132 argc -= optind;
9133 argv += optind;
9135 if (argc > 1)
9136 usage_ref();
9138 error = got_repo_pack_fds_open(&pack_fds);
9139 if (error != NULL)
9140 goto done;
9142 if (repo_path == NULL) {
9143 cwd = getcwd(NULL, 0);
9144 if (cwd == NULL)
9145 return got_error_from_errno("getcwd");
9146 error = got_worktree_open(&worktree, cwd, NULL);
9147 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9148 goto done;
9149 if (worktree)
9150 repo_path =
9151 strdup(got_worktree_get_repo_path(worktree));
9152 else
9153 repo_path = strdup(cwd);
9154 if (repo_path == NULL) {
9155 error = got_error_from_errno("strdup");
9156 goto done;
9160 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9161 if (error != NULL)
9162 goto done;
9164 init_curses();
9166 error = apply_unveil(got_repo_get_path(repo), NULL);
9167 if (error)
9168 goto done;
9170 error = tog_load_refs(repo, 0);
9171 if (error)
9172 goto done;
9174 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
9175 if (view == NULL) {
9176 error = got_error_from_errno("view_open");
9177 goto done;
9180 error = open_ref_view(view, repo);
9181 if (error)
9182 goto done;
9184 if (worktree) {
9185 error = set_tog_base_commit(repo, worktree);
9186 if (error != NULL)
9187 goto done;
9189 /* Release work tree lock. */
9190 got_worktree_close(worktree);
9191 worktree = NULL;
9194 error = view_loop(view);
9196 done:
9197 free(tog_base_commit.id);
9198 free(repo_path);
9199 free(cwd);
9200 if (worktree != NULL)
9201 got_worktree_close(worktree);
9202 if (repo) {
9203 const struct got_error *close_err = got_repo_close(repo);
9204 if (close_err)
9205 error = close_err;
9207 if (pack_fds) {
9208 const struct got_error *pack_err =
9209 got_repo_pack_fds_close(pack_fds);
9210 if (error == NULL)
9211 error = pack_err;
9213 tog_free_refs();
9214 return error;
9217 static const struct got_error*
9218 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
9219 const char *str)
9221 size_t len;
9223 if (win == NULL)
9224 win = stdscr;
9226 len = strlen(str);
9227 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
9229 if (focus)
9230 wstandout(win);
9231 if (mvwprintw(win, y, x, "%s", str) == ERR)
9232 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
9233 if (focus)
9234 wstandend(win);
9236 return NULL;
9239 static const struct got_error *
9240 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
9242 off_t *p;
9244 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
9245 if (p == NULL) {
9246 free(*line_offsets);
9247 *line_offsets = NULL;
9248 return got_error_from_errno("reallocarray");
9251 *line_offsets = p;
9252 (*line_offsets)[*nlines] = off;
9253 ++(*nlines);
9254 return NULL;
9257 static const struct got_error *
9258 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
9260 *ret = 0;
9262 for (;n > 0; --n, ++km) {
9263 char *t0, *t, *k;
9264 size_t len = 1;
9266 if (km->keys == NULL)
9267 continue;
9269 t = t0 = strdup(km->keys);
9270 if (t0 == NULL)
9271 return got_error_from_errno("strdup");
9273 len += strlen(t);
9274 while ((k = strsep(&t, " ")) != NULL)
9275 len += strlen(k) > 1 ? 2 : 0;
9276 free(t0);
9277 *ret = MAX(*ret, len);
9280 return NULL;
9284 * Write keymap section headers, keys, and key info in km to f.
9285 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9286 * wrap control and symbolic keys in guillemets, else use <>.
9288 static const struct got_error *
9289 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9291 int n, len = width;
9293 if (km->keys) {
9294 static const char *u8_glyph[] = {
9295 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9296 "\xe2\x80\xba" /* U+203A (utf8 >) */
9298 char *t0, *t, *k;
9299 int cs, s, first = 1;
9301 cs = got_locale_is_utf8();
9303 t = t0 = strdup(km->keys);
9304 if (t0 == NULL)
9305 return got_error_from_errno("strdup");
9307 len = strlen(km->keys);
9308 while ((k = strsep(&t, " ")) != NULL) {
9309 s = strlen(k) > 1; /* control or symbolic key */
9310 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9311 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9312 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9313 if (n < 0) {
9314 free(t0);
9315 return got_error_from_errno("fprintf");
9317 first = 0;
9318 len += s ? 2 : 0;
9319 *off += n;
9321 free(t0);
9323 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9324 if (n < 0)
9325 return got_error_from_errno("fprintf");
9326 *off += n;
9328 return NULL;
9331 static const struct got_error *
9332 format_help(struct tog_help_view_state *s)
9334 const struct got_error *err = NULL;
9335 off_t off = 0;
9336 int i, max, n, show = s->all;
9337 static const struct tog_key_map km[] = {
9338 #define KEYMAP_(info, type) { NULL, (info), type }
9339 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9340 GENERATE_HELP
9341 #undef KEYMAP_
9342 #undef KEY_
9345 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9346 if (err)
9347 return err;
9349 n = nitems(km);
9350 err = max_key_str(&max, km, n);
9351 if (err)
9352 return err;
9354 for (i = 0; i < n; ++i) {
9355 if (km[i].keys == NULL) {
9356 show = s->all;
9357 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9358 km[i].type == s->type || s->all)
9359 show = 1;
9361 if (show) {
9362 err = format_help_line(&off, s->f, &km[i], max);
9363 if (err)
9364 return err;
9365 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9366 if (err)
9367 return err;
9370 fputc('\n', s->f);
9371 ++off;
9372 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9373 return err;
9376 static const struct got_error *
9377 create_help(struct tog_help_view_state *s)
9379 FILE *f;
9380 const struct got_error *err;
9382 free(s->line_offsets);
9383 s->line_offsets = NULL;
9384 s->nlines = 0;
9386 f = got_opentemp();
9387 if (f == NULL)
9388 return got_error_from_errno("got_opentemp");
9389 s->f = f;
9391 err = format_help(s);
9392 if (err)
9393 return err;
9395 if (s->f && fflush(s->f) != 0)
9396 return got_error_from_errno("fflush");
9398 return NULL;
9401 static const struct got_error *
9402 search_start_help_view(struct tog_view *view)
9404 view->state.help.matched_line = 0;
9405 return NULL;
9408 static void
9409 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9410 size_t *nlines, int **first, int **last, int **match, int **selected)
9412 struct tog_help_view_state *s = &view->state.help;
9414 *f = s->f;
9415 *nlines = s->nlines;
9416 *line_offsets = s->line_offsets;
9417 *match = &s->matched_line;
9418 *first = &s->first_displayed_line;
9419 *last = &s->last_displayed_line;
9420 *selected = &s->selected_line;
9423 static const struct got_error *
9424 show_help_view(struct tog_view *view)
9426 struct tog_help_view_state *s = &view->state.help;
9427 const struct got_error *err;
9428 regmatch_t *regmatch = &view->regmatch;
9429 wchar_t *wline;
9430 char *line;
9431 ssize_t linelen;
9432 size_t linesz = 0;
9433 int width, nprinted = 0, rc = 0;
9434 int eos = view->nlines;
9436 if (view_is_hsplit_top(view))
9437 --eos; /* account for border */
9439 s->lineno = 0;
9440 rewind(s->f);
9441 werase(view->window);
9443 if (view->gline > s->nlines - 1)
9444 view->gline = s->nlines - 1;
9446 err = win_draw_center(view->window, 0, 0, view->ncols,
9447 view_needs_focus_indication(view),
9448 "tog help (press q to return to tog)");
9449 if (err)
9450 return err;
9451 if (eos <= 1)
9452 return NULL;
9453 waddstr(view->window, "\n\n");
9454 eos -= 2;
9456 s->eof = 0;
9457 view->maxx = 0;
9458 line = NULL;
9459 while (eos > 0 && nprinted < eos) {
9460 attr_t attr = 0;
9462 linelen = getline(&line, &linesz, s->f);
9463 if (linelen == -1) {
9464 if (!feof(s->f)) {
9465 free(line);
9466 return got_ferror(s->f, GOT_ERR_IO);
9468 s->eof = 1;
9469 break;
9471 if (++s->lineno < s->first_displayed_line)
9472 continue;
9473 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9474 continue;
9475 if (s->lineno == view->hiline)
9476 attr = A_STANDOUT;
9478 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9479 view->x ? 1 : 0);
9480 if (err) {
9481 free(line);
9482 return err;
9484 view->maxx = MAX(view->maxx, width);
9485 free(wline);
9486 wline = NULL;
9488 if (attr)
9489 wattron(view->window, attr);
9490 if (s->first_displayed_line + nprinted == s->matched_line &&
9491 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9492 err = add_matched_line(&width, line, view->ncols - 1, 0,
9493 view->window, view->x, regmatch);
9494 if (err) {
9495 free(line);
9496 return err;
9498 } else {
9499 int skip;
9501 err = format_line(&wline, &width, &skip, line,
9502 view->x, view->ncols, 0, view->x ? 1 : 0);
9503 if (err) {
9504 free(line);
9505 return err;
9507 waddwstr(view->window, &wline[skip]);
9508 free(wline);
9509 wline = NULL;
9511 if (s->lineno == view->hiline) {
9512 while (width++ < view->ncols)
9513 waddch(view->window, ' ');
9514 } else {
9515 if (width < view->ncols)
9516 waddch(view->window, '\n');
9518 if (attr)
9519 wattroff(view->window, attr);
9520 if (++nprinted == 1)
9521 s->first_displayed_line = s->lineno;
9523 free(line);
9524 if (nprinted > 0)
9525 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9526 else
9527 s->last_displayed_line = s->first_displayed_line;
9529 view_border(view);
9531 if (s->eof) {
9532 rc = waddnstr(view->window,
9533 "See the tog(1) manual page for full documentation",
9534 view->ncols - 1);
9535 if (rc == ERR)
9536 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9537 } else {
9538 wmove(view->window, view->nlines - 1, 0);
9539 wclrtoeol(view->window);
9540 wstandout(view->window);
9541 rc = waddnstr(view->window, "scroll down for more...",
9542 view->ncols - 1);
9543 if (rc == ERR)
9544 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9545 if (getcurx(view->window) < view->ncols - 6) {
9546 rc = wprintw(view->window, "[%.0f%%]",
9547 100.00 * s->last_displayed_line / s->nlines);
9548 if (rc == ERR)
9549 return got_error_msg(GOT_ERR_IO, "wprintw");
9551 wstandend(view->window);
9554 return NULL;
9557 static const struct got_error *
9558 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9560 struct tog_help_view_state *s = &view->state.help;
9561 const struct got_error *err = NULL;
9562 char *line = NULL;
9563 ssize_t linelen;
9564 size_t linesz = 0;
9565 int eos, nscroll;
9567 eos = nscroll = view->nlines;
9568 if (view_is_hsplit_top(view))
9569 --eos; /* border */
9571 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9573 switch (ch) {
9574 case '0':
9575 case '$':
9576 case KEY_RIGHT:
9577 case 'l':
9578 case KEY_LEFT:
9579 case 'h':
9580 horizontal_scroll_input(view, ch);
9581 break;
9582 case 'g':
9583 case KEY_HOME:
9584 s->first_displayed_line = 1;
9585 view->count = 0;
9586 break;
9587 case 'G':
9588 case KEY_END:
9589 view->count = 0;
9590 if (s->eof)
9591 break;
9592 s->first_displayed_line = (s->nlines - eos) + 3;
9593 s->eof = 1;
9594 break;
9595 case 'k':
9596 case KEY_UP:
9597 if (s->first_displayed_line > 1)
9598 --s->first_displayed_line;
9599 else
9600 view->count = 0;
9601 break;
9602 case CTRL('u'):
9603 case 'u':
9604 nscroll /= 2;
9605 /* FALL THROUGH */
9606 case KEY_PPAGE:
9607 case CTRL('b'):
9608 case 'b':
9609 if (s->first_displayed_line == 1) {
9610 view->count = 0;
9611 break;
9613 while (--nscroll > 0 && s->first_displayed_line > 1)
9614 s->first_displayed_line--;
9615 break;
9616 case 'j':
9617 case KEY_DOWN:
9618 case CTRL('n'):
9619 if (!s->eof)
9620 ++s->first_displayed_line;
9621 else
9622 view->count = 0;
9623 break;
9624 case CTRL('d'):
9625 case 'd':
9626 nscroll /= 2;
9627 /* FALL THROUGH */
9628 case KEY_NPAGE:
9629 case CTRL('f'):
9630 case 'f':
9631 case ' ':
9632 if (s->eof) {
9633 view->count = 0;
9634 break;
9636 while (!s->eof && --nscroll > 0) {
9637 linelen = getline(&line, &linesz, s->f);
9638 s->first_displayed_line++;
9639 if (linelen == -1) {
9640 if (feof(s->f))
9641 s->eof = 1;
9642 else
9643 err = got_ferror(s->f, GOT_ERR_IO);
9644 break;
9647 free(line);
9648 break;
9649 default:
9650 view->count = 0;
9651 break;
9654 return err;
9657 static const struct got_error *
9658 close_help_view(struct tog_view *view)
9660 struct tog_help_view_state *s = &view->state.help;
9662 free(s->line_offsets);
9663 s->line_offsets = NULL;
9664 if (fclose(s->f) == EOF)
9665 return got_error_from_errno("fclose");
9667 return NULL;
9670 static const struct got_error *
9671 reset_help_view(struct tog_view *view)
9673 struct tog_help_view_state *s = &view->state.help;
9676 if (s->f && fclose(s->f) == EOF)
9677 return got_error_from_errno("fclose");
9679 wclear(view->window);
9680 view->count = 0;
9681 view->x = 0;
9682 s->all = !s->all;
9683 s->first_displayed_line = 1;
9684 s->last_displayed_line = view->nlines;
9685 s->matched_line = 0;
9687 return create_help(s);
9690 static const struct got_error *
9691 open_help_view(struct tog_view *view, struct tog_view *parent)
9693 const struct got_error *err = NULL;
9694 struct tog_help_view_state *s = &view->state.help;
9696 s->type = (enum tog_keymap_type)parent->type;
9697 s->first_displayed_line = 1;
9698 s->last_displayed_line = view->nlines;
9699 s->selected_line = 1;
9701 view->show = show_help_view;
9702 view->input = input_help_view;
9703 view->reset = reset_help_view;
9704 view->close = close_help_view;
9705 view->search_start = search_start_help_view;
9706 view->search_setup = search_setup_help_view;
9707 view->search_next = search_next_view_match;
9709 err = create_help(s);
9710 return err;
9713 static const struct got_error *
9714 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9715 enum tog_view_type request, int y, int x)
9717 const struct got_error *err = NULL;
9719 *new_view = NULL;
9721 switch (request) {
9722 case TOG_VIEW_DIFF:
9723 if (view->type == TOG_VIEW_LOG) {
9724 struct tog_log_view_state *s = &view->state.log;
9726 err = open_diff_view_for_commit(new_view, y, x,
9727 s->selected_entry->commit, s->selected_entry->id,
9728 view, s->repo);
9729 } else
9730 return got_error_msg(GOT_ERR_NOT_IMPL,
9731 "parent/child view pair not supported");
9732 break;
9733 case TOG_VIEW_BLAME:
9734 if (view->type == TOG_VIEW_TREE) {
9735 struct tog_tree_view_state *s = &view->state.tree;
9737 err = blame_tree_entry(new_view, y, x,
9738 s->selected_entry, &s->parents, s->commit_id,
9739 s->repo);
9740 } else
9741 return got_error_msg(GOT_ERR_NOT_IMPL,
9742 "parent/child view pair not supported");
9743 break;
9744 case TOG_VIEW_LOG:
9745 if (view->type == TOG_VIEW_BLAME)
9746 err = log_annotated_line(new_view, y, x,
9747 view->state.blame.repo, view->state.blame.id_to_log);
9748 else if (view->type == TOG_VIEW_TREE)
9749 err = log_selected_tree_entry(new_view, y, x,
9750 &view->state.tree);
9751 else if (view->type == TOG_VIEW_REF)
9752 err = log_ref_entry(new_view, y, x,
9753 view->state.ref.selected_entry,
9754 view->state.ref.repo);
9755 else
9756 return got_error_msg(GOT_ERR_NOT_IMPL,
9757 "parent/child view pair not supported");
9758 break;
9759 case TOG_VIEW_TREE:
9760 if (view->type == TOG_VIEW_LOG)
9761 err = browse_commit_tree(new_view, y, x,
9762 view->state.log.selected_entry,
9763 view->state.log.in_repo_path,
9764 view->state.log.head_ref_name,
9765 view->state.log.repo);
9766 else if (view->type == TOG_VIEW_REF)
9767 err = browse_ref_tree(new_view, y, x,
9768 view->state.ref.selected_entry,
9769 view->state.ref.repo);
9770 else
9771 return got_error_msg(GOT_ERR_NOT_IMPL,
9772 "parent/child view pair not supported");
9773 break;
9774 case TOG_VIEW_REF:
9775 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9776 if (*new_view == NULL)
9777 return got_error_from_errno("view_open");
9778 if (view->type == TOG_VIEW_LOG)
9779 err = open_ref_view(*new_view, view->state.log.repo);
9780 else if (view->type == TOG_VIEW_TREE)
9781 err = open_ref_view(*new_view, view->state.tree.repo);
9782 else
9783 err = got_error_msg(GOT_ERR_NOT_IMPL,
9784 "parent/child view pair not supported");
9785 if (err)
9786 view_close(*new_view);
9787 break;
9788 case TOG_VIEW_HELP:
9789 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9790 if (*new_view == NULL)
9791 return got_error_from_errno("view_open");
9792 err = open_help_view(*new_view, view);
9793 if (err)
9794 view_close(*new_view);
9795 break;
9796 default:
9797 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9800 return err;
9804 * If view was scrolled down to move the selected line into view when opening a
9805 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9807 static void
9808 offset_selection_up(struct tog_view *view)
9810 switch (view->type) {
9811 case TOG_VIEW_BLAME: {
9812 struct tog_blame_view_state *s = &view->state.blame;
9813 if (s->first_displayed_line == 1) {
9814 s->selected_line = MAX(s->selected_line - view->offset,
9815 1);
9816 break;
9818 if (s->first_displayed_line > view->offset)
9819 s->first_displayed_line -= view->offset;
9820 else
9821 s->first_displayed_line = 1;
9822 s->selected_line += view->offset;
9823 break;
9825 case TOG_VIEW_LOG:
9826 log_scroll_up(&view->state.log, view->offset);
9827 view->state.log.selected += view->offset;
9828 break;
9829 case TOG_VIEW_REF:
9830 ref_scroll_up(&view->state.ref, view->offset);
9831 view->state.ref.selected += view->offset;
9832 break;
9833 case TOG_VIEW_TREE:
9834 tree_scroll_up(&view->state.tree, view->offset);
9835 view->state.tree.selected += view->offset;
9836 break;
9837 default:
9838 break;
9841 view->offset = 0;
9845 * If the selected line is in the section of screen covered by the bottom split,
9846 * scroll down offset lines to move it into view and index its new position.
9848 static const struct got_error *
9849 offset_selection_down(struct tog_view *view)
9851 const struct got_error *err = NULL;
9852 const struct got_error *(*scrolld)(struct tog_view *, int);
9853 int *selected = NULL;
9854 int header, offset;
9856 switch (view->type) {
9857 case TOG_VIEW_BLAME: {
9858 struct tog_blame_view_state *s = &view->state.blame;
9859 header = 3;
9860 scrolld = NULL;
9861 if (s->selected_line > view->nlines - header) {
9862 offset = abs(view->nlines - s->selected_line - header);
9863 s->first_displayed_line += offset;
9864 s->selected_line -= offset;
9865 view->offset = offset;
9867 break;
9869 case TOG_VIEW_LOG: {
9870 struct tog_log_view_state *s = &view->state.log;
9871 scrolld = &log_scroll_down;
9872 header = view_is_parent_view(view) ? 3 : 2;
9873 selected = &s->selected;
9874 break;
9876 case TOG_VIEW_REF: {
9877 struct tog_ref_view_state *s = &view->state.ref;
9878 scrolld = &ref_scroll_down;
9879 header = 3;
9880 selected = &s->selected;
9881 break;
9883 case TOG_VIEW_TREE: {
9884 struct tog_tree_view_state *s = &view->state.tree;
9885 scrolld = &tree_scroll_down;
9886 header = 5;
9887 selected = &s->selected;
9888 break;
9890 default:
9891 selected = NULL;
9892 scrolld = NULL;
9893 header = 0;
9894 break;
9897 if (selected && *selected > view->nlines - header) {
9898 offset = abs(view->nlines - *selected - header);
9899 view->offset = offset;
9900 if (scrolld && offset) {
9901 err = scrolld(view, offset);
9902 *selected -= offset;
9906 return err;
9909 static void
9910 list_commands(FILE *fp)
9912 size_t i;
9914 fprintf(fp, "commands:");
9915 for (i = 0; i < nitems(tog_commands); i++) {
9916 const struct tog_cmd *cmd = &tog_commands[i];
9917 fprintf(fp, " %s", cmd->name);
9919 fputc('\n', fp);
9922 __dead static void
9923 usage(int hflag, int status)
9925 FILE *fp = (status == 0) ? stdout : stderr;
9927 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9928 getprogname());
9929 if (hflag) {
9930 fprintf(fp, "lazy usage: %s path\n", getprogname());
9931 list_commands(fp);
9933 exit(status);
9936 static char **
9937 make_argv(int argc, ...)
9939 va_list ap;
9940 char **argv;
9941 int i;
9943 va_start(ap, argc);
9945 argv = calloc(argc, sizeof(char *));
9946 if (argv == NULL)
9947 err(1, "calloc");
9948 for (i = 0; i < argc; i++) {
9949 argv[i] = strdup(va_arg(ap, char *));
9950 if (argv[i] == NULL)
9951 err(1, "strdup");
9954 va_end(ap);
9955 return argv;
9959 * Try to convert 'tog path' into a 'tog log path' command.
9960 * The user could simply have mistyped the command rather than knowingly
9961 * provided a path. So check whether argv[0] can in fact be resolved
9962 * to a path in the HEAD commit and print a special error if not.
9963 * This hack is for mpi@ <3
9965 static const struct got_error *
9966 tog_log_with_path(int argc, char *argv[])
9968 const struct got_error *error = NULL, *close_err;
9969 const struct tog_cmd *cmd = NULL;
9970 struct got_repository *repo = NULL;
9971 struct got_worktree *worktree = NULL;
9972 struct got_object_id *commit_id = NULL, *id = NULL;
9973 struct got_commit_object *commit = NULL;
9974 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9975 char *commit_id_str = NULL, **cmd_argv = NULL;
9976 int *pack_fds = NULL;
9978 cwd = getcwd(NULL, 0);
9979 if (cwd == NULL)
9980 return got_error_from_errno("getcwd");
9982 error = got_repo_pack_fds_open(&pack_fds);
9983 if (error != NULL)
9984 goto done;
9986 error = got_worktree_open(&worktree, cwd, NULL);
9987 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9988 goto done;
9990 if (worktree)
9991 repo_path = strdup(got_worktree_get_repo_path(worktree));
9992 else
9993 repo_path = strdup(cwd);
9994 if (repo_path == NULL) {
9995 error = got_error_from_errno("strdup");
9996 goto done;
9999 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
10000 if (error != NULL)
10001 goto done;
10003 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
10004 repo, worktree);
10005 if (error)
10006 goto done;
10008 error = tog_load_refs(repo, 0);
10009 if (error)
10010 goto done;
10011 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
10012 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
10013 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
10014 if (error)
10015 goto done;
10017 if (worktree) {
10018 got_worktree_close(worktree);
10019 worktree = NULL;
10022 error = got_object_open_as_commit(&commit, repo, commit_id);
10023 if (error)
10024 goto done;
10026 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
10027 if (error) {
10028 if (error->code != GOT_ERR_NO_TREE_ENTRY)
10029 goto done;
10030 fprintf(stderr, "%s: '%s' is no known command or path\n",
10031 getprogname(), argv[0]);
10032 usage(1, 1);
10033 /* not reached */
10036 error = got_object_id_str(&commit_id_str, commit_id);
10037 if (error)
10038 goto done;
10040 cmd = &tog_commands[0]; /* log */
10041 argc = 4;
10042 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
10043 error = cmd->cmd_main(argc, cmd_argv);
10044 done:
10045 if (repo) {
10046 close_err = got_repo_close(repo);
10047 if (error == NULL)
10048 error = close_err;
10050 if (commit)
10051 got_object_commit_close(commit);
10052 if (worktree)
10053 got_worktree_close(worktree);
10054 if (pack_fds) {
10055 const struct got_error *pack_err =
10056 got_repo_pack_fds_close(pack_fds);
10057 if (error == NULL)
10058 error = pack_err;
10060 free(id);
10061 free(commit_id_str);
10062 free(commit_id);
10063 free(cwd);
10064 free(repo_path);
10065 free(in_repo_path);
10066 if (cmd_argv) {
10067 int i;
10068 for (i = 0; i < argc; i++)
10069 free(cmd_argv[i]);
10070 free(cmd_argv);
10072 tog_free_refs();
10073 return error;
10076 int
10077 main(int argc, char *argv[])
10079 const struct got_error *io_err, *error = NULL;
10080 const struct tog_cmd *cmd = NULL;
10081 int ch, hflag = 0, Vflag = 0;
10082 char **cmd_argv = NULL;
10083 static const struct option longopts[] = {
10084 { "version", no_argument, NULL, 'V' },
10085 { NULL, 0, NULL, 0}
10087 char *diff_algo_str = NULL;
10088 const char *test_script_path;
10090 setlocale(LC_CTYPE, "");
10093 * Test mode init must happen before pledge() because "tty" will
10094 * not allow TTY-related ioctls to occur via regular files.
10096 test_script_path = getenv("TOG_TEST_SCRIPT");
10097 if (test_script_path != NULL) {
10098 error = init_mock_term(test_script_path);
10099 if (error) {
10100 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10101 return 1;
10103 } else if (!isatty(STDIN_FILENO))
10104 errx(1, "standard input is not a tty");
10106 #if !defined(PROFILE)
10107 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
10108 NULL) == -1)
10109 err(1, "pledge");
10110 #endif
10112 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
10113 switch (ch) {
10114 case 'h':
10115 hflag = 1;
10116 break;
10117 case 'V':
10118 Vflag = 1;
10119 break;
10120 default:
10121 usage(hflag, 1);
10122 /* NOTREACHED */
10126 argc -= optind;
10127 argv += optind;
10128 optind = 1;
10129 optreset = 1;
10131 if (Vflag) {
10132 got_version_print_str();
10133 return 0;
10136 if (argc == 0) {
10137 if (hflag)
10138 usage(hflag, 0);
10139 /* Build an argument vector which runs a default command. */
10140 cmd = &tog_commands[0];
10141 argc = 1;
10142 cmd_argv = make_argv(argc, cmd->name);
10143 } else {
10144 size_t i;
10146 /* Did the user specify a command? */
10147 for (i = 0; i < nitems(tog_commands); i++) {
10148 if (strncmp(tog_commands[i].name, argv[0],
10149 strlen(argv[0])) == 0) {
10150 cmd = &tog_commands[i];
10151 break;
10156 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
10157 if (diff_algo_str) {
10158 if (strcasecmp(diff_algo_str, "patience") == 0)
10159 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
10160 if (strcasecmp(diff_algo_str, "myers") == 0)
10161 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
10164 tog_base_commit.idx = -1;
10165 tog_base_commit.marker = GOT_WORKTREE_STATE_UNKNOWN;
10167 if (cmd == NULL) {
10168 if (argc != 1)
10169 usage(0, 1);
10170 /* No command specified; try log with a path */
10171 error = tog_log_with_path(argc, argv);
10172 } else {
10173 if (hflag)
10174 cmd->cmd_usage();
10175 else
10176 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
10179 if (using_mock_io) {
10180 io_err = tog_io_close();
10181 if (error == NULL)
10182 error = io_err;
10184 endwin();
10185 if (cmd_argv) {
10186 int i;
10187 for (i = 0; i < argc; i++)
10188 free(cmd_argv[i]);
10189 free(cmd_argv);
10192 if (error && error->code != GOT_ERR_CANCELLED &&
10193 error->code != GOT_ERR_EOF &&
10194 error->code != GOT_ERR_PRIVSEP_EXIT &&
10195 error->code != GOT_ERR_PRIVSEP_PIPE &&
10196 !(error->code == GOT_ERR_ERRNO && errno == EINTR)) {
10197 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10198 return 1;
10200 return 0;