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;
2436 if (tog_io.wait_for_ui && s->thread_args.need_commit_marker) {
2437 int rc;
2439 rc = pthread_cond_wait(&s->thread_args.log_loaded, &tog_mutex);
2440 if (rc)
2441 return got_error_set_errno(rc, "pthread_cond_wait");
2444 committer_time = got_object_commit_get_committer_time(commit);
2445 if (gmtime_r(&committer_time, &tm) == NULL)
2446 return got_error_from_errno("gmtime_r");
2447 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2448 return got_error(GOT_ERR_NO_SPACE);
2450 if (avail <= date_display_cols)
2451 limit = MIN(sizeof(datebuf) - 1, avail);
2452 else
2453 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2454 tc = get_color(&s->colors, TOG_COLOR_DATE);
2455 if (tc)
2456 wattr_on(view->window,
2457 COLOR_PAIR(tc->colorpair), NULL);
2458 waddnstr(view->window, datebuf, limit);
2459 if (tc)
2460 wattr_off(view->window,
2461 COLOR_PAIR(tc->colorpair), NULL);
2462 col = limit;
2463 if (col > avail)
2464 goto done;
2466 if (avail >= 120) {
2467 char *id_str;
2468 err = got_object_id_str(&id_str, id);
2469 if (err)
2470 goto done;
2471 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2472 if (tc)
2473 wattr_on(view->window,
2474 COLOR_PAIR(tc->colorpair), NULL);
2475 wprintw(view->window, "%.8s ", id_str);
2476 if (tc)
2477 wattr_off(view->window,
2478 COLOR_PAIR(tc->colorpair), NULL);
2479 free(id_str);
2480 col += 9;
2481 if (col > avail)
2482 goto done;
2485 if (s->use_committer)
2486 author = strdup(got_object_commit_get_committer(commit));
2487 else
2488 author = strdup(got_object_commit_get_author(commit));
2489 if (author == NULL) {
2490 err = got_error_from_errno("strdup");
2491 goto done;
2493 err = format_author(&wauthor, &author_width, author, avail - col, col);
2494 if (err)
2495 goto done;
2496 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2497 if (tc)
2498 wattr_on(view->window,
2499 COLOR_PAIR(tc->colorpair), NULL);
2500 waddwstr(view->window, wauthor);
2501 col += author_width;
2502 while (col < avail && author_width < author_display_cols + 2) {
2503 if (tog_base_commit.marker != GOT_WORKTREE_STATE_UNKNOWN &&
2504 author_width == marker_column &&
2505 entry->idx == tog_base_commit.idx && !s->limit_view) {
2506 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2507 if (tc)
2508 wattr_on(view->window,
2509 COLOR_PAIR(tc->colorpair), NULL);
2510 waddch(view->window, tog_base_commit.marker);
2511 if (tc)
2512 wattr_off(view->window,
2513 COLOR_PAIR(tc->colorpair), NULL);
2514 } else
2515 waddch(view->window, ' ');
2516 col++;
2517 author_width++;
2519 if (tc)
2520 wattr_off(view->window,
2521 COLOR_PAIR(tc->colorpair), NULL);
2522 if (col > avail)
2523 goto done;
2525 err = got_object_commit_get_logmsg(&logmsg0, commit);
2526 if (err)
2527 goto done;
2528 logmsg = logmsg0;
2529 while (*logmsg == '\n')
2530 logmsg++;
2531 newline = strchr(logmsg, '\n');
2532 if (newline)
2533 *newline = '\0';
2535 limit = avail - col;
2536 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2537 limit--; /* for the border */
2539 /* Prepend reference labels to log message if possible .*/
2540 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, id);
2541 err = build_refs_str(&refs_str, refs, id, s->repo);
2542 if (err)
2543 goto done;
2544 if (refs_str) {
2545 char *rs;
2547 if (asprintf(&rs, "[%s]", refs_str) == -1) {
2548 err = got_error_from_errno("asprintf");
2549 goto done;
2551 err = format_line(&wrefstr, &refstr_width,
2552 &scrollx, rs, view->x, limit, col, 1);
2553 free(rs);
2554 if (err)
2555 goto done;
2556 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2557 if (tc)
2558 wattr_on(view->window,
2559 COLOR_PAIR(tc->colorpair), NULL);
2560 waddwstr(view->window, &wrefstr[scrollx]);
2561 if (tc)
2562 wattr_off(view->window,
2563 COLOR_PAIR(tc->colorpair), NULL);
2564 col += MAX(refstr_width, 0);
2565 if (col > avail)
2566 goto done;
2568 if (col < avail) {
2569 waddch(view->window, ' ');
2570 col++;
2573 if (refstr_width > 0)
2574 logmsg_x = 0;
2575 else {
2576 int unscrolled_refstr_width;
2577 size_t len = wcslen(wrefstr);
2580 * No need to check for -1 return value here since
2581 * unprintables have been replaced by span_wline().
2583 unscrolled_refstr_width = wcswidth(wrefstr, len);
2584 unscrolled_refstr_width += 1; /* trailing space */
2585 logmsg_x = view->x - unscrolled_refstr_width;
2588 limit = avail - col;
2589 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2590 limit--; /* for the border */
2591 } else
2592 logmsg_x = view->x;
2594 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, logmsg_x,
2595 limit, col, 1);
2596 if (err)
2597 goto done;
2598 waddwstr(view->window, &wlogmsg[scrollx]);
2599 col += MAX(logmsg_width, 0);
2600 while (col < avail) {
2601 waddch(view->window, ' ');
2602 col++;
2604 done:
2605 free(logmsg0);
2606 free(wlogmsg);
2607 free(wrefstr);
2608 free(refs_str);
2609 free(author);
2610 free(wauthor);
2611 free(line);
2612 return err;
2615 static struct commit_queue_entry *
2616 alloc_commit_queue_entry(struct got_commit_object *commit,
2617 struct got_object_id *id)
2619 struct commit_queue_entry *entry;
2620 struct got_object_id *dup;
2622 entry = calloc(1, sizeof(*entry));
2623 if (entry == NULL)
2624 return NULL;
2626 dup = got_object_id_dup(id);
2627 if (dup == NULL) {
2628 free(entry);
2629 return NULL;
2632 entry->id = dup;
2633 entry->commit = commit;
2634 return entry;
2637 static void
2638 pop_commit(struct commit_queue *commits)
2640 struct commit_queue_entry *entry;
2642 entry = TAILQ_FIRST(&commits->head);
2643 TAILQ_REMOVE(&commits->head, entry, entry);
2644 got_object_commit_close(entry->commit);
2645 commits->ncommits--;
2646 free(entry->id);
2647 free(entry);
2650 static void
2651 free_commits(struct commit_queue *commits)
2653 while (!TAILQ_EMPTY(&commits->head))
2654 pop_commit(commits);
2657 static const struct got_error *
2658 match_commit(int *have_match, struct got_object_id *id,
2659 struct got_commit_object *commit, regex_t *regex)
2661 const struct got_error *err = NULL;
2662 regmatch_t regmatch;
2663 char *id_str = NULL, *logmsg = NULL;
2665 *have_match = 0;
2667 err = got_object_id_str(&id_str, id);
2668 if (err)
2669 return err;
2671 err = got_object_commit_get_logmsg(&logmsg, commit);
2672 if (err)
2673 goto done;
2675 if (regexec(regex, got_object_commit_get_author(commit), 1,
2676 &regmatch, 0) == 0 ||
2677 regexec(regex, got_object_commit_get_committer(commit), 1,
2678 &regmatch, 0) == 0 ||
2679 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2680 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2681 *have_match = 1;
2682 done:
2683 free(id_str);
2684 free(logmsg);
2685 return err;
2688 static const struct got_error *
2689 queue_commits(struct tog_log_thread_args *a)
2691 const struct got_error *err = NULL;
2694 * We keep all commits open throughout the lifetime of the log
2695 * view in order to avoid having to re-fetch commits from disk
2696 * while updating the display.
2698 do {
2699 struct got_object_id id;
2700 struct got_commit_object *commit;
2701 struct commit_queue_entry *entry;
2702 int limit_match = 0;
2703 int errcode;
2705 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2706 NULL, NULL);
2707 if (err)
2708 break;
2710 err = got_object_open_as_commit(&commit, a->repo, &id);
2711 if (err)
2712 break;
2713 entry = alloc_commit_queue_entry(commit, &id);
2714 if (entry == NULL) {
2715 err = got_error_from_errno("alloc_commit_queue_entry");
2716 break;
2719 errcode = pthread_mutex_lock(&tog_mutex);
2720 if (errcode) {
2721 err = got_error_set_errno(errcode,
2722 "pthread_mutex_lock");
2723 break;
2726 entry->idx = a->real_commits->ncommits;
2727 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2728 a->real_commits->ncommits++;
2730 if (*a->limiting) {
2731 err = match_commit(&limit_match, &id, commit,
2732 a->limit_regex);
2733 if (err)
2734 break;
2736 if (limit_match) {
2737 struct commit_queue_entry *matched;
2739 matched = alloc_commit_queue_entry(
2740 entry->commit, entry->id);
2741 if (matched == NULL) {
2742 err = got_error_from_errno(
2743 "alloc_commit_queue_entry");
2744 break;
2746 matched->commit = entry->commit;
2747 got_object_commit_retain(entry->commit);
2749 matched->idx = a->limit_commits->ncommits;
2750 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2751 matched, entry);
2752 a->limit_commits->ncommits++;
2756 * This is how we signal log_thread() that we
2757 * have found a match, and that it should be
2758 * counted as a new entry for the view.
2760 a->limit_match = limit_match;
2763 if (*a->searching == TOG_SEARCH_FORWARD &&
2764 !*a->search_next_done) {
2765 int have_match;
2766 err = match_commit(&have_match, &id, commit, a->regex);
2767 if (err)
2768 break;
2770 if (*a->limiting) {
2771 if (limit_match && have_match)
2772 *a->search_next_done =
2773 TOG_SEARCH_HAVE_MORE;
2774 } else if (have_match)
2775 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2778 errcode = pthread_mutex_unlock(&tog_mutex);
2779 if (errcode && err == NULL)
2780 err = got_error_set_errno(errcode,
2781 "pthread_mutex_unlock");
2782 if (err)
2783 break;
2784 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2786 return err;
2789 static void
2790 select_commit(struct tog_log_view_state *s)
2792 struct commit_queue_entry *entry;
2793 int ncommits = 0;
2795 entry = s->first_displayed_entry;
2796 while (entry) {
2797 if (ncommits == s->selected) {
2798 s->selected_entry = entry;
2799 break;
2801 entry = TAILQ_NEXT(entry, entry);
2802 ncommits++;
2806 static const struct got_error *
2807 draw_commits(struct tog_view *view)
2809 const struct got_error *err = NULL;
2810 struct tog_log_view_state *s = &view->state.log;
2811 struct commit_queue_entry *entry = s->selected_entry;
2812 int limit = view->nlines;
2813 int width;
2814 int ncommits, author_cols = 4, refstr_cols;
2815 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2816 char *refs_str = NULL;
2817 wchar_t *wline;
2818 struct tog_color *tc;
2819 static const size_t date_display_cols = 12;
2820 struct got_reflist_head *refs;
2822 if (view_is_hsplit_top(view))
2823 --limit; /* account for border */
2825 if (s->selected_entry &&
2826 !(view->searching && view->search_next_done == 0)) {
2827 err = got_object_id_str(&id_str, s->selected_entry->id);
2828 if (err)
2829 return err;
2830 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2831 s->selected_entry->id);
2832 err = build_refs_str(&refs_str, refs, s->selected_entry->id,
2833 s->repo);
2834 if (err)
2835 goto done;
2838 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2839 halfdelay(10); /* disable fast refresh */
2841 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2842 if (asprintf(&ncommits_str, " [%d/%d] %s",
2843 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2844 (view->searching && !view->search_next_done) ?
2845 "searching..." : "loading...") == -1) {
2846 err = got_error_from_errno("asprintf");
2847 goto done;
2849 } else {
2850 const char *search_str = NULL;
2851 const char *limit_str = NULL;
2853 if (view->searching) {
2854 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2855 search_str = "no more matches";
2856 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2857 search_str = "no matches found";
2858 else if (!view->search_next_done)
2859 search_str = "searching...";
2862 if (s->limit_view && s->commits->ncommits == 0)
2863 limit_str = "no matches found";
2865 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2866 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2867 search_str ? search_str : (refs_str ? refs_str : ""),
2868 limit_str ? limit_str : "") == -1) {
2869 err = got_error_from_errno("asprintf");
2870 goto done;
2874 free(refs_str);
2875 refs_str = NULL;
2877 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2878 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2879 "........................................",
2880 s->in_repo_path, ncommits_str) == -1) {
2881 err = got_error_from_errno("asprintf");
2882 header = NULL;
2883 goto done;
2885 } else if (asprintf(&header, "commit %s%s",
2886 id_str ? id_str : "........................................",
2887 ncommits_str) == -1) {
2888 err = got_error_from_errno("asprintf");
2889 header = NULL;
2890 goto done;
2892 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2893 if (err)
2894 goto done;
2896 werase(view->window);
2898 if (view_needs_focus_indication(view))
2899 wstandout(view->window);
2900 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2901 if (tc)
2902 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2903 waddwstr(view->window, wline);
2904 while (width < view->ncols) {
2905 waddch(view->window, ' ');
2906 width++;
2908 if (tc)
2909 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2910 if (view_needs_focus_indication(view))
2911 wstandend(view->window);
2912 free(wline);
2913 if (limit <= 1)
2914 goto done;
2916 /* Grow author column size if necessary, and set view->maxx. */
2917 entry = s->first_displayed_entry;
2918 ncommits = 0;
2919 view->maxx = 0;
2920 while (entry) {
2921 struct got_commit_object *c = entry->commit;
2922 char *author, *eol, *msg, *msg0;
2923 wchar_t *wauthor, *wmsg;
2924 int width;
2925 if (ncommits >= limit - 1)
2926 break;
2927 if (s->use_committer)
2928 author = strdup(got_object_commit_get_committer(c));
2929 else
2930 author = strdup(got_object_commit_get_author(c));
2931 if (author == NULL) {
2932 err = got_error_from_errno("strdup");
2933 goto done;
2935 err = format_author(&wauthor, &width, author, COLS,
2936 date_display_cols);
2937 if (author_cols < width)
2938 author_cols = width;
2939 free(wauthor);
2940 free(author);
2941 if (err)
2942 goto done;
2943 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2944 entry->id);
2945 err = build_refs_str(&refs_str, refs, entry->id, s->repo);
2946 if (err)
2947 goto done;
2948 if (refs_str) {
2949 wchar_t *ws;
2950 err = format_line(&ws, &width, NULL, refs_str,
2951 0, INT_MAX, date_display_cols + author_cols, 0);
2952 free(ws);
2953 free(refs_str);
2954 refs_str = NULL;
2955 if (err)
2956 goto done;
2957 refstr_cols = width + 3; /* account for [ ] + space */
2958 } else
2959 refstr_cols = 0;
2960 err = got_object_commit_get_logmsg(&msg0, c);
2961 if (err)
2962 goto done;
2963 msg = msg0;
2964 while (*msg == '\n')
2965 ++msg;
2966 if ((eol = strchr(msg, '\n')))
2967 *eol = '\0';
2968 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2969 date_display_cols + author_cols + refstr_cols, 0);
2970 if (err)
2971 goto done;
2972 view->maxx = MAX(view->maxx, width + refstr_cols);
2973 free(msg0);
2974 free(wmsg);
2975 ncommits++;
2976 entry = TAILQ_NEXT(entry, entry);
2979 entry = s->first_displayed_entry;
2980 s->last_displayed_entry = s->first_displayed_entry;
2981 ncommits = 0;
2982 while (entry) {
2983 if (ncommits >= limit - 1)
2984 break;
2985 if (ncommits == s->selected)
2986 wstandout(view->window);
2987 err = draw_commit(view, entry, date_display_cols, author_cols);
2988 if (ncommits == s->selected)
2989 wstandend(view->window);
2990 if (err)
2991 goto done;
2992 ncommits++;
2993 s->last_displayed_entry = entry;
2994 entry = TAILQ_NEXT(entry, entry);
2997 view_border(view);
2998 done:
2999 free(id_str);
3000 free(refs_str);
3001 free(ncommits_str);
3002 free(header);
3003 return err;
3006 static void
3007 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
3009 struct commit_queue_entry *entry;
3010 int nscrolled = 0;
3012 entry = TAILQ_FIRST(&s->commits->head);
3013 if (s->first_displayed_entry == entry)
3014 return;
3016 entry = s->first_displayed_entry;
3017 while (entry && nscrolled < maxscroll) {
3018 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3019 if (entry) {
3020 s->first_displayed_entry = entry;
3021 nscrolled++;
3026 static const struct got_error *
3027 trigger_log_thread(struct tog_view *view, int wait)
3029 struct tog_log_thread_args *ta = &view->state.log.thread_args;
3030 int errcode;
3032 if (!using_mock_io)
3033 halfdelay(1); /* fast refresh while loading commits */
3035 while (!ta->log_complete && !tog_thread_error &&
3036 (ta->commits_needed > 0 || ta->load_all)) {
3037 /* Wake the log thread. */
3038 errcode = pthread_cond_signal(&ta->need_commits);
3039 if (errcode)
3040 return got_error_set_errno(errcode,
3041 "pthread_cond_signal");
3044 * The mutex will be released while the view loop waits
3045 * in wgetch(), at which time the log thread will run.
3047 if (!wait)
3048 break;
3050 /* Display progress update in log view. */
3051 show_log_view(view);
3052 update_panels();
3053 doupdate();
3055 /* Wait right here while next commit is being loaded. */
3056 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
3057 if (errcode)
3058 return got_error_set_errno(errcode,
3059 "pthread_cond_wait");
3061 /* Display progress update in log view. */
3062 show_log_view(view);
3063 update_panels();
3064 doupdate();
3067 return NULL;
3070 static const struct got_error *
3071 request_log_commits(struct tog_view *view)
3073 struct tog_log_view_state *state = &view->state.log;
3074 const struct got_error *err = NULL;
3076 if (state->thread_args.log_complete)
3077 return NULL;
3079 state->thread_args.commits_needed += view->nscrolled;
3080 err = trigger_log_thread(view, 1);
3081 view->nscrolled = 0;
3083 return err;
3086 static const struct got_error *
3087 log_scroll_down(struct tog_view *view, int maxscroll)
3089 struct tog_log_view_state *s = &view->state.log;
3090 const struct got_error *err = NULL;
3091 struct commit_queue_entry *pentry;
3092 int nscrolled = 0, ncommits_needed;
3094 if (s->last_displayed_entry == NULL)
3095 return NULL;
3097 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
3098 if (s->commits->ncommits < ncommits_needed &&
3099 !s->thread_args.log_complete) {
3101 * Ask the log thread for required amount of commits.
3103 s->thread_args.commits_needed +=
3104 ncommits_needed - s->commits->ncommits;
3105 err = trigger_log_thread(view, 1);
3106 if (err)
3107 return err;
3110 do {
3111 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
3112 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3113 break;
3115 s->last_displayed_entry = pentry ?
3116 pentry : s->last_displayed_entry;
3118 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3119 if (pentry == NULL)
3120 break;
3121 s->first_displayed_entry = pentry;
3122 } while (++nscrolled < maxscroll);
3124 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3125 view->nscrolled += nscrolled;
3126 else
3127 view->nscrolled = 0;
3129 return err;
3132 static const struct got_error *
3133 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3134 struct got_commit_object *commit, struct got_object_id *commit_id,
3135 struct tog_view *log_view, struct got_repository *repo)
3137 const struct got_error *err;
3138 struct got_object_qid *parent_id;
3139 struct tog_view *diff_view;
3141 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3142 if (diff_view == NULL)
3143 return got_error_from_errno("view_open");
3145 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3146 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3147 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3148 if (err == NULL)
3149 *new_view = diff_view;
3150 return err;
3153 static const struct got_error *
3154 tree_view_visit_subtree(struct tog_tree_view_state *s,
3155 struct got_tree_object *subtree)
3157 struct tog_parent_tree *parent;
3159 parent = calloc(1, sizeof(*parent));
3160 if (parent == NULL)
3161 return got_error_from_errno("calloc");
3163 parent->tree = s->tree;
3164 parent->first_displayed_entry = s->first_displayed_entry;
3165 parent->selected_entry = s->selected_entry;
3166 parent->selected = s->selected;
3167 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3168 s->tree = subtree;
3169 s->selected = 0;
3170 s->first_displayed_entry = NULL;
3171 return NULL;
3174 static const struct got_error *
3175 tree_view_walk_path(struct tog_tree_view_state *s,
3176 struct got_commit_object *commit, const char *path)
3178 const struct got_error *err = NULL;
3179 struct got_tree_object *tree = NULL;
3180 const char *p;
3181 char *slash, *subpath = NULL;
3183 /* Walk the path and open corresponding tree objects. */
3184 p = path;
3185 while (*p) {
3186 struct got_tree_entry *te;
3187 struct got_object_id *tree_id;
3188 char *te_name;
3190 while (p[0] == '/')
3191 p++;
3193 /* Ensure the correct subtree entry is selected. */
3194 slash = strchr(p, '/');
3195 if (slash == NULL)
3196 te_name = strdup(p);
3197 else
3198 te_name = strndup(p, slash - p);
3199 if (te_name == NULL) {
3200 err = got_error_from_errno("strndup");
3201 break;
3203 te = got_object_tree_find_entry(s->tree, te_name);
3204 if (te == NULL) {
3205 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3206 free(te_name);
3207 break;
3209 free(te_name);
3210 s->first_displayed_entry = s->selected_entry = te;
3212 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3213 break; /* jump to this file's entry */
3215 slash = strchr(p, '/');
3216 if (slash)
3217 subpath = strndup(path, slash - path);
3218 else
3219 subpath = strdup(path);
3220 if (subpath == NULL) {
3221 err = got_error_from_errno("strdup");
3222 break;
3225 err = got_object_id_by_path(&tree_id, s->repo, commit,
3226 subpath);
3227 if (err)
3228 break;
3230 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3231 free(tree_id);
3232 if (err)
3233 break;
3235 err = tree_view_visit_subtree(s, tree);
3236 if (err) {
3237 got_object_tree_close(tree);
3238 break;
3240 if (slash == NULL)
3241 break;
3242 free(subpath);
3243 subpath = NULL;
3244 p = slash;
3247 free(subpath);
3248 return err;
3251 static const struct got_error *
3252 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3253 struct commit_queue_entry *entry, const char *path,
3254 const char *head_ref_name, struct got_repository *repo)
3256 const struct got_error *err = NULL;
3257 struct tog_tree_view_state *s;
3258 struct tog_view *tree_view;
3260 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3261 if (tree_view == NULL)
3262 return got_error_from_errno("view_open");
3264 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3265 if (err)
3266 return err;
3267 s = &tree_view->state.tree;
3269 *new_view = tree_view;
3271 if (got_path_is_root_dir(path))
3272 return NULL;
3274 return tree_view_walk_path(s, entry->commit, path);
3277 static const struct got_error *
3278 block_signals_used_by_main_thread(void)
3280 sigset_t sigset;
3281 int errcode;
3283 if (sigemptyset(&sigset) == -1)
3284 return got_error_from_errno("sigemptyset");
3286 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3287 if (sigaddset(&sigset, SIGWINCH) == -1)
3288 return got_error_from_errno("sigaddset");
3289 if (sigaddset(&sigset, SIGCONT) == -1)
3290 return got_error_from_errno("sigaddset");
3291 if (sigaddset(&sigset, SIGINT) == -1)
3292 return got_error_from_errno("sigaddset");
3293 if (sigaddset(&sigset, SIGTERM) == -1)
3294 return got_error_from_errno("sigaddset");
3296 /* ncurses handles SIGTSTP */
3297 if (sigaddset(&sigset, SIGTSTP) == -1)
3298 return got_error_from_errno("sigaddset");
3300 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3301 if (errcode)
3302 return got_error_set_errno(errcode, "pthread_sigmask");
3304 return NULL;
3307 static void *
3308 log_thread(void *arg)
3310 const struct got_error *err = NULL;
3311 int errcode = 0;
3312 struct tog_log_thread_args *a = arg;
3313 int done = 0;
3316 * Sync startup with main thread such that we begin our
3317 * work once view_input() has released the mutex.
3319 errcode = pthread_mutex_lock(&tog_mutex);
3320 if (errcode) {
3321 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3322 return (void *)err;
3325 err = block_signals_used_by_main_thread();
3326 if (err) {
3327 pthread_mutex_unlock(&tog_mutex);
3328 goto done;
3331 while (!done && !err && !tog_fatal_signal_received()) {
3332 errcode = pthread_mutex_unlock(&tog_mutex);
3333 if (errcode) {
3334 err = got_error_set_errno(errcode,
3335 "pthread_mutex_unlock");
3336 goto done;
3338 err = queue_commits(a);
3339 if (err) {
3340 if (err->code != GOT_ERR_ITER_COMPLETED)
3341 goto done;
3342 err = NULL;
3343 done = 1;
3344 a->commits_needed = 0;
3345 } else if (a->commits_needed > 0 && !a->load_all) {
3346 if (*a->limiting) {
3347 if (a->limit_match)
3348 a->commits_needed--;
3349 } else
3350 a->commits_needed--;
3353 errcode = pthread_mutex_lock(&tog_mutex);
3354 if (errcode) {
3355 err = got_error_set_errno(errcode,
3356 "pthread_mutex_lock");
3357 goto done;
3358 } else if (*a->quit)
3359 done = 1;
3360 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3361 *a->first_displayed_entry =
3362 TAILQ_FIRST(&a->limit_commits->head);
3363 *a->selected_entry = *a->first_displayed_entry;
3364 } else if (*a->first_displayed_entry == NULL) {
3365 *a->first_displayed_entry =
3366 TAILQ_FIRST(&a->real_commits->head);
3367 *a->selected_entry = *a->first_displayed_entry;
3370 errcode = pthread_cond_signal(&a->commit_loaded);
3371 if (errcode) {
3372 err = got_error_set_errno(errcode,
3373 "pthread_cond_signal");
3374 pthread_mutex_unlock(&tog_mutex);
3375 goto done;
3378 if (a->commits_needed == 0 &&
3379 a->need_commit_marker && a->worktree) {
3380 errcode = pthread_mutex_unlock(&tog_mutex);
3381 if (errcode) {
3382 err = got_error_set_errno(errcode,
3383 "pthread_mutex_unlock");
3384 goto done;
3386 err = got_worktree_get_state(&tog_base_commit.marker,
3387 a->repo, a->worktree, NULL, NULL);
3388 if (err)
3389 goto done;
3390 errcode = pthread_mutex_lock(&tog_mutex);
3391 if (errcode) {
3392 err = got_error_set_errno(errcode,
3393 "pthread_mutex_lock");
3394 goto done;
3396 a->need_commit_marker = 0;
3398 * The main thread did not close this
3399 * work tree yet. Close it now.
3401 got_worktree_close(a->worktree);
3402 a->worktree = NULL;
3404 if (*a->quit)
3405 done = 1;
3408 if (done)
3409 a->commits_needed = 0;
3410 else {
3411 if (a->commits_needed == 0 && !a->load_all) {
3412 if (tog_io.wait_for_ui) {
3413 errcode = pthread_cond_signal(
3414 &a->log_loaded);
3415 if (errcode && err == NULL)
3416 err = got_error_set_errno(
3417 errcode,
3418 "pthread_cond_signal");
3421 errcode = pthread_cond_wait(&a->need_commits,
3422 &tog_mutex);
3423 if (errcode) {
3424 err = got_error_set_errno(errcode,
3425 "pthread_cond_wait");
3426 pthread_mutex_unlock(&tog_mutex);
3427 goto done;
3429 if (*a->quit)
3430 done = 1;
3434 a->log_complete = 1;
3435 if (tog_io.wait_for_ui) {
3436 errcode = pthread_cond_signal(&a->log_loaded);
3437 if (errcode && err == NULL)
3438 err = got_error_set_errno(errcode,
3439 "pthread_cond_signal");
3442 errcode = pthread_mutex_unlock(&tog_mutex);
3443 if (errcode)
3444 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3445 done:
3446 if (err) {
3447 tog_thread_error = 1;
3448 pthread_cond_signal(&a->commit_loaded);
3449 if (a->worktree) {
3450 got_worktree_close(a->worktree);
3451 a->worktree = NULL;
3454 return (void *)err;
3457 static const struct got_error *
3458 stop_log_thread(struct tog_log_view_state *s)
3460 const struct got_error *err = NULL, *thread_err = NULL;
3461 int errcode;
3463 if (s->thread) {
3464 s->quit = 1;
3465 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3466 if (errcode)
3467 return got_error_set_errno(errcode,
3468 "pthread_cond_signal");
3469 errcode = pthread_mutex_unlock(&tog_mutex);
3470 if (errcode)
3471 return got_error_set_errno(errcode,
3472 "pthread_mutex_unlock");
3473 errcode = pthread_join(s->thread, (void **)&thread_err);
3474 if (errcode)
3475 return got_error_set_errno(errcode, "pthread_join");
3476 errcode = pthread_mutex_lock(&tog_mutex);
3477 if (errcode)
3478 return got_error_set_errno(errcode,
3479 "pthread_mutex_lock");
3480 s->thread = 0; //NULL;
3483 if (s->thread_args.repo) {
3484 err = got_repo_close(s->thread_args.repo);
3485 s->thread_args.repo = NULL;
3488 if (s->thread_args.pack_fds) {
3489 const struct got_error *pack_err =
3490 got_repo_pack_fds_close(s->thread_args.pack_fds);
3491 if (err == NULL)
3492 err = pack_err;
3493 s->thread_args.pack_fds = NULL;
3496 if (s->thread_args.graph) {
3497 got_commit_graph_close(s->thread_args.graph);
3498 s->thread_args.graph = NULL;
3501 return err ? err : thread_err;
3504 static const struct got_error *
3505 close_log_view(struct tog_view *view)
3507 const struct got_error *err = NULL;
3508 struct tog_log_view_state *s = &view->state.log;
3509 int errcode;
3511 err = stop_log_thread(s);
3513 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3514 if (errcode && err == NULL)
3515 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3517 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3518 if (errcode && err == NULL)
3519 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3521 free_commits(&s->limit_commits);
3522 free_commits(&s->real_commits);
3523 free(s->in_repo_path);
3524 s->in_repo_path = NULL;
3525 free(s->start_id);
3526 s->start_id = NULL;
3527 free(s->head_ref_name);
3528 s->head_ref_name = NULL;
3529 return err;
3533 * We use two queues to implement the limit feature: first consists of
3534 * commits matching the current limit_regex; second is the real queue
3535 * of all known commits (real_commits). When the user starts limiting,
3536 * we swap queues such that all movement and displaying functionality
3537 * works with very slight change.
3539 static const struct got_error *
3540 limit_log_view(struct tog_view *view)
3542 struct tog_log_view_state *s = &view->state.log;
3543 struct commit_queue_entry *entry;
3544 struct tog_view *v = view;
3545 const struct got_error *err = NULL;
3546 char pattern[1024];
3547 int ret;
3549 if (view_is_hsplit_top(view))
3550 v = view->child;
3551 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3552 v = view->parent;
3554 /* Get the pattern */
3555 wmove(v->window, v->nlines - 1, 0);
3556 wclrtoeol(v->window);
3557 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3558 nodelay(v->window, FALSE);
3559 nocbreak();
3560 echo();
3561 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3562 cbreak();
3563 noecho();
3564 nodelay(v->window, TRUE);
3565 if (ret == ERR)
3566 return NULL;
3568 if (*pattern == '\0') {
3570 * Safety measure for the situation where the user
3571 * resets limit without previously limiting anything.
3573 if (!s->limit_view)
3574 return NULL;
3577 * User could have pressed Ctrl+L, which refreshed the
3578 * commit queues, it means we can't save previously
3579 * (before limit took place) displayed entries,
3580 * because they would point to already free'ed memory,
3581 * so we are forced to always select first entry of
3582 * the queue.
3584 s->commits = &s->real_commits;
3585 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3586 s->selected_entry = s->first_displayed_entry;
3587 s->selected = 0;
3588 s->limit_view = 0;
3590 return NULL;
3593 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3594 return NULL;
3596 s->limit_view = 1;
3598 /* Clear the screen while loading limit view */
3599 s->first_displayed_entry = NULL;
3600 s->last_displayed_entry = NULL;
3601 s->selected_entry = NULL;
3602 s->commits = &s->limit_commits;
3604 /* Prepare limit queue for new search */
3605 free_commits(&s->limit_commits);
3606 s->limit_commits.ncommits = 0;
3608 /* First process commits, which are in queue already */
3609 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3610 int have_match = 0;
3612 err = match_commit(&have_match, entry->id,
3613 entry->commit, &s->limit_regex);
3614 if (err)
3615 return err;
3617 if (have_match) {
3618 struct commit_queue_entry *matched;
3620 matched = alloc_commit_queue_entry(entry->commit,
3621 entry->id);
3622 if (matched == NULL) {
3623 err = got_error_from_errno(
3624 "alloc_commit_queue_entry");
3625 break;
3627 matched->commit = entry->commit;
3628 got_object_commit_retain(entry->commit);
3630 matched->idx = s->limit_commits.ncommits;
3631 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3632 matched, entry);
3633 s->limit_commits.ncommits++;
3637 /* Second process all the commits, until we fill the screen */
3638 if (s->limit_commits.ncommits < view->nlines - 1 &&
3639 !s->thread_args.log_complete) {
3640 s->thread_args.commits_needed +=
3641 view->nlines - s->limit_commits.ncommits - 1;
3642 err = trigger_log_thread(view, 1);
3643 if (err)
3644 return err;
3647 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3648 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3649 s->selected = 0;
3651 return NULL;
3654 static const struct got_error *
3655 search_start_log_view(struct tog_view *view)
3657 struct tog_log_view_state *s = &view->state.log;
3659 s->matched_entry = NULL;
3660 s->search_entry = NULL;
3661 return NULL;
3664 static const struct got_error *
3665 search_next_log_view(struct tog_view *view)
3667 const struct got_error *err = NULL;
3668 struct tog_log_view_state *s = &view->state.log;
3669 struct commit_queue_entry *entry;
3671 /* Display progress update in log view. */
3672 show_log_view(view);
3673 update_panels();
3674 doupdate();
3676 if (s->search_entry) {
3677 int errcode, ch;
3678 errcode = pthread_mutex_unlock(&tog_mutex);
3679 if (errcode)
3680 return got_error_set_errno(errcode,
3681 "pthread_mutex_unlock");
3682 ch = wgetch(view->window);
3683 errcode = pthread_mutex_lock(&tog_mutex);
3684 if (errcode)
3685 return got_error_set_errno(errcode,
3686 "pthread_mutex_lock");
3687 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3688 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3689 return NULL;
3691 if (view->searching == TOG_SEARCH_FORWARD)
3692 entry = TAILQ_NEXT(s->search_entry, entry);
3693 else
3694 entry = TAILQ_PREV(s->search_entry,
3695 commit_queue_head, entry);
3696 } else if (s->matched_entry) {
3698 * If the user has moved the cursor after we hit a match,
3699 * the position from where we should continue searching
3700 * might have changed.
3702 if (view->searching == TOG_SEARCH_FORWARD)
3703 entry = TAILQ_NEXT(s->selected_entry, entry);
3704 else
3705 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3706 entry);
3707 } else {
3708 entry = s->selected_entry;
3711 while (1) {
3712 int have_match = 0;
3714 if (entry == NULL) {
3715 if (s->thread_args.log_complete ||
3716 view->searching == TOG_SEARCH_BACKWARD) {
3717 view->search_next_done =
3718 (s->matched_entry == NULL ?
3719 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3720 s->search_entry = NULL;
3721 return NULL;
3724 * Poke the log thread for more commits and return,
3725 * allowing the main loop to make progress. Search
3726 * will resume at s->search_entry once we come back.
3728 s->search_entry = s->selected_entry;
3729 s->thread_args.commits_needed++;
3730 return trigger_log_thread(view, 0);
3733 err = match_commit(&have_match, entry->id, entry->commit,
3734 &view->regex);
3735 if (err)
3736 break;
3737 if (have_match) {
3738 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3739 s->matched_entry = entry;
3740 break;
3743 s->search_entry = entry;
3744 if (view->searching == TOG_SEARCH_FORWARD)
3745 entry = TAILQ_NEXT(entry, entry);
3746 else
3747 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3750 if (s->matched_entry) {
3751 int cur = s->selected_entry->idx;
3752 while (cur < s->matched_entry->idx) {
3753 err = input_log_view(NULL, view, KEY_DOWN);
3754 if (err)
3755 return err;
3756 cur++;
3758 while (cur > s->matched_entry->idx) {
3759 err = input_log_view(NULL, view, KEY_UP);
3760 if (err)
3761 return err;
3762 cur--;
3766 s->search_entry = NULL;
3768 return NULL;
3771 static const struct got_error *
3772 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3773 struct got_repository *repo, const char *head_ref_name,
3774 const char *in_repo_path, int log_branches,
3775 struct got_worktree *worktree)
3777 const struct got_error *err = NULL;
3778 struct tog_log_view_state *s = &view->state.log;
3779 struct got_repository *thread_repo = NULL;
3780 struct got_commit_graph *thread_graph = NULL;
3781 int errcode;
3783 if (in_repo_path != s->in_repo_path) {
3784 free(s->in_repo_path);
3785 s->in_repo_path = strdup(in_repo_path);
3786 if (s->in_repo_path == NULL) {
3787 err = got_error_from_errno("strdup");
3788 goto done;
3792 /* The commit queue only contains commits being displayed. */
3793 TAILQ_INIT(&s->real_commits.head);
3794 s->real_commits.ncommits = 0;
3795 s->commits = &s->real_commits;
3797 TAILQ_INIT(&s->limit_commits.head);
3798 s->limit_view = 0;
3799 s->limit_commits.ncommits = 0;
3801 s->repo = repo;
3802 if (head_ref_name) {
3803 s->head_ref_name = strdup(head_ref_name);
3804 if (s->head_ref_name == NULL) {
3805 err = got_error_from_errno("strdup");
3806 goto done;
3809 s->start_id = got_object_id_dup(start_id);
3810 if (s->start_id == NULL) {
3811 err = got_error_from_errno("got_object_id_dup");
3812 goto done;
3814 s->log_branches = log_branches;
3815 s->use_committer = 1;
3817 STAILQ_INIT(&s->colors);
3818 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3819 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3820 get_color_value("TOG_COLOR_COMMIT"));
3821 if (err)
3822 goto done;
3823 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3824 get_color_value("TOG_COLOR_AUTHOR"));
3825 if (err) {
3826 free_colors(&s->colors);
3827 goto done;
3829 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3830 get_color_value("TOG_COLOR_DATE"));
3831 if (err) {
3832 free_colors(&s->colors);
3833 goto done;
3837 view->show = show_log_view;
3838 view->input = input_log_view;
3839 view->resize = resize_log_view;
3840 view->close = close_log_view;
3841 view->search_start = search_start_log_view;
3842 view->search_next = search_next_log_view;
3844 if (s->thread_args.pack_fds == NULL) {
3845 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3846 if (err)
3847 goto done;
3849 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3850 s->thread_args.pack_fds);
3851 if (err)
3852 goto done;
3853 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3854 !s->log_branches);
3855 if (err)
3856 goto done;
3857 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3858 s->repo, NULL, NULL);
3859 if (err)
3860 goto done;
3862 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3863 if (errcode) {
3864 err = got_error_set_errno(errcode, "pthread_cond_init");
3865 goto done;
3867 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3868 if (errcode) {
3869 err = got_error_set_errno(errcode, "pthread_cond_init");
3870 goto done;
3873 if (using_mock_io) {
3874 int rc;
3876 rc = pthread_cond_init(&s->thread_args.log_loaded, NULL);
3877 if (rc)
3878 return got_error_set_errno(rc, "pthread_cond_init");
3881 s->thread_args.commits_needed = view->nlines;
3882 s->thread_args.graph = thread_graph;
3883 s->thread_args.real_commits = &s->real_commits;
3884 s->thread_args.limit_commits = &s->limit_commits;
3885 s->thread_args.in_repo_path = s->in_repo_path;
3886 s->thread_args.start_id = s->start_id;
3887 s->thread_args.repo = thread_repo;
3888 s->thread_args.log_complete = 0;
3889 s->thread_args.quit = &s->quit;
3890 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3891 s->thread_args.selected_entry = &s->selected_entry;
3892 s->thread_args.searching = &view->searching;
3893 s->thread_args.search_next_done = &view->search_next_done;
3894 s->thread_args.regex = &view->regex;
3895 s->thread_args.limiting = &s->limit_view;
3896 s->thread_args.limit_regex = &s->limit_regex;
3897 s->thread_args.limit_commits = &s->limit_commits;
3898 s->thread_args.worktree = worktree;
3899 if (worktree)
3900 s->thread_args.need_commit_marker = 1;
3901 done:
3902 if (err) {
3903 if (view->close == NULL)
3904 close_log_view(view);
3905 view_close(view);
3907 return err;
3910 static const struct got_error *
3911 show_log_view(struct tog_view *view)
3913 const struct got_error *err;
3914 struct tog_log_view_state *s = &view->state.log;
3916 if (s->thread == 0) { //NULL) {
3917 int errcode = pthread_create(&s->thread, NULL, log_thread,
3918 &s->thread_args);
3919 if (errcode)
3920 return got_error_set_errno(errcode, "pthread_create");
3921 if (s->thread_args.commits_needed > 0) {
3922 err = trigger_log_thread(view, 1);
3923 if (err)
3924 return err;
3928 return draw_commits(view);
3931 static void
3932 log_move_cursor_up(struct tog_view *view, int page, int home)
3934 struct tog_log_view_state *s = &view->state.log;
3936 if (s->first_displayed_entry == NULL)
3937 return;
3938 if (s->selected_entry->idx == 0)
3939 view->count = 0;
3941 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3942 || home)
3943 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3945 if (!page && !home && s->selected > 0)
3946 --s->selected;
3947 else
3948 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3950 select_commit(s);
3951 return;
3954 static const struct got_error *
3955 log_move_cursor_down(struct tog_view *view, int page)
3957 struct tog_log_view_state *s = &view->state.log;
3958 const struct got_error *err = NULL;
3959 int eos = view->nlines - 2;
3961 if (s->first_displayed_entry == NULL)
3962 return NULL;
3964 if (s->thread_args.log_complete &&
3965 s->selected_entry->idx >= s->commits->ncommits - 1)
3966 return NULL;
3968 if (view_is_hsplit_top(view))
3969 --eos; /* border consumes the last line */
3971 if (!page) {
3972 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3973 ++s->selected;
3974 else
3975 err = log_scroll_down(view, 1);
3976 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3977 struct commit_queue_entry *entry;
3978 int n;
3980 s->selected = 0;
3981 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3982 s->last_displayed_entry = entry;
3983 for (n = 0; n <= eos; n++) {
3984 if (entry == NULL)
3985 break;
3986 s->first_displayed_entry = entry;
3987 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3989 if (n > 0)
3990 s->selected = n - 1;
3991 } else {
3992 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3993 s->thread_args.log_complete)
3994 s->selected += MIN(page,
3995 s->commits->ncommits - s->selected_entry->idx - 1);
3996 else
3997 err = log_scroll_down(view, page);
3999 if (err)
4000 return err;
4003 * We might necessarily overshoot in horizontal
4004 * splits; if so, select the last displayed commit.
4006 if (s->first_displayed_entry && s->last_displayed_entry) {
4007 s->selected = MIN(s->selected,
4008 s->last_displayed_entry->idx -
4009 s->first_displayed_entry->idx);
4012 select_commit(s);
4014 if (s->thread_args.log_complete &&
4015 s->selected_entry->idx == s->commits->ncommits - 1)
4016 view->count = 0;
4018 return NULL;
4021 static void
4022 view_get_split(struct tog_view *view, int *y, int *x)
4024 *x = 0;
4025 *y = 0;
4027 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
4028 if (view->child && view->child->resized_y)
4029 *y = view->child->resized_y;
4030 else if (view->resized_y)
4031 *y = view->resized_y;
4032 else
4033 *y = view_split_begin_y(view->lines);
4034 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
4035 if (view->child && view->child->resized_x)
4036 *x = view->child->resized_x;
4037 else if (view->resized_x)
4038 *x = view->resized_x;
4039 else
4040 *x = view_split_begin_x(view->begin_x);
4044 /* Split view horizontally at y and offset view->state->selected line. */
4045 static const struct got_error *
4046 view_init_hsplit(struct tog_view *view, int y)
4048 const struct got_error *err = NULL;
4050 view->nlines = y;
4051 view->ncols = COLS;
4052 err = view_resize(view);
4053 if (err)
4054 return err;
4056 err = offset_selection_down(view);
4058 return err;
4061 static const struct got_error *
4062 log_goto_line(struct tog_view *view, int nlines)
4064 const struct got_error *err = NULL;
4065 struct tog_log_view_state *s = &view->state.log;
4066 int g, idx = s->selected_entry->idx;
4068 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
4069 return NULL;
4071 g = view->gline;
4072 view->gline = 0;
4074 if (g >= s->first_displayed_entry->idx + 1 &&
4075 g <= s->last_displayed_entry->idx + 1 &&
4076 g - s->first_displayed_entry->idx - 1 < nlines) {
4077 s->selected = g - s->first_displayed_entry->idx - 1;
4078 select_commit(s);
4079 return NULL;
4082 if (idx + 1 < g) {
4083 err = log_move_cursor_down(view, g - idx - 1);
4084 if (!err && g > s->selected_entry->idx + 1)
4085 err = log_move_cursor_down(view,
4086 g - s->first_displayed_entry->idx - 1);
4087 if (err)
4088 return err;
4089 } else if (idx + 1 > g)
4090 log_move_cursor_up(view, idx - g + 1, 0);
4092 if (g < nlines && s->first_displayed_entry->idx == 0)
4093 s->selected = g - 1;
4095 select_commit(s);
4096 return NULL;
4100 static void
4101 horizontal_scroll_input(struct tog_view *view, int ch)
4104 switch (ch) {
4105 case KEY_LEFT:
4106 case 'h':
4107 view->x -= MIN(view->x, 2);
4108 if (view->x <= 0)
4109 view->count = 0;
4110 break;
4111 case KEY_RIGHT:
4112 case 'l':
4113 if (view->x + view->ncols / 2 < view->maxx)
4114 view->x += 2;
4115 else
4116 view->count = 0;
4117 break;
4118 case '0':
4119 view->x = 0;
4120 break;
4121 case '$':
4122 view->x = MAX(view->maxx - view->ncols / 2, 0);
4123 view->count = 0;
4124 break;
4125 default:
4126 break;
4130 static const struct got_error *
4131 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4133 const struct got_error *err = NULL;
4134 struct tog_log_view_state *s = &view->state.log;
4135 int eos, nscroll;
4137 if (s->thread_args.load_all) {
4138 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4139 s->thread_args.load_all = 0;
4140 else if (s->thread_args.log_complete) {
4141 err = log_move_cursor_down(view, s->commits->ncommits);
4142 s->thread_args.load_all = 0;
4144 if (err)
4145 return err;
4148 eos = nscroll = view->nlines - 1;
4149 if (view_is_hsplit_top(view))
4150 --eos; /* border */
4152 if (view->gline)
4153 return log_goto_line(view, eos);
4155 switch (ch) {
4156 case '&':
4157 err = limit_log_view(view);
4158 break;
4159 case 'q':
4160 s->quit = 1;
4161 break;
4162 case '0':
4163 case '$':
4164 case KEY_RIGHT:
4165 case 'l':
4166 case KEY_LEFT:
4167 case 'h':
4168 horizontal_scroll_input(view, ch);
4169 break;
4170 case 'k':
4171 case KEY_UP:
4172 case '<':
4173 case ',':
4174 case CTRL('p'):
4175 log_move_cursor_up(view, 0, 0);
4176 break;
4177 case 'g':
4178 case '=':
4179 case KEY_HOME:
4180 log_move_cursor_up(view, 0, 1);
4181 view->count = 0;
4182 break;
4183 case CTRL('u'):
4184 case 'u':
4185 nscroll /= 2;
4186 /* FALL THROUGH */
4187 case KEY_PPAGE:
4188 case CTRL('b'):
4189 case 'b':
4190 log_move_cursor_up(view, nscroll, 0);
4191 break;
4192 case 'j':
4193 case KEY_DOWN:
4194 case '>':
4195 case '.':
4196 case CTRL('n'):
4197 err = log_move_cursor_down(view, 0);
4198 break;
4199 case '@':
4200 s->use_committer = !s->use_committer;
4201 view->action = s->use_committer ?
4202 "show committer" : "show commit author";
4203 break;
4204 case 'G':
4205 case '*':
4206 case KEY_END: {
4207 /* We don't know yet how many commits, so we're forced to
4208 * traverse them all. */
4209 view->count = 0;
4210 s->thread_args.load_all = 1;
4211 if (!s->thread_args.log_complete)
4212 return trigger_log_thread(view, 0);
4213 err = log_move_cursor_down(view, s->commits->ncommits);
4214 s->thread_args.load_all = 0;
4215 break;
4217 case CTRL('d'):
4218 case 'd':
4219 nscroll /= 2;
4220 /* FALL THROUGH */
4221 case KEY_NPAGE:
4222 case CTRL('f'):
4223 case 'f':
4224 case ' ':
4225 err = log_move_cursor_down(view, nscroll);
4226 break;
4227 case KEY_RESIZE:
4228 if (s->selected > view->nlines - 2)
4229 s->selected = view->nlines - 2;
4230 if (s->selected > s->commits->ncommits - 1)
4231 s->selected = s->commits->ncommits - 1;
4232 select_commit(s);
4233 if (s->commits->ncommits < view->nlines - 1 &&
4234 !s->thread_args.log_complete) {
4235 s->thread_args.commits_needed += (view->nlines - 1) -
4236 s->commits->ncommits;
4237 err = trigger_log_thread(view, 1);
4239 break;
4240 case KEY_ENTER:
4241 case '\r':
4242 view->count = 0;
4243 if (s->selected_entry == NULL)
4244 break;
4245 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4246 break;
4247 case 'T':
4248 view->count = 0;
4249 if (s->selected_entry == NULL)
4250 break;
4251 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4252 break;
4253 case KEY_BACKSPACE:
4254 case CTRL('l'):
4255 case 'B':
4256 view->count = 0;
4257 if (ch == KEY_BACKSPACE &&
4258 got_path_is_root_dir(s->in_repo_path))
4259 break;
4260 err = stop_log_thread(s);
4261 if (err)
4262 return err;
4263 if (ch == KEY_BACKSPACE) {
4264 char *parent_path;
4265 err = got_path_dirname(&parent_path, s->in_repo_path);
4266 if (err)
4267 return err;
4268 free(s->in_repo_path);
4269 s->in_repo_path = parent_path;
4270 s->thread_args.in_repo_path = s->in_repo_path;
4271 } else if (ch == CTRL('l')) {
4272 struct got_object_id *start_id;
4273 err = got_repo_match_object_id(&start_id, NULL,
4274 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4275 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4276 if (err) {
4277 if (s->head_ref_name == NULL ||
4278 err->code != GOT_ERR_NOT_REF)
4279 return err;
4280 /* Try to cope with deleted references. */
4281 free(s->head_ref_name);
4282 s->head_ref_name = NULL;
4283 err = got_repo_match_object_id(&start_id,
4284 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4285 &tog_refs, s->repo);
4286 if (err)
4287 return err;
4289 free(s->start_id);
4290 s->start_id = start_id;
4291 s->thread_args.start_id = s->start_id;
4292 } else /* 'B' */
4293 s->log_branches = !s->log_branches;
4295 if (s->thread_args.pack_fds == NULL) {
4296 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4297 if (err)
4298 return err;
4300 err = got_repo_open(&s->thread_args.repo,
4301 got_repo_get_path(s->repo), NULL,
4302 s->thread_args.pack_fds);
4303 if (err)
4304 return err;
4305 tog_free_refs();
4306 err = tog_load_refs(s->repo, 0);
4307 if (err)
4308 return err;
4309 err = got_commit_graph_open(&s->thread_args.graph,
4310 s->in_repo_path, !s->log_branches);
4311 if (err)
4312 return err;
4313 err = got_commit_graph_iter_start(s->thread_args.graph,
4314 s->start_id, s->repo, NULL, NULL);
4315 if (err)
4316 return err;
4317 free_commits(&s->real_commits);
4318 free_commits(&s->limit_commits);
4319 s->first_displayed_entry = NULL;
4320 s->last_displayed_entry = NULL;
4321 s->selected_entry = NULL;
4322 s->selected = 0;
4323 s->thread_args.log_complete = 0;
4324 s->quit = 0;
4325 s->thread_args.commits_needed = view->lines;
4326 s->matched_entry = NULL;
4327 s->search_entry = NULL;
4328 view->offset = 0;
4329 break;
4330 case 'R':
4331 view->count = 0;
4332 err = view_request_new(new_view, view, TOG_VIEW_REF);
4333 break;
4334 default:
4335 view->count = 0;
4336 break;
4339 return err;
4342 static const struct got_error *
4343 apply_unveil(const char *repo_path, const char *worktree_path)
4345 const struct got_error *error;
4347 #ifdef PROFILE
4348 if (unveil("gmon.out", "rwc") != 0)
4349 return got_error_from_errno2("unveil", "gmon.out");
4350 #endif
4351 if (repo_path && unveil(repo_path, "r") != 0)
4352 return got_error_from_errno2("unveil", repo_path);
4354 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4355 return got_error_from_errno2("unveil", worktree_path);
4357 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4358 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4360 error = got_privsep_unveil_exec_helpers();
4361 if (error != NULL)
4362 return error;
4364 if (unveil(NULL, NULL) != 0)
4365 return got_error_from_errno("unveil");
4367 return NULL;
4370 static const struct got_error *
4371 init_mock_term(const char *test_script_path)
4373 const struct got_error *err = NULL;
4374 const char *screen_dump_path;
4375 int in;
4377 if (test_script_path == NULL || *test_script_path == '\0')
4378 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4380 tog_io.f = fopen(test_script_path, "re");
4381 if (tog_io.f == NULL) {
4382 err = got_error_from_errno_fmt("fopen: %s",
4383 test_script_path);
4384 goto done;
4387 /* test mode, we don't want any output */
4388 tog_io.cout = fopen("/dev/null", "w+");
4389 if (tog_io.cout == NULL) {
4390 err = got_error_from_errno2("fopen", "/dev/null");
4391 goto done;
4394 in = dup(fileno(tog_io.cout));
4395 if (in == -1) {
4396 err = got_error_from_errno("dup");
4397 goto done;
4399 tog_io.cin = fdopen(in, "r");
4400 if (tog_io.cin == NULL) {
4401 err = got_error_from_errno("fdopen");
4402 close(in);
4403 goto done;
4406 screen_dump_path = getenv("TOG_SCR_DUMP");
4407 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4408 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4409 tog_io.sdump = fopen(screen_dump_path, "we");
4410 if (tog_io.sdump == NULL) {
4411 err = got_error_from_errno2("fopen", screen_dump_path);
4412 goto done;
4415 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4416 err = got_error_from_errno("fseeko");
4417 goto done;
4420 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4421 err = got_error_msg(GOT_ERR_IO,
4422 "newterm: failed to initialise curses");
4424 using_mock_io = 1;
4426 done:
4427 if (err)
4428 tog_io_close();
4429 return err;
4432 static void
4433 init_curses(void)
4435 if (using_mock_io) /* In test mode we use a fake terminal */
4436 return;
4438 initscr();
4440 cbreak();
4441 halfdelay(1); /* Fast refresh while initial view is loading. */
4442 noecho();
4443 nonl();
4444 intrflush(stdscr, FALSE);
4445 keypad(stdscr, TRUE);
4446 curs_set(0);
4447 if (getenv("TOG_COLORS") != NULL) {
4448 start_color();
4449 use_default_colors();
4452 return;
4455 static const struct got_error *
4456 set_tog_base_commit(struct got_repository *repo, struct got_worktree *worktree)
4458 tog_base_commit.id = got_object_id_dup(
4459 got_worktree_get_base_commit_id(worktree));
4460 if (tog_base_commit.id == NULL)
4461 return got_error_from_errno( "got_object_id_dup");
4463 return NULL;
4466 static const struct got_error *
4467 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4468 struct got_repository *repo, struct got_worktree *worktree)
4470 const struct got_error *err = NULL;
4472 if (argc == 0) {
4473 *in_repo_path = strdup("/");
4474 if (*in_repo_path == NULL)
4475 return got_error_from_errno("strdup");
4476 return NULL;
4479 if (worktree) {
4480 const char *prefix = got_worktree_get_path_prefix(worktree);
4481 char *p;
4483 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4484 if (err)
4485 return err;
4486 if (asprintf(in_repo_path, "%s%s%s", prefix,
4487 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4488 p) == -1) {
4489 err = got_error_from_errno("asprintf");
4490 *in_repo_path = NULL;
4492 free(p);
4493 } else
4494 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4496 return err;
4499 static const struct got_error *
4500 cmd_log(int argc, char *argv[])
4502 const struct got_error *error;
4503 struct got_repository *repo = NULL;
4504 struct got_worktree *worktree = NULL;
4505 struct got_object_id *start_id = NULL;
4506 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4507 char *keyword_idstr = NULL, *start_commit = NULL, *label = NULL;
4508 struct got_reference *ref = NULL;
4509 const char *head_ref_name = NULL;
4510 int ch, log_branches = 0;
4511 struct tog_view *view;
4512 int *pack_fds = NULL;
4514 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4515 switch (ch) {
4516 case 'b':
4517 log_branches = 1;
4518 break;
4519 case 'c':
4520 start_commit = optarg;
4521 break;
4522 case 'r':
4523 repo_path = realpath(optarg, NULL);
4524 if (repo_path == NULL)
4525 return got_error_from_errno2("realpath",
4526 optarg);
4527 break;
4528 default:
4529 usage_log();
4530 /* NOTREACHED */
4534 argc -= optind;
4535 argv += optind;
4537 if (argc > 1)
4538 usage_log();
4540 error = got_repo_pack_fds_open(&pack_fds);
4541 if (error != NULL)
4542 goto done;
4544 if (repo_path == NULL) {
4545 cwd = getcwd(NULL, 0);
4546 if (cwd == NULL) {
4547 error = got_error_from_errno("getcwd");
4548 goto done;
4550 error = got_worktree_open(&worktree, cwd, NULL);
4551 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4552 goto done;
4553 if (worktree)
4554 repo_path =
4555 strdup(got_worktree_get_repo_path(worktree));
4556 else
4557 repo_path = strdup(cwd);
4558 if (repo_path == NULL) {
4559 error = got_error_from_errno("strdup");
4560 goto done;
4564 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4565 if (error != NULL)
4566 goto done;
4568 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4569 repo, worktree);
4570 if (error)
4571 goto done;
4573 init_curses();
4575 error = apply_unveil(got_repo_get_path(repo),
4576 worktree ? got_worktree_get_root_path(worktree) : NULL);
4577 if (error)
4578 goto done;
4580 /* already loaded by tog_log_with_path()? */
4581 if (TAILQ_EMPTY(&tog_refs)) {
4582 error = tog_load_refs(repo, 0);
4583 if (error)
4584 goto done;
4587 if (start_commit == NULL) {
4588 error = got_repo_match_object_id(&start_id, &label,
4589 worktree ? got_worktree_get_head_ref_name(worktree) :
4590 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4591 if (error)
4592 goto done;
4593 head_ref_name = label;
4594 } else {
4595 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4596 repo, worktree);
4597 if (error != NULL)
4598 goto done;
4599 if (keyword_idstr != NULL)
4600 start_commit = keyword_idstr;
4602 error = got_ref_open(&ref, repo, start_commit, 0);
4603 if (error == NULL)
4604 head_ref_name = got_ref_get_name(ref);
4605 else if (error->code != GOT_ERR_NOT_REF)
4606 goto done;
4607 error = got_repo_match_object_id(&start_id, NULL,
4608 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4609 if (error)
4610 goto done;
4613 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4614 if (view == NULL) {
4615 error = got_error_from_errno("view_open");
4616 goto done;
4619 if (worktree) {
4620 error = set_tog_base_commit(repo, worktree);
4621 if (error != NULL)
4622 goto done;
4625 error = open_log_view(view, start_id, repo, head_ref_name,
4626 in_repo_path, log_branches, worktree);
4627 if (error)
4628 goto done;
4630 if (worktree) {
4631 /* The work tree will be closed by the log thread. */
4632 worktree = NULL;
4635 error = view_loop(view);
4637 done:
4638 free(tog_base_commit.id);
4639 free(keyword_idstr);
4640 free(in_repo_path);
4641 free(repo_path);
4642 free(cwd);
4643 free(start_id);
4644 free(label);
4645 if (ref)
4646 got_ref_close(ref);
4647 if (repo) {
4648 const struct got_error *close_err = got_repo_close(repo);
4649 if (error == NULL)
4650 error = close_err;
4652 if (worktree)
4653 got_worktree_close(worktree);
4654 if (pack_fds) {
4655 const struct got_error *pack_err =
4656 got_repo_pack_fds_close(pack_fds);
4657 if (error == NULL)
4658 error = pack_err;
4660 tog_free_refs();
4661 return error;
4664 __dead static void
4665 usage_diff(void)
4667 endwin();
4668 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4669 "object1 object2\n", getprogname());
4670 exit(1);
4673 static int
4674 match_line(const char *line, regex_t *regex, size_t nmatch,
4675 regmatch_t *regmatch)
4677 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4680 static struct tog_color *
4681 match_color(struct tog_colors *colors, const char *line)
4683 struct tog_color *tc = NULL;
4685 STAILQ_FOREACH(tc, colors, entry) {
4686 if (match_line(line, &tc->regex, 0, NULL))
4687 return tc;
4690 return NULL;
4693 static const struct got_error *
4694 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4695 WINDOW *window, int skipcol, regmatch_t *regmatch)
4697 const struct got_error *err = NULL;
4698 char *exstr = NULL;
4699 wchar_t *wline = NULL;
4700 int rme, rms, n, width, scrollx;
4701 int width0 = 0, width1 = 0, width2 = 0;
4702 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4704 *wtotal = 0;
4706 rms = regmatch->rm_so;
4707 rme = regmatch->rm_eo;
4709 err = expand_tab(&exstr, line);
4710 if (err)
4711 return err;
4713 /* Split the line into 3 segments, according to match offsets. */
4714 seg0 = strndup(exstr, rms);
4715 if (seg0 == NULL) {
4716 err = got_error_from_errno("strndup");
4717 goto done;
4719 seg1 = strndup(exstr + rms, rme - rms);
4720 if (seg1 == NULL) {
4721 err = got_error_from_errno("strndup");
4722 goto done;
4724 seg2 = strdup(exstr + rme);
4725 if (seg2 == NULL) {
4726 err = got_error_from_errno("strndup");
4727 goto done;
4730 /* draw up to matched token if we haven't scrolled past it */
4731 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4732 col_tab_align, 1);
4733 if (err)
4734 goto done;
4735 n = MAX(width0 - skipcol, 0);
4736 if (n) {
4737 free(wline);
4738 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4739 wlimit, col_tab_align, 1);
4740 if (err)
4741 goto done;
4742 waddwstr(window, &wline[scrollx]);
4743 wlimit -= width;
4744 *wtotal += width;
4747 if (wlimit > 0) {
4748 int i = 0, w = 0;
4749 size_t wlen;
4751 free(wline);
4752 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4753 col_tab_align, 1);
4754 if (err)
4755 goto done;
4756 wlen = wcslen(wline);
4757 while (i < wlen) {
4758 width = wcwidth(wline[i]);
4759 if (width == -1) {
4760 /* should not happen, tabs are expanded */
4761 err = got_error(GOT_ERR_RANGE);
4762 goto done;
4764 if (width0 + w + width > skipcol)
4765 break;
4766 w += width;
4767 i++;
4769 /* draw (visible part of) matched token (if scrolled into it) */
4770 if (width1 - w > 0) {
4771 wattron(window, A_STANDOUT);
4772 waddwstr(window, &wline[i]);
4773 wattroff(window, A_STANDOUT);
4774 wlimit -= (width1 - w);
4775 *wtotal += (width1 - w);
4779 if (wlimit > 0) { /* draw rest of line */
4780 free(wline);
4781 if (skipcol > width0 + width1) {
4782 err = format_line(&wline, &width2, &scrollx, seg2,
4783 skipcol - (width0 + width1), wlimit,
4784 col_tab_align, 1);
4785 if (err)
4786 goto done;
4787 waddwstr(window, &wline[scrollx]);
4788 } else {
4789 err = format_line(&wline, &width2, NULL, seg2, 0,
4790 wlimit, col_tab_align, 1);
4791 if (err)
4792 goto done;
4793 waddwstr(window, wline);
4795 *wtotal += width2;
4797 done:
4798 free(wline);
4799 free(exstr);
4800 free(seg0);
4801 free(seg1);
4802 free(seg2);
4803 return err;
4806 static int
4807 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4809 FILE *f = NULL;
4810 int *eof, *first, *selected;
4812 if (view->type == TOG_VIEW_DIFF) {
4813 struct tog_diff_view_state *s = &view->state.diff;
4815 first = &s->first_displayed_line;
4816 selected = first;
4817 eof = &s->eof;
4818 f = s->f;
4819 } else if (view->type == TOG_VIEW_HELP) {
4820 struct tog_help_view_state *s = &view->state.help;
4822 first = &s->first_displayed_line;
4823 selected = first;
4824 eof = &s->eof;
4825 f = s->f;
4826 } else if (view->type == TOG_VIEW_BLAME) {
4827 struct tog_blame_view_state *s = &view->state.blame;
4829 first = &s->first_displayed_line;
4830 selected = &s->selected_line;
4831 eof = &s->eof;
4832 f = s->blame.f;
4833 } else
4834 return 0;
4836 /* Center gline in the middle of the page like vi(1). */
4837 if (*lineno < view->gline - (view->nlines - 3) / 2)
4838 return 0;
4839 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4840 rewind(f);
4841 *eof = 0;
4842 *first = 1;
4843 *lineno = 0;
4844 *nprinted = 0;
4845 return 0;
4848 *selected = view->gline <= (view->nlines - 3) / 2 ?
4849 view->gline : (view->nlines - 3) / 2 + 1;
4850 view->gline = 0;
4852 return 1;
4855 static const struct got_error *
4856 draw_file(struct tog_view *view, const char *header)
4858 struct tog_diff_view_state *s = &view->state.diff;
4859 regmatch_t *regmatch = &view->regmatch;
4860 const struct got_error *err;
4861 int nprinted = 0;
4862 char *line;
4863 size_t linesize = 0;
4864 ssize_t linelen;
4865 wchar_t *wline;
4866 int width;
4867 int max_lines = view->nlines;
4868 int nlines = s->nlines;
4869 off_t line_offset;
4871 s->lineno = s->first_displayed_line - 1;
4872 line_offset = s->lines[s->first_displayed_line - 1].offset;
4873 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4874 return got_error_from_errno("fseek");
4876 werase(view->window);
4878 if (view->gline > s->nlines - 1)
4879 view->gline = s->nlines - 1;
4881 if (header) {
4882 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4883 1 : view->gline - (view->nlines - 3) / 2 :
4884 s->lineno + s->selected_line;
4886 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4887 return got_error_from_errno("asprintf");
4888 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4889 0, 0);
4890 free(line);
4891 if (err)
4892 return err;
4894 if (view_needs_focus_indication(view))
4895 wstandout(view->window);
4896 waddwstr(view->window, wline);
4897 free(wline);
4898 wline = NULL;
4899 while (width++ < view->ncols)
4900 waddch(view->window, ' ');
4901 if (view_needs_focus_indication(view))
4902 wstandend(view->window);
4904 if (max_lines <= 1)
4905 return NULL;
4906 max_lines--;
4909 s->eof = 0;
4910 view->maxx = 0;
4911 line = NULL;
4912 while (max_lines > 0 && nprinted < max_lines) {
4913 enum got_diff_line_type linetype;
4914 attr_t attr = 0;
4916 linelen = getline(&line, &linesize, s->f);
4917 if (linelen == -1) {
4918 if (feof(s->f)) {
4919 s->eof = 1;
4920 break;
4922 free(line);
4923 return got_ferror(s->f, GOT_ERR_IO);
4926 if (++s->lineno < s->first_displayed_line)
4927 continue;
4928 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4929 continue;
4930 if (s->lineno == view->hiline)
4931 attr = A_STANDOUT;
4933 /* Set view->maxx based on full line length. */
4934 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4935 view->x ? 1 : 0);
4936 if (err) {
4937 free(line);
4938 return err;
4940 view->maxx = MAX(view->maxx, width);
4941 free(wline);
4942 wline = NULL;
4944 linetype = s->lines[s->lineno].type;
4945 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4946 linetype < GOT_DIFF_LINE_CONTEXT)
4947 attr |= COLOR_PAIR(linetype);
4948 if (attr)
4949 wattron(view->window, attr);
4950 if (s->first_displayed_line + nprinted == s->matched_line &&
4951 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4952 err = add_matched_line(&width, line, view->ncols, 0,
4953 view->window, view->x, regmatch);
4954 if (err) {
4955 free(line);
4956 return err;
4958 } else {
4959 int skip;
4960 err = format_line(&wline, &width, &skip, line,
4961 view->x, view->ncols, 0, view->x ? 1 : 0);
4962 if (err) {
4963 free(line);
4964 return err;
4966 waddwstr(view->window, &wline[skip]);
4967 free(wline);
4968 wline = NULL;
4970 if (s->lineno == view->hiline) {
4971 /* highlight full gline length */
4972 while (width++ < view->ncols)
4973 waddch(view->window, ' ');
4974 } else {
4975 if (width <= view->ncols - 1)
4976 waddch(view->window, '\n');
4978 if (attr)
4979 wattroff(view->window, attr);
4980 if (++nprinted == 1)
4981 s->first_displayed_line = s->lineno;
4983 free(line);
4984 if (nprinted >= 1)
4985 s->last_displayed_line = s->first_displayed_line +
4986 (nprinted - 1);
4987 else
4988 s->last_displayed_line = s->first_displayed_line;
4990 view_border(view);
4992 if (s->eof) {
4993 while (nprinted < view->nlines) {
4994 waddch(view->window, '\n');
4995 nprinted++;
4998 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4999 view->ncols, 0, 0);
5000 if (err) {
5001 return err;
5004 wstandout(view->window);
5005 waddwstr(view->window, wline);
5006 free(wline);
5007 wline = NULL;
5008 wstandend(view->window);
5011 return NULL;
5014 static char *
5015 get_datestr(time_t *time, char *datebuf)
5017 struct tm mytm, *tm;
5018 char *p, *s;
5020 tm = gmtime_r(time, &mytm);
5021 if (tm == NULL)
5022 return NULL;
5023 s = asctime_r(tm, datebuf);
5024 if (s == NULL)
5025 return NULL;
5026 p = strchr(s, '\n');
5027 if (p)
5028 *p = '\0';
5029 return s;
5032 static const struct got_error *
5033 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
5034 off_t off, uint8_t type)
5036 struct got_diff_line *p;
5038 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
5039 if (p == NULL)
5040 return got_error_from_errno("reallocarray");
5041 *lines = p;
5042 (*lines)[*nlines].offset = off;
5043 (*lines)[*nlines].type = type;
5044 (*nlines)++;
5046 return NULL;
5049 static const struct got_error *
5050 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
5051 struct got_diff_line *s_lines, size_t s_nlines)
5053 struct got_diff_line *p;
5054 char buf[BUFSIZ];
5055 size_t i, r;
5057 if (fseeko(src, 0L, SEEK_SET) == -1)
5058 return got_error_from_errno("fseeko");
5060 for (;;) {
5061 r = fread(buf, 1, sizeof(buf), src);
5062 if (r == 0) {
5063 if (ferror(src))
5064 return got_error_from_errno("fread");
5065 if (feof(src))
5066 break;
5068 if (fwrite(buf, 1, r, dst) != r)
5069 return got_ferror(dst, GOT_ERR_IO);
5072 if (s_nlines == 0 && *d_nlines == 0)
5073 return NULL;
5076 * If commit info was in dst, increment line offsets
5077 * of the appended diff content, but skip s_lines[0]
5078 * because offset zero is already in *d_lines.
5080 if (*d_nlines > 0) {
5081 for (i = 1; i < s_nlines; ++i)
5082 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
5084 if (s_nlines > 0) {
5085 --s_nlines;
5086 ++s_lines;
5090 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
5091 if (p == NULL) {
5092 /* d_lines is freed in close_diff_view() */
5093 return got_error_from_errno("reallocarray");
5096 *d_lines = p;
5098 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
5099 *d_nlines += s_nlines;
5101 return NULL;
5104 static const struct got_error *
5105 write_commit_info(struct got_diff_line **lines, size_t *nlines,
5106 struct got_object_id *commit_id, struct got_reflist_head *refs,
5107 struct got_repository *repo, int ignore_ws, int force_text_diff,
5108 struct got_diffstat_cb_arg *dsa, FILE *outfile)
5110 const struct got_error *err = NULL;
5111 char datebuf[26], *datestr;
5112 struct got_commit_object *commit;
5113 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
5114 time_t committer_time;
5115 const char *author, *committer;
5116 char *refs_str = NULL;
5117 struct got_pathlist_entry *pe;
5118 off_t outoff = 0;
5119 int n;
5121 err = build_refs_str(&refs_str, refs, commit_id, repo);
5122 if (err)
5123 return err;
5125 err = got_object_open_as_commit(&commit, repo, commit_id);
5126 if (err)
5127 return err;
5129 err = got_object_id_str(&id_str, commit_id);
5130 if (err) {
5131 err = got_error_from_errno("got_object_id_str");
5132 goto done;
5135 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
5136 if (err)
5137 goto done;
5139 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
5140 refs_str ? refs_str : "", refs_str ? ")" : "");
5141 if (n < 0) {
5142 err = got_error_from_errno("fprintf");
5143 goto done;
5145 outoff += n;
5146 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
5147 if (err)
5148 goto done;
5150 n = fprintf(outfile, "from: %s\n",
5151 got_object_commit_get_author(commit));
5152 if (n < 0) {
5153 err = got_error_from_errno("fprintf");
5154 goto done;
5156 outoff += n;
5157 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5158 if (err)
5159 goto done;
5161 author = got_object_commit_get_author(commit);
5162 committer = got_object_commit_get_committer(commit);
5163 if (strcmp(author, committer) != 0) {
5164 n = fprintf(outfile, "via: %s\n", committer);
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,
5171 GOT_DIFF_LINE_AUTHOR);
5172 if (err)
5173 goto done;
5175 committer_time = got_object_commit_get_committer_time(commit);
5176 datestr = get_datestr(&committer_time, datebuf);
5177 if (datestr) {
5178 n = fprintf(outfile, "date: %s UTC\n", datestr);
5179 if (n < 0) {
5180 err = got_error_from_errno("fprintf");
5181 goto done;
5183 outoff += n;
5184 err = add_line_metadata(lines, nlines, outoff,
5185 GOT_DIFF_LINE_DATE);
5186 if (err)
5187 goto done;
5189 if (got_object_commit_get_nparents(commit) > 1) {
5190 const struct got_object_id_queue *parent_ids;
5191 struct got_object_qid *qid;
5192 int pn = 1;
5193 parent_ids = got_object_commit_get_parent_ids(commit);
5194 STAILQ_FOREACH(qid, parent_ids, entry) {
5195 err = got_object_id_str(&id_str, &qid->id);
5196 if (err)
5197 goto done;
5198 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5199 if (n < 0) {
5200 err = got_error_from_errno("fprintf");
5201 goto done;
5203 outoff += n;
5204 err = add_line_metadata(lines, nlines, outoff,
5205 GOT_DIFF_LINE_META);
5206 if (err)
5207 goto done;
5208 free(id_str);
5209 id_str = NULL;
5213 err = got_object_commit_get_logmsg(&logmsg, commit);
5214 if (err)
5215 goto done;
5216 s = logmsg;
5217 while ((line = strsep(&s, "\n")) != NULL) {
5218 n = fprintf(outfile, "%s\n", line);
5219 if (n < 0) {
5220 err = got_error_from_errno("fprintf");
5221 goto done;
5223 outoff += n;
5224 err = add_line_metadata(lines, nlines, outoff,
5225 GOT_DIFF_LINE_LOGMSG);
5226 if (err)
5227 goto done;
5230 TAILQ_FOREACH(pe, dsa->paths, entry) {
5231 struct got_diff_changed_path *cp = pe->data;
5232 int pad = dsa->max_path_len - pe->path_len + 1;
5234 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5235 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5236 dsa->rm_cols + 1, cp->rm);
5237 if (n < 0) {
5238 err = got_error_from_errno("fprintf");
5239 goto done;
5241 outoff += n;
5242 err = add_line_metadata(lines, nlines, outoff,
5243 GOT_DIFF_LINE_CHANGES);
5244 if (err)
5245 goto done;
5248 fputc('\n', outfile);
5249 outoff++;
5250 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5251 if (err)
5252 goto done;
5254 n = fprintf(outfile,
5255 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5256 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5257 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5258 if (n < 0) {
5259 err = got_error_from_errno("fprintf");
5260 goto done;
5262 outoff += n;
5263 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5264 if (err)
5265 goto done;
5267 fputc('\n', outfile);
5268 outoff++;
5269 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5270 done:
5271 free(id_str);
5272 free(logmsg);
5273 free(refs_str);
5274 got_object_commit_close(commit);
5275 if (err) {
5276 free(*lines);
5277 *lines = NULL;
5278 *nlines = 0;
5280 return err;
5283 static const struct got_error *
5284 create_diff(struct tog_diff_view_state *s)
5286 const struct got_error *err = NULL;
5287 FILE *f = NULL, *tmp_diff_file = NULL;
5288 int obj_type;
5289 struct got_diff_line *lines = NULL;
5290 struct got_pathlist_head changed_paths;
5292 TAILQ_INIT(&changed_paths);
5294 free(s->lines);
5295 s->lines = malloc(sizeof(*s->lines));
5296 if (s->lines == NULL)
5297 return got_error_from_errno("malloc");
5298 s->nlines = 0;
5300 f = got_opentemp();
5301 if (f == NULL) {
5302 err = got_error_from_errno("got_opentemp");
5303 goto done;
5305 tmp_diff_file = got_opentemp();
5306 if (tmp_diff_file == NULL) {
5307 err = got_error_from_errno("got_opentemp");
5308 goto done;
5310 if (s->f && fclose(s->f) == EOF) {
5311 err = got_error_from_errno("fclose");
5312 goto done;
5314 s->f = f;
5316 if (s->id1)
5317 err = got_object_get_type(&obj_type, s->repo, s->id1);
5318 else
5319 err = got_object_get_type(&obj_type, s->repo, s->id2);
5320 if (err)
5321 goto done;
5323 switch (obj_type) {
5324 case GOT_OBJ_TYPE_BLOB:
5325 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5326 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5327 s->label1, s->label2, tog_diff_algo, s->diff_context,
5328 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5329 s->f);
5330 break;
5331 case GOT_OBJ_TYPE_TREE:
5332 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5333 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5334 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5335 s->force_text_diff, NULL, s->repo, s->f);
5336 break;
5337 case GOT_OBJ_TYPE_COMMIT: {
5338 const struct got_object_id_queue *parent_ids;
5339 struct got_object_qid *pid;
5340 struct got_commit_object *commit2;
5341 struct got_reflist_head *refs;
5342 size_t nlines = 0;
5343 struct got_diffstat_cb_arg dsa = {
5344 0, 0, 0, 0, 0, 0,
5345 &changed_paths,
5346 s->ignore_whitespace,
5347 s->force_text_diff,
5348 tog_diff_algo
5351 lines = malloc(sizeof(*lines));
5352 if (lines == NULL) {
5353 err = got_error_from_errno("malloc");
5354 goto done;
5357 /* build diff first in tmp file then append to commit info */
5358 err = got_diff_objects_as_commits(&lines, &nlines,
5359 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5360 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5361 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5362 if (err)
5363 break;
5365 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5366 if (err)
5367 goto done;
5368 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5369 /* Show commit info if we're diffing to a parent/root commit. */
5370 if (s->id1 == NULL) {
5371 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5372 refs, s->repo, s->ignore_whitespace,
5373 s->force_text_diff, &dsa, s->f);
5374 if (err)
5375 goto done;
5376 } else {
5377 parent_ids = got_object_commit_get_parent_ids(commit2);
5378 STAILQ_FOREACH(pid, parent_ids, entry) {
5379 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5380 err = write_commit_info(&s->lines,
5381 &s->nlines, s->id2, refs, s->repo,
5382 s->ignore_whitespace,
5383 s->force_text_diff, &dsa, s->f);
5384 if (err)
5385 goto done;
5386 break;
5390 got_object_commit_close(commit2);
5392 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5393 lines, nlines);
5394 break;
5396 default:
5397 err = got_error(GOT_ERR_OBJ_TYPE);
5398 break;
5400 done:
5401 free(lines);
5402 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5403 if (s->f && fflush(s->f) != 0 && err == NULL)
5404 err = got_error_from_errno("fflush");
5405 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5406 err = got_error_from_errno("fclose");
5407 return err;
5410 static void
5411 diff_view_indicate_progress(struct tog_view *view)
5413 mvwaddstr(view->window, 0, 0, "diffing...");
5414 update_panels();
5415 doupdate();
5418 static const struct got_error *
5419 search_start_diff_view(struct tog_view *view)
5421 struct tog_diff_view_state *s = &view->state.diff;
5423 s->matched_line = 0;
5424 return NULL;
5427 static void
5428 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5429 size_t *nlines, int **first, int **last, int **match, int **selected)
5431 struct tog_diff_view_state *s = &view->state.diff;
5433 *f = s->f;
5434 *nlines = s->nlines;
5435 *line_offsets = NULL;
5436 *match = &s->matched_line;
5437 *first = &s->first_displayed_line;
5438 *last = &s->last_displayed_line;
5439 *selected = &s->selected_line;
5442 static const struct got_error *
5443 search_next_view_match(struct tog_view *view)
5445 const struct got_error *err = NULL;
5446 FILE *f;
5447 int lineno;
5448 char *line = NULL;
5449 size_t linesize = 0;
5450 ssize_t linelen;
5451 off_t *line_offsets;
5452 size_t nlines = 0;
5453 int *first, *last, *match, *selected;
5455 if (!view->search_setup)
5456 return got_error_msg(GOT_ERR_NOT_IMPL,
5457 "view search not supported");
5458 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5459 &match, &selected);
5461 if (!view->searching) {
5462 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5463 return NULL;
5466 if (*match) {
5467 if (view->searching == TOG_SEARCH_FORWARD)
5468 lineno = *first + 1;
5469 else
5470 lineno = *first - 1;
5471 } else
5472 lineno = *first - 1 + *selected;
5474 while (1) {
5475 off_t offset;
5477 if (lineno <= 0 || lineno > nlines) {
5478 if (*match == 0) {
5479 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5480 break;
5483 if (view->searching == TOG_SEARCH_FORWARD)
5484 lineno = 1;
5485 else
5486 lineno = nlines;
5489 offset = view->type == TOG_VIEW_DIFF ?
5490 view->state.diff.lines[lineno - 1].offset :
5491 line_offsets[lineno - 1];
5492 if (fseeko(f, offset, SEEK_SET) != 0) {
5493 free(line);
5494 return got_error_from_errno("fseeko");
5496 linelen = getline(&line, &linesize, f);
5497 if (linelen != -1) {
5498 char *exstr;
5499 err = expand_tab(&exstr, line);
5500 if (err)
5501 break;
5502 if (match_line(exstr, &view->regex, 1,
5503 &view->regmatch)) {
5504 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5505 *match = lineno;
5506 free(exstr);
5507 break;
5509 free(exstr);
5511 if (view->searching == TOG_SEARCH_FORWARD)
5512 lineno++;
5513 else
5514 lineno--;
5516 free(line);
5518 if (*match) {
5519 *first = *match;
5520 *selected = 1;
5523 return err;
5526 static const struct got_error *
5527 close_diff_view(struct tog_view *view)
5529 const struct got_error *err = NULL;
5530 struct tog_diff_view_state *s = &view->state.diff;
5532 free(s->id1);
5533 s->id1 = NULL;
5534 free(s->id2);
5535 s->id2 = NULL;
5536 if (s->f && fclose(s->f) == EOF)
5537 err = got_error_from_errno("fclose");
5538 s->f = NULL;
5539 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5540 err = got_error_from_errno("fclose");
5541 s->f1 = NULL;
5542 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5543 err = got_error_from_errno("fclose");
5544 s->f2 = NULL;
5545 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5546 err = got_error_from_errno("close");
5547 s->fd1 = -1;
5548 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5549 err = got_error_from_errno("close");
5550 s->fd2 = -1;
5551 free(s->lines);
5552 s->lines = NULL;
5553 s->nlines = 0;
5554 return err;
5557 static const struct got_error *
5558 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5559 struct got_object_id *id2, const char *label1, const char *label2,
5560 int diff_context, int ignore_whitespace, int force_text_diff,
5561 struct tog_view *parent_view, struct got_repository *repo)
5563 const struct got_error *err;
5564 struct tog_diff_view_state *s = &view->state.diff;
5566 memset(s, 0, sizeof(*s));
5567 s->fd1 = -1;
5568 s->fd2 = -1;
5570 if (id1 != NULL && id2 != NULL) {
5571 int type1, type2;
5573 err = got_object_get_type(&type1, repo, id1);
5574 if (err)
5575 goto done;
5576 err = got_object_get_type(&type2, repo, id2);
5577 if (err)
5578 goto done;
5580 if (type1 != type2) {
5581 err = got_error(GOT_ERR_OBJ_TYPE);
5582 goto done;
5585 s->first_displayed_line = 1;
5586 s->last_displayed_line = view->nlines;
5587 s->selected_line = 1;
5588 s->repo = repo;
5589 s->id1 = id1;
5590 s->id2 = id2;
5591 s->label1 = label1;
5592 s->label2 = label2;
5594 if (id1) {
5595 s->id1 = got_object_id_dup(id1);
5596 if (s->id1 == NULL) {
5597 err = got_error_from_errno("got_object_id_dup");
5598 goto done;
5600 } else
5601 s->id1 = NULL;
5603 s->id2 = got_object_id_dup(id2);
5604 if (s->id2 == NULL) {
5605 err = got_error_from_errno("got_object_id_dup");
5606 goto done;
5609 s->f1 = got_opentemp();
5610 if (s->f1 == NULL) {
5611 err = got_error_from_errno("got_opentemp");
5612 goto done;
5615 s->f2 = got_opentemp();
5616 if (s->f2 == NULL) {
5617 err = got_error_from_errno("got_opentemp");
5618 goto done;
5621 s->fd1 = got_opentempfd();
5622 if (s->fd1 == -1) {
5623 err = got_error_from_errno("got_opentempfd");
5624 goto done;
5627 s->fd2 = got_opentempfd();
5628 if (s->fd2 == -1) {
5629 err = got_error_from_errno("got_opentempfd");
5630 goto done;
5633 s->diff_context = diff_context;
5634 s->ignore_whitespace = ignore_whitespace;
5635 s->force_text_diff = force_text_diff;
5636 s->parent_view = parent_view;
5637 s->repo = repo;
5639 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5640 int rc;
5642 rc = init_pair(GOT_DIFF_LINE_MINUS,
5643 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5644 if (rc != ERR)
5645 rc = init_pair(GOT_DIFF_LINE_PLUS,
5646 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5647 if (rc != ERR)
5648 rc = init_pair(GOT_DIFF_LINE_HUNK,
5649 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5650 if (rc != ERR)
5651 rc = init_pair(GOT_DIFF_LINE_META,
5652 get_color_value("TOG_COLOR_DIFF_META"), -1);
5653 if (rc != ERR)
5654 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5655 get_color_value("TOG_COLOR_DIFF_META"), -1);
5656 if (rc != ERR)
5657 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5658 get_color_value("TOG_COLOR_DIFF_META"), -1);
5659 if (rc != ERR)
5660 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5661 get_color_value("TOG_COLOR_DIFF_META"), -1);
5662 if (rc != ERR)
5663 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5664 get_color_value("TOG_COLOR_AUTHOR"), -1);
5665 if (rc != ERR)
5666 rc = init_pair(GOT_DIFF_LINE_DATE,
5667 get_color_value("TOG_COLOR_DATE"), -1);
5668 if (rc == ERR) {
5669 err = got_error(GOT_ERR_RANGE);
5670 goto done;
5674 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5675 view_is_splitscreen(view))
5676 show_log_view(parent_view); /* draw border */
5677 diff_view_indicate_progress(view);
5679 err = create_diff(s);
5681 view->show = show_diff_view;
5682 view->input = input_diff_view;
5683 view->reset = reset_diff_view;
5684 view->close = close_diff_view;
5685 view->search_start = search_start_diff_view;
5686 view->search_setup = search_setup_diff_view;
5687 view->search_next = search_next_view_match;
5688 done:
5689 if (err) {
5690 if (view->close == NULL)
5691 close_diff_view(view);
5692 view_close(view);
5694 return err;
5697 static const struct got_error *
5698 show_diff_view(struct tog_view *view)
5700 const struct got_error *err;
5701 struct tog_diff_view_state *s = &view->state.diff;
5702 char *id_str1 = NULL, *id_str2, *header;
5703 const char *label1, *label2;
5705 if (s->id1) {
5706 err = got_object_id_str(&id_str1, s->id1);
5707 if (err)
5708 return err;
5709 label1 = s->label1 ? s->label1 : id_str1;
5710 } else
5711 label1 = "/dev/null";
5713 err = got_object_id_str(&id_str2, s->id2);
5714 if (err)
5715 return err;
5716 label2 = s->label2 ? s->label2 : id_str2;
5718 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5719 err = got_error_from_errno("asprintf");
5720 free(id_str1);
5721 free(id_str2);
5722 return err;
5724 free(id_str1);
5725 free(id_str2);
5727 err = draw_file(view, header);
5728 free(header);
5729 return err;
5732 static const struct got_error *
5733 set_selected_commit(struct tog_diff_view_state *s,
5734 struct commit_queue_entry *entry)
5736 const struct got_error *err;
5737 const struct got_object_id_queue *parent_ids;
5738 struct got_commit_object *selected_commit;
5739 struct got_object_qid *pid;
5741 free(s->id2);
5742 s->id2 = got_object_id_dup(entry->id);
5743 if (s->id2 == NULL)
5744 return got_error_from_errno("got_object_id_dup");
5746 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5747 if (err)
5748 return err;
5749 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5750 free(s->id1);
5751 pid = STAILQ_FIRST(parent_ids);
5752 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5753 got_object_commit_close(selected_commit);
5754 return NULL;
5757 static const struct got_error *
5758 reset_diff_view(struct tog_view *view)
5760 struct tog_diff_view_state *s = &view->state.diff;
5762 view->count = 0;
5763 wclear(view->window);
5764 s->first_displayed_line = 1;
5765 s->last_displayed_line = view->nlines;
5766 s->matched_line = 0;
5767 diff_view_indicate_progress(view);
5768 return create_diff(s);
5771 static void
5772 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5774 int start, i;
5776 i = start = s->first_displayed_line - 1;
5778 while (s->lines[i].type != type) {
5779 if (i == 0)
5780 i = s->nlines - 1;
5781 if (--i == start)
5782 return; /* do nothing, requested type not in file */
5785 s->selected_line = 1;
5786 s->first_displayed_line = i;
5789 static void
5790 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5792 int start, i;
5794 i = start = s->first_displayed_line + 1;
5796 while (s->lines[i].type != type) {
5797 if (i == s->nlines - 1)
5798 i = 0;
5799 if (++i == start)
5800 return; /* do nothing, requested type not in file */
5803 s->selected_line = 1;
5804 s->first_displayed_line = i;
5807 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5808 int, int, int);
5809 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5810 int, int);
5812 static const struct got_error *
5813 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5815 const struct got_error *err = NULL;
5816 struct tog_diff_view_state *s = &view->state.diff;
5817 struct tog_log_view_state *ls;
5818 struct commit_queue_entry *old_selected_entry;
5819 char *line = NULL;
5820 size_t linesize = 0;
5821 ssize_t linelen;
5822 int i, nscroll = view->nlines - 1, up = 0;
5824 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5826 switch (ch) {
5827 case '0':
5828 case '$':
5829 case KEY_RIGHT:
5830 case 'l':
5831 case KEY_LEFT:
5832 case 'h':
5833 horizontal_scroll_input(view, ch);
5834 break;
5835 case 'a':
5836 case 'w':
5837 if (ch == 'a') {
5838 s->force_text_diff = !s->force_text_diff;
5839 view->action = s->force_text_diff ?
5840 "force ASCII text enabled" :
5841 "force ASCII text disabled";
5843 else if (ch == 'w') {
5844 s->ignore_whitespace = !s->ignore_whitespace;
5845 view->action = s->ignore_whitespace ?
5846 "ignore whitespace enabled" :
5847 "ignore whitespace disabled";
5849 err = reset_diff_view(view);
5850 break;
5851 case 'g':
5852 case KEY_HOME:
5853 s->first_displayed_line = 1;
5854 view->count = 0;
5855 break;
5856 case 'G':
5857 case KEY_END:
5858 view->count = 0;
5859 if (s->eof)
5860 break;
5862 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5863 s->eof = 1;
5864 break;
5865 case 'k':
5866 case KEY_UP:
5867 case CTRL('p'):
5868 if (s->first_displayed_line > 1)
5869 s->first_displayed_line--;
5870 else
5871 view->count = 0;
5872 break;
5873 case CTRL('u'):
5874 case 'u':
5875 nscroll /= 2;
5876 /* FALL THROUGH */
5877 case KEY_PPAGE:
5878 case CTRL('b'):
5879 case 'b':
5880 if (s->first_displayed_line == 1) {
5881 view->count = 0;
5882 break;
5884 i = 0;
5885 while (i++ < nscroll && s->first_displayed_line > 1)
5886 s->first_displayed_line--;
5887 break;
5888 case 'j':
5889 case KEY_DOWN:
5890 case CTRL('n'):
5891 if (!s->eof)
5892 s->first_displayed_line++;
5893 else
5894 view->count = 0;
5895 break;
5896 case CTRL('d'):
5897 case 'd':
5898 nscroll /= 2;
5899 /* FALL THROUGH */
5900 case KEY_NPAGE:
5901 case CTRL('f'):
5902 case 'f':
5903 case ' ':
5904 if (s->eof) {
5905 view->count = 0;
5906 break;
5908 i = 0;
5909 while (!s->eof && i++ < nscroll) {
5910 linelen = getline(&line, &linesize, s->f);
5911 s->first_displayed_line++;
5912 if (linelen == -1) {
5913 if (feof(s->f)) {
5914 s->eof = 1;
5915 } else
5916 err = got_ferror(s->f, GOT_ERR_IO);
5917 break;
5920 free(line);
5921 break;
5922 case '(':
5923 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5924 break;
5925 case ')':
5926 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5927 break;
5928 case '{':
5929 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5930 break;
5931 case '}':
5932 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5933 break;
5934 case '[':
5935 if (s->diff_context > 0) {
5936 s->diff_context--;
5937 s->matched_line = 0;
5938 diff_view_indicate_progress(view);
5939 err = create_diff(s);
5940 if (s->first_displayed_line + view->nlines - 1 >
5941 s->nlines) {
5942 s->first_displayed_line = 1;
5943 s->last_displayed_line = view->nlines;
5945 } else
5946 view->count = 0;
5947 break;
5948 case ']':
5949 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5950 s->diff_context++;
5951 s->matched_line = 0;
5952 diff_view_indicate_progress(view);
5953 err = create_diff(s);
5954 } else
5955 view->count = 0;
5956 break;
5957 case '<':
5958 case ',':
5959 case 'K':
5960 up = 1;
5961 /* FALL THROUGH */
5962 case '>':
5963 case '.':
5964 case 'J':
5965 if (s->parent_view == NULL) {
5966 view->count = 0;
5967 break;
5969 s->parent_view->count = view->count;
5971 if (s->parent_view->type == TOG_VIEW_LOG) {
5972 ls = &s->parent_view->state.log;
5973 old_selected_entry = ls->selected_entry;
5975 err = input_log_view(NULL, s->parent_view,
5976 up ? KEY_UP : KEY_DOWN);
5977 if (err)
5978 break;
5979 view->count = s->parent_view->count;
5981 if (old_selected_entry == ls->selected_entry)
5982 break;
5984 err = set_selected_commit(s, ls->selected_entry);
5985 if (err)
5986 break;
5987 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5988 struct tog_blame_view_state *bs;
5989 struct got_object_id *id, *prev_id;
5991 bs = &s->parent_view->state.blame;
5992 prev_id = get_annotation_for_line(bs->blame.lines,
5993 bs->blame.nlines, bs->last_diffed_line);
5995 err = input_blame_view(&view, s->parent_view,
5996 up ? KEY_UP : KEY_DOWN);
5997 if (err)
5998 break;
5999 view->count = s->parent_view->count;
6001 if (prev_id == NULL)
6002 break;
6003 id = get_selected_commit_id(bs->blame.lines,
6004 bs->blame.nlines, bs->first_displayed_line,
6005 bs->selected_line);
6006 if (id == NULL)
6007 break;
6009 if (!got_object_id_cmp(prev_id, id))
6010 break;
6012 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
6013 if (err)
6014 break;
6016 s->first_displayed_line = 1;
6017 s->last_displayed_line = view->nlines;
6018 s->matched_line = 0;
6019 view->x = 0;
6021 diff_view_indicate_progress(view);
6022 err = create_diff(s);
6023 break;
6024 default:
6025 view->count = 0;
6026 break;
6029 return err;
6032 static const struct got_error *
6033 cmd_diff(int argc, char *argv[])
6035 const struct got_error *error;
6036 struct got_repository *repo = NULL;
6037 struct got_worktree *worktree = NULL;
6038 struct got_object_id *id1 = NULL, *id2 = NULL;
6039 char *repo_path = NULL, *cwd = NULL;
6040 char *id_str1 = NULL, *id_str2 = NULL;
6041 char *keyword_idstr1 = NULL, *keyword_idstr2 = NULL;
6042 char *label1 = NULL, *label2 = NULL;
6043 int diff_context = 3, ignore_whitespace = 0;
6044 int ch, force_text_diff = 0;
6045 const char *errstr;
6046 struct tog_view *view;
6047 int *pack_fds = NULL;
6049 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
6050 switch (ch) {
6051 case 'a':
6052 force_text_diff = 1;
6053 break;
6054 case 'C':
6055 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
6056 &errstr);
6057 if (errstr != NULL)
6058 errx(1, "number of context lines is %s: %s",
6059 errstr, errstr);
6060 break;
6061 case 'r':
6062 repo_path = realpath(optarg, NULL);
6063 if (repo_path == NULL)
6064 return got_error_from_errno2("realpath",
6065 optarg);
6066 got_path_strip_trailing_slashes(repo_path);
6067 break;
6068 case 'w':
6069 ignore_whitespace = 1;
6070 break;
6071 default:
6072 usage_diff();
6073 /* NOTREACHED */
6077 argc -= optind;
6078 argv += optind;
6080 if (argc == 0) {
6081 usage_diff(); /* TODO show local worktree changes */
6082 } else if (argc == 2) {
6083 id_str1 = argv[0];
6084 id_str2 = argv[1];
6085 } else
6086 usage_diff();
6088 error = got_repo_pack_fds_open(&pack_fds);
6089 if (error)
6090 goto done;
6092 if (repo_path == NULL) {
6093 cwd = getcwd(NULL, 0);
6094 if (cwd == NULL)
6095 return got_error_from_errno("getcwd");
6096 error = got_worktree_open(&worktree, cwd, NULL);
6097 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6098 goto done;
6099 if (worktree)
6100 repo_path =
6101 strdup(got_worktree_get_repo_path(worktree));
6102 else
6103 repo_path = strdup(cwd);
6104 if (repo_path == NULL) {
6105 error = got_error_from_errno("strdup");
6106 goto done;
6110 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6111 if (error)
6112 goto done;
6114 init_curses();
6116 error = apply_unveil(got_repo_get_path(repo), NULL);
6117 if (error)
6118 goto done;
6120 error = tog_load_refs(repo, 0);
6121 if (error)
6122 goto done;
6124 if (id_str1 != NULL) {
6125 error = got_keyword_to_idstr(&keyword_idstr1, id_str1,
6126 repo, worktree);
6127 if (error != NULL)
6128 goto done;
6129 if (keyword_idstr1 != NULL)
6130 id_str1 = keyword_idstr1;
6132 if (id_str2 != NULL) {
6133 error = got_keyword_to_idstr(&keyword_idstr2, id_str2,
6134 repo, worktree);
6135 if (error != NULL)
6136 goto done;
6137 if (keyword_idstr2 != NULL)
6138 id_str2 = keyword_idstr2;
6141 error = got_repo_match_object_id(&id1, &label1, id_str1,
6142 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6143 if (error)
6144 goto done;
6146 error = got_repo_match_object_id(&id2, &label2, id_str2,
6147 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6148 if (error)
6149 goto done;
6151 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
6152 if (view == NULL) {
6153 error = got_error_from_errno("view_open");
6154 goto done;
6156 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
6157 ignore_whitespace, force_text_diff, NULL, repo);
6158 if (error)
6159 goto done;
6161 if (worktree) {
6162 error = set_tog_base_commit(repo, worktree);
6163 if (error != NULL)
6164 goto done;
6167 error = view_loop(view);
6169 done:
6170 free(tog_base_commit.id);
6171 free(keyword_idstr1);
6172 free(keyword_idstr2);
6173 free(label1);
6174 free(label2);
6175 free(repo_path);
6176 free(cwd);
6177 if (repo) {
6178 const struct got_error *close_err = got_repo_close(repo);
6179 if (error == NULL)
6180 error = close_err;
6182 if (worktree)
6183 got_worktree_close(worktree);
6184 if (pack_fds) {
6185 const struct got_error *pack_err =
6186 got_repo_pack_fds_close(pack_fds);
6187 if (error == NULL)
6188 error = pack_err;
6190 tog_free_refs();
6191 return error;
6194 __dead static void
6195 usage_blame(void)
6197 endwin();
6198 fprintf(stderr,
6199 "usage: %s blame [-c commit] [-r repository-path] path\n",
6200 getprogname());
6201 exit(1);
6204 struct tog_blame_line {
6205 int annotated;
6206 struct got_object_id *id;
6209 static const struct got_error *
6210 draw_blame(struct tog_view *view)
6212 struct tog_blame_view_state *s = &view->state.blame;
6213 struct tog_blame *blame = &s->blame;
6214 regmatch_t *regmatch = &view->regmatch;
6215 const struct got_error *err;
6216 int lineno = 0, nprinted = 0;
6217 char *line = NULL;
6218 size_t linesize = 0;
6219 ssize_t linelen;
6220 wchar_t *wline;
6221 int width;
6222 struct tog_blame_line *blame_line;
6223 struct got_object_id *prev_id = NULL;
6224 char *id_str;
6225 struct tog_color *tc;
6227 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6228 if (err)
6229 return err;
6231 rewind(blame->f);
6232 werase(view->window);
6234 if (asprintf(&line, "commit %s", id_str) == -1) {
6235 err = got_error_from_errno("asprintf");
6236 free(id_str);
6237 return err;
6240 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6241 free(line);
6242 line = NULL;
6243 if (err)
6244 return err;
6245 if (view_needs_focus_indication(view))
6246 wstandout(view->window);
6247 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6248 if (tc)
6249 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6250 waddwstr(view->window, wline);
6251 while (width++ < view->ncols)
6252 waddch(view->window, ' ');
6253 if (tc)
6254 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6255 if (view_needs_focus_indication(view))
6256 wstandend(view->window);
6257 free(wline);
6258 wline = NULL;
6260 if (view->gline > blame->nlines)
6261 view->gline = blame->nlines;
6263 if (tog_io.wait_for_ui) {
6264 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6265 int rc;
6267 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6268 if (rc)
6269 return got_error_set_errno(rc, "pthread_cond_wait");
6270 tog_io.wait_for_ui = 0;
6273 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6274 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6275 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6276 free(id_str);
6277 return got_error_from_errno("asprintf");
6279 free(id_str);
6280 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6281 free(line);
6282 line = NULL;
6283 if (err)
6284 return err;
6285 waddwstr(view->window, wline);
6286 free(wline);
6287 wline = NULL;
6288 if (width < view->ncols - 1)
6289 waddch(view->window, '\n');
6291 s->eof = 0;
6292 view->maxx = 0;
6293 while (nprinted < view->nlines - 2) {
6294 linelen = getline(&line, &linesize, blame->f);
6295 if (linelen == -1) {
6296 if (feof(blame->f)) {
6297 s->eof = 1;
6298 break;
6300 free(line);
6301 return got_ferror(blame->f, GOT_ERR_IO);
6303 if (++lineno < s->first_displayed_line)
6304 continue;
6305 if (view->gline && !gotoline(view, &lineno, &nprinted))
6306 continue;
6308 /* Set view->maxx based on full line length. */
6309 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6310 if (err) {
6311 free(line);
6312 return err;
6314 free(wline);
6315 wline = NULL;
6316 view->maxx = MAX(view->maxx, width);
6318 if (nprinted == s->selected_line - 1)
6319 wstandout(view->window);
6321 if (blame->nlines > 0) {
6322 blame_line = &blame->lines[lineno - 1];
6323 if (blame_line->annotated && prev_id &&
6324 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6325 !(nprinted == s->selected_line - 1)) {
6326 waddstr(view->window, " ");
6327 } else if (blame_line->annotated) {
6328 char *id_str;
6329 err = got_object_id_str(&id_str,
6330 blame_line->id);
6331 if (err) {
6332 free(line);
6333 return err;
6335 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6336 if (tc)
6337 wattr_on(view->window,
6338 COLOR_PAIR(tc->colorpair), NULL);
6339 wprintw(view->window, "%.8s", id_str);
6340 if (tc)
6341 wattr_off(view->window,
6342 COLOR_PAIR(tc->colorpair), NULL);
6343 free(id_str);
6344 prev_id = blame_line->id;
6345 } else {
6346 waddstr(view->window, "........");
6347 prev_id = NULL;
6349 } else {
6350 waddstr(view->window, "........");
6351 prev_id = NULL;
6354 if (nprinted == s->selected_line - 1)
6355 wstandend(view->window);
6356 waddstr(view->window, " ");
6358 if (view->ncols <= 9) {
6359 width = 9;
6360 } else if (s->first_displayed_line + nprinted ==
6361 s->matched_line &&
6362 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6363 err = add_matched_line(&width, line, view->ncols - 9, 9,
6364 view->window, view->x, regmatch);
6365 if (err) {
6366 free(line);
6367 return err;
6369 width += 9;
6370 } else {
6371 int skip;
6372 err = format_line(&wline, &width, &skip, line,
6373 view->x, view->ncols - 9, 9, 1);
6374 if (err) {
6375 free(line);
6376 return err;
6378 waddwstr(view->window, &wline[skip]);
6379 width += 9;
6380 free(wline);
6381 wline = NULL;
6384 if (width <= view->ncols - 1)
6385 waddch(view->window, '\n');
6386 if (++nprinted == 1)
6387 s->first_displayed_line = lineno;
6389 free(line);
6390 s->last_displayed_line = lineno;
6392 view_border(view);
6394 return NULL;
6397 static const struct got_error *
6398 blame_cb(void *arg, int nlines, int lineno,
6399 struct got_commit_object *commit, struct got_object_id *id)
6401 const struct got_error *err = NULL;
6402 struct tog_blame_cb_args *a = arg;
6403 struct tog_blame_line *line;
6404 int errcode;
6406 if (nlines != a->nlines ||
6407 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6408 return got_error(GOT_ERR_RANGE);
6410 errcode = pthread_mutex_lock(&tog_mutex);
6411 if (errcode)
6412 return got_error_set_errno(errcode, "pthread_mutex_lock");
6414 if (*a->quit) { /* user has quit the blame view */
6415 err = got_error(GOT_ERR_ITER_COMPLETED);
6416 goto done;
6419 if (lineno == -1)
6420 goto done; /* no change in this commit */
6422 line = &a->lines[lineno - 1];
6423 if (line->annotated)
6424 goto done;
6426 line->id = got_object_id_dup(id);
6427 if (line->id == NULL) {
6428 err = got_error_from_errno("got_object_id_dup");
6429 goto done;
6431 line->annotated = 1;
6432 done:
6433 errcode = pthread_mutex_unlock(&tog_mutex);
6434 if (errcode)
6435 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6436 return err;
6439 static void *
6440 blame_thread(void *arg)
6442 const struct got_error *err, *close_err;
6443 struct tog_blame_thread_args *ta = arg;
6444 struct tog_blame_cb_args *a = ta->cb_args;
6445 int errcode, fd1 = -1, fd2 = -1;
6446 FILE *f1 = NULL, *f2 = NULL;
6448 fd1 = got_opentempfd();
6449 if (fd1 == -1)
6450 return (void *)got_error_from_errno("got_opentempfd");
6452 fd2 = got_opentempfd();
6453 if (fd2 == -1) {
6454 err = got_error_from_errno("got_opentempfd");
6455 goto done;
6458 f1 = got_opentemp();
6459 if (f1 == NULL) {
6460 err = (void *)got_error_from_errno("got_opentemp");
6461 goto done;
6463 f2 = got_opentemp();
6464 if (f2 == NULL) {
6465 err = (void *)got_error_from_errno("got_opentemp");
6466 goto done;
6469 err = block_signals_used_by_main_thread();
6470 if (err)
6471 goto done;
6473 err = got_blame(ta->path, a->commit_id, ta->repo,
6474 tog_diff_algo, blame_cb, ta->cb_args,
6475 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6476 if (err && err->code == GOT_ERR_CANCELLED)
6477 err = NULL;
6479 errcode = pthread_mutex_lock(&tog_mutex);
6480 if (errcode) {
6481 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6482 goto done;
6485 close_err = got_repo_close(ta->repo);
6486 if (err == NULL)
6487 err = close_err;
6488 ta->repo = NULL;
6489 *ta->complete = 1;
6491 if (tog_io.wait_for_ui) {
6492 errcode = pthread_cond_signal(&ta->blame_complete);
6493 if (errcode && err == NULL)
6494 err = got_error_set_errno(errcode,
6495 "pthread_cond_signal");
6498 errcode = pthread_mutex_unlock(&tog_mutex);
6499 if (errcode && err == NULL)
6500 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6502 done:
6503 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6504 err = got_error_from_errno("close");
6505 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6506 err = got_error_from_errno("close");
6507 if (f1 && fclose(f1) == EOF && err == NULL)
6508 err = got_error_from_errno("fclose");
6509 if (f2 && fclose(f2) == EOF && err == NULL)
6510 err = got_error_from_errno("fclose");
6512 return (void *)err;
6515 static struct got_object_id *
6516 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6517 int first_displayed_line, int selected_line)
6519 struct tog_blame_line *line;
6521 if (nlines <= 0)
6522 return NULL;
6524 line = &lines[first_displayed_line - 1 + selected_line - 1];
6525 if (!line->annotated)
6526 return NULL;
6528 return line->id;
6531 static struct got_object_id *
6532 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6533 int lineno)
6535 struct tog_blame_line *line;
6537 if (nlines <= 0 || lineno >= nlines)
6538 return NULL;
6540 line = &lines[lineno - 1];
6541 if (!line->annotated)
6542 return NULL;
6544 return line->id;
6547 static const struct got_error *
6548 stop_blame(struct tog_blame *blame)
6550 const struct got_error *err = NULL;
6551 int i;
6553 if (blame->thread) {
6554 int errcode;
6555 errcode = pthread_mutex_unlock(&tog_mutex);
6556 if (errcode)
6557 return got_error_set_errno(errcode,
6558 "pthread_mutex_unlock");
6559 errcode = pthread_join(blame->thread, (void **)&err);
6560 if (errcode)
6561 return got_error_set_errno(errcode, "pthread_join");
6562 errcode = pthread_mutex_lock(&tog_mutex);
6563 if (errcode)
6564 return got_error_set_errno(errcode,
6565 "pthread_mutex_lock");
6566 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6567 err = NULL;
6568 blame->thread = 0; //NULL;
6570 if (blame->thread_args.repo) {
6571 const struct got_error *close_err;
6572 close_err = got_repo_close(blame->thread_args.repo);
6573 if (err == NULL)
6574 err = close_err;
6575 blame->thread_args.repo = NULL;
6577 if (blame->f) {
6578 if (fclose(blame->f) == EOF && err == NULL)
6579 err = got_error_from_errno("fclose");
6580 blame->f = NULL;
6582 if (blame->lines) {
6583 for (i = 0; i < blame->nlines; i++)
6584 free(blame->lines[i].id);
6585 free(blame->lines);
6586 blame->lines = NULL;
6588 free(blame->cb_args.commit_id);
6589 blame->cb_args.commit_id = NULL;
6590 if (blame->pack_fds) {
6591 const struct got_error *pack_err =
6592 got_repo_pack_fds_close(blame->pack_fds);
6593 if (err == NULL)
6594 err = pack_err;
6595 blame->pack_fds = NULL;
6597 return err;
6600 static const struct got_error *
6601 cancel_blame_view(void *arg)
6603 const struct got_error *err = NULL;
6604 int *done = arg;
6605 int errcode;
6607 errcode = pthread_mutex_lock(&tog_mutex);
6608 if (errcode)
6609 return got_error_set_errno(errcode,
6610 "pthread_mutex_unlock");
6612 if (*done)
6613 err = got_error(GOT_ERR_CANCELLED);
6615 errcode = pthread_mutex_unlock(&tog_mutex);
6616 if (errcode)
6617 return got_error_set_errno(errcode,
6618 "pthread_mutex_lock");
6620 return err;
6623 static const struct got_error *
6624 run_blame(struct tog_view *view)
6626 struct tog_blame_view_state *s = &view->state.blame;
6627 struct tog_blame *blame = &s->blame;
6628 const struct got_error *err = NULL;
6629 struct got_commit_object *commit = NULL;
6630 struct got_blob_object *blob = NULL;
6631 struct got_repository *thread_repo = NULL;
6632 struct got_object_id *obj_id = NULL;
6633 int obj_type, fd = -1;
6634 int *pack_fds = NULL;
6636 err = got_object_open_as_commit(&commit, s->repo,
6637 &s->blamed_commit->id);
6638 if (err)
6639 return err;
6641 fd = got_opentempfd();
6642 if (fd == -1) {
6643 err = got_error_from_errno("got_opentempfd");
6644 goto done;
6647 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6648 if (err)
6649 goto done;
6651 err = got_object_get_type(&obj_type, s->repo, obj_id);
6652 if (err)
6653 goto done;
6655 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6656 err = got_error(GOT_ERR_OBJ_TYPE);
6657 goto done;
6660 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6661 if (err)
6662 goto done;
6663 blame->f = got_opentemp();
6664 if (blame->f == NULL) {
6665 err = got_error_from_errno("got_opentemp");
6666 goto done;
6668 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6669 &blame->line_offsets, blame->f, blob);
6670 if (err)
6671 goto done;
6672 if (blame->nlines == 0) {
6673 s->blame_complete = 1;
6674 goto done;
6677 /* Don't include \n at EOF in the blame line count. */
6678 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6679 blame->nlines--;
6681 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6682 if (blame->lines == NULL) {
6683 err = got_error_from_errno("calloc");
6684 goto done;
6687 err = got_repo_pack_fds_open(&pack_fds);
6688 if (err)
6689 goto done;
6690 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6691 pack_fds);
6692 if (err)
6693 goto done;
6695 blame->pack_fds = pack_fds;
6696 blame->cb_args.view = view;
6697 blame->cb_args.lines = blame->lines;
6698 blame->cb_args.nlines = blame->nlines;
6699 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6700 if (blame->cb_args.commit_id == NULL) {
6701 err = got_error_from_errno("got_object_id_dup");
6702 goto done;
6704 blame->cb_args.quit = &s->done;
6706 blame->thread_args.path = s->path;
6707 blame->thread_args.repo = thread_repo;
6708 blame->thread_args.cb_args = &blame->cb_args;
6709 blame->thread_args.complete = &s->blame_complete;
6710 blame->thread_args.cancel_cb = cancel_blame_view;
6711 blame->thread_args.cancel_arg = &s->done;
6712 s->blame_complete = 0;
6714 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6715 s->first_displayed_line = 1;
6716 s->last_displayed_line = view->nlines;
6717 s->selected_line = 1;
6719 s->matched_line = 0;
6721 done:
6722 if (commit)
6723 got_object_commit_close(commit);
6724 if (fd != -1 && close(fd) == -1 && err == NULL)
6725 err = got_error_from_errno("close");
6726 if (blob)
6727 got_object_blob_close(blob);
6728 free(obj_id);
6729 if (err)
6730 stop_blame(blame);
6731 return err;
6734 static const struct got_error *
6735 open_blame_view(struct tog_view *view, char *path,
6736 struct got_object_id *commit_id, struct got_repository *repo)
6738 const struct got_error *err = NULL;
6739 struct tog_blame_view_state *s = &view->state.blame;
6741 STAILQ_INIT(&s->blamed_commits);
6743 s->path = strdup(path);
6744 if (s->path == NULL)
6745 return got_error_from_errno("strdup");
6747 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6748 if (err) {
6749 free(s->path);
6750 return err;
6753 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6754 s->first_displayed_line = 1;
6755 s->last_displayed_line = view->nlines;
6756 s->selected_line = 1;
6757 s->blame_complete = 0;
6758 s->repo = repo;
6759 s->commit_id = commit_id;
6760 memset(&s->blame, 0, sizeof(s->blame));
6762 STAILQ_INIT(&s->colors);
6763 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6764 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6765 get_color_value("TOG_COLOR_COMMIT"));
6766 if (err)
6767 return err;
6770 view->show = show_blame_view;
6771 view->input = input_blame_view;
6772 view->reset = reset_blame_view;
6773 view->close = close_blame_view;
6774 view->search_start = search_start_blame_view;
6775 view->search_setup = search_setup_blame_view;
6776 view->search_next = search_next_view_match;
6778 if (using_mock_io) {
6779 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6780 int rc;
6782 rc = pthread_cond_init(&bta->blame_complete, NULL);
6783 if (rc)
6784 return got_error_set_errno(rc, "pthread_cond_init");
6787 return run_blame(view);
6790 static const struct got_error *
6791 close_blame_view(struct tog_view *view)
6793 const struct got_error *err = NULL;
6794 struct tog_blame_view_state *s = &view->state.blame;
6796 if (s->blame.thread)
6797 err = stop_blame(&s->blame);
6799 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6800 struct got_object_qid *blamed_commit;
6801 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6802 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6803 got_object_qid_free(blamed_commit);
6806 if (using_mock_io) {
6807 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6808 int rc;
6810 rc = pthread_cond_destroy(&bta->blame_complete);
6811 if (rc && err == NULL)
6812 err = got_error_set_errno(rc, "pthread_cond_destroy");
6815 free(s->path);
6816 free_colors(&s->colors);
6817 return err;
6820 static const struct got_error *
6821 search_start_blame_view(struct tog_view *view)
6823 struct tog_blame_view_state *s = &view->state.blame;
6825 s->matched_line = 0;
6826 return NULL;
6829 static void
6830 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6831 size_t *nlines, int **first, int **last, int **match, int **selected)
6833 struct tog_blame_view_state *s = &view->state.blame;
6835 *f = s->blame.f;
6836 *nlines = s->blame.nlines;
6837 *line_offsets = s->blame.line_offsets;
6838 *match = &s->matched_line;
6839 *first = &s->first_displayed_line;
6840 *last = &s->last_displayed_line;
6841 *selected = &s->selected_line;
6844 static const struct got_error *
6845 show_blame_view(struct tog_view *view)
6847 const struct got_error *err = NULL;
6848 struct tog_blame_view_state *s = &view->state.blame;
6849 int errcode;
6851 if (s->blame.thread == 0 && !s->blame_complete) {
6852 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6853 &s->blame.thread_args);
6854 if (errcode)
6855 return got_error_set_errno(errcode, "pthread_create");
6857 if (!using_mock_io)
6858 halfdelay(1); /* fast refresh while annotating */
6861 if (s->blame_complete && !using_mock_io)
6862 halfdelay(10); /* disable fast refresh */
6864 err = draw_blame(view);
6866 view_border(view);
6867 return err;
6870 static const struct got_error *
6871 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6872 struct got_repository *repo, struct got_object_id *id)
6874 struct tog_view *log_view;
6875 const struct got_error *err = NULL;
6877 *new_view = NULL;
6879 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6880 if (log_view == NULL)
6881 return got_error_from_errno("view_open");
6883 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0, NULL);
6884 if (err)
6885 view_close(log_view);
6886 else
6887 *new_view = log_view;
6889 return err;
6892 static const struct got_error *
6893 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6895 const struct got_error *err = NULL, *thread_err = NULL;
6896 struct tog_view *diff_view;
6897 struct tog_blame_view_state *s = &view->state.blame;
6898 int eos, nscroll, begin_y = 0, begin_x = 0;
6900 eos = nscroll = view->nlines - 2;
6901 if (view_is_hsplit_top(view))
6902 --eos; /* border */
6904 switch (ch) {
6905 case '0':
6906 case '$':
6907 case KEY_RIGHT:
6908 case 'l':
6909 case KEY_LEFT:
6910 case 'h':
6911 horizontal_scroll_input(view, ch);
6912 break;
6913 case 'q':
6914 s->done = 1;
6915 break;
6916 case 'g':
6917 case KEY_HOME:
6918 s->selected_line = 1;
6919 s->first_displayed_line = 1;
6920 view->count = 0;
6921 break;
6922 case 'G':
6923 case KEY_END:
6924 if (s->blame.nlines < eos) {
6925 s->selected_line = s->blame.nlines;
6926 s->first_displayed_line = 1;
6927 } else {
6928 s->selected_line = eos;
6929 s->first_displayed_line = s->blame.nlines - (eos - 1);
6931 view->count = 0;
6932 break;
6933 case 'k':
6934 case KEY_UP:
6935 case CTRL('p'):
6936 if (s->selected_line > 1)
6937 s->selected_line--;
6938 else if (s->selected_line == 1 &&
6939 s->first_displayed_line > 1)
6940 s->first_displayed_line--;
6941 else
6942 view->count = 0;
6943 break;
6944 case CTRL('u'):
6945 case 'u':
6946 nscroll /= 2;
6947 /* FALL THROUGH */
6948 case KEY_PPAGE:
6949 case CTRL('b'):
6950 case 'b':
6951 if (s->first_displayed_line == 1) {
6952 if (view->count > 1)
6953 nscroll += nscroll;
6954 s->selected_line = MAX(1, s->selected_line - nscroll);
6955 view->count = 0;
6956 break;
6958 if (s->first_displayed_line > nscroll)
6959 s->first_displayed_line -= nscroll;
6960 else
6961 s->first_displayed_line = 1;
6962 break;
6963 case 'j':
6964 case KEY_DOWN:
6965 case CTRL('n'):
6966 if (s->selected_line < eos && s->first_displayed_line +
6967 s->selected_line <= s->blame.nlines)
6968 s->selected_line++;
6969 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6970 s->first_displayed_line++;
6971 else
6972 view->count = 0;
6973 break;
6974 case 'c':
6975 case 'p': {
6976 struct got_object_id *id = NULL;
6978 view->count = 0;
6979 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6980 s->first_displayed_line, s->selected_line);
6981 if (id == NULL)
6982 break;
6983 if (ch == 'p') {
6984 struct got_commit_object *commit, *pcommit;
6985 struct got_object_qid *pid;
6986 struct got_object_id *blob_id = NULL;
6987 int obj_type;
6988 err = got_object_open_as_commit(&commit,
6989 s->repo, id);
6990 if (err)
6991 break;
6992 pid = STAILQ_FIRST(
6993 got_object_commit_get_parent_ids(commit));
6994 if (pid == NULL) {
6995 got_object_commit_close(commit);
6996 break;
6998 /* Check if path history ends here. */
6999 err = got_object_open_as_commit(&pcommit,
7000 s->repo, &pid->id);
7001 if (err)
7002 break;
7003 err = got_object_id_by_path(&blob_id, s->repo,
7004 pcommit, s->path);
7005 got_object_commit_close(pcommit);
7006 if (err) {
7007 if (err->code == GOT_ERR_NO_TREE_ENTRY)
7008 err = NULL;
7009 got_object_commit_close(commit);
7010 break;
7012 err = got_object_get_type(&obj_type, s->repo,
7013 blob_id);
7014 free(blob_id);
7015 /* Can't blame non-blob type objects. */
7016 if (obj_type != GOT_OBJ_TYPE_BLOB) {
7017 got_object_commit_close(commit);
7018 break;
7020 err = got_object_qid_alloc(&s->blamed_commit,
7021 &pid->id);
7022 got_object_commit_close(commit);
7023 } else {
7024 if (got_object_id_cmp(id,
7025 &s->blamed_commit->id) == 0)
7026 break;
7027 err = got_object_qid_alloc(&s->blamed_commit,
7028 id);
7030 if (err)
7031 break;
7032 s->done = 1;
7033 thread_err = stop_blame(&s->blame);
7034 s->done = 0;
7035 if (thread_err)
7036 break;
7037 STAILQ_INSERT_HEAD(&s->blamed_commits,
7038 s->blamed_commit, entry);
7039 err = run_blame(view);
7040 if (err)
7041 break;
7042 break;
7044 case 'C': {
7045 struct got_object_qid *first;
7047 view->count = 0;
7048 first = STAILQ_FIRST(&s->blamed_commits);
7049 if (!got_object_id_cmp(&first->id, s->commit_id))
7050 break;
7051 s->done = 1;
7052 thread_err = stop_blame(&s->blame);
7053 s->done = 0;
7054 if (thread_err)
7055 break;
7056 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
7057 got_object_qid_free(s->blamed_commit);
7058 s->blamed_commit =
7059 STAILQ_FIRST(&s->blamed_commits);
7060 err = run_blame(view);
7061 if (err)
7062 break;
7063 break;
7065 case 'L':
7066 view->count = 0;
7067 s->id_to_log = get_selected_commit_id(s->blame.lines,
7068 s->blame.nlines, s->first_displayed_line, s->selected_line);
7069 if (s->id_to_log)
7070 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7071 break;
7072 case KEY_ENTER:
7073 case '\r': {
7074 struct got_object_id *id = NULL;
7075 struct got_object_qid *pid;
7076 struct got_commit_object *commit = NULL;
7078 view->count = 0;
7079 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7080 s->first_displayed_line, s->selected_line);
7081 if (id == NULL)
7082 break;
7083 err = got_object_open_as_commit(&commit, s->repo, id);
7084 if (err)
7085 break;
7086 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7087 if (*new_view) {
7088 /* traversed from diff view, release diff resources */
7089 err = close_diff_view(*new_view);
7090 if (err)
7091 break;
7092 diff_view = *new_view;
7093 } else {
7094 if (view_is_parent_view(view))
7095 view_get_split(view, &begin_y, &begin_x);
7097 diff_view = view_open(0, 0, begin_y, begin_x,
7098 TOG_VIEW_DIFF);
7099 if (diff_view == NULL) {
7100 got_object_commit_close(commit);
7101 err = got_error_from_errno("view_open");
7102 break;
7105 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
7106 id, NULL, NULL, 3, 0, 0, view, s->repo);
7107 got_object_commit_close(commit);
7108 if (err)
7109 break;
7110 s->last_diffed_line = s->first_displayed_line - 1 +
7111 s->selected_line;
7112 if (*new_view)
7113 break; /* still open from active diff view */
7114 if (view_is_parent_view(view) &&
7115 view->mode == TOG_VIEW_SPLIT_HRZN) {
7116 err = view_init_hsplit(view, begin_y);
7117 if (err)
7118 break;
7121 view->focussed = 0;
7122 diff_view->focussed = 1;
7123 diff_view->mode = view->mode;
7124 diff_view->nlines = view->lines - begin_y;
7125 if (view_is_parent_view(view)) {
7126 view_transfer_size(diff_view, view);
7127 err = view_close_child(view);
7128 if (err)
7129 break;
7130 err = view_set_child(view, diff_view);
7131 if (err)
7132 break;
7133 view->focus_child = 1;
7134 } else
7135 *new_view = diff_view;
7136 if (err)
7137 break;
7138 break;
7140 case CTRL('d'):
7141 case 'd':
7142 nscroll /= 2;
7143 /* FALL THROUGH */
7144 case KEY_NPAGE:
7145 case CTRL('f'):
7146 case 'f':
7147 case ' ':
7148 if (s->last_displayed_line >= s->blame.nlines &&
7149 s->selected_line >= MIN(s->blame.nlines,
7150 view->nlines - 2)) {
7151 view->count = 0;
7152 break;
7154 if (s->last_displayed_line >= s->blame.nlines &&
7155 s->selected_line < view->nlines - 2) {
7156 s->selected_line +=
7157 MIN(nscroll, s->last_displayed_line -
7158 s->first_displayed_line - s->selected_line + 1);
7160 if (s->last_displayed_line + nscroll <= s->blame.nlines)
7161 s->first_displayed_line += nscroll;
7162 else
7163 s->first_displayed_line =
7164 s->blame.nlines - (view->nlines - 3);
7165 break;
7166 case KEY_RESIZE:
7167 if (s->selected_line > view->nlines - 2) {
7168 s->selected_line = MIN(s->blame.nlines,
7169 view->nlines - 2);
7171 break;
7172 default:
7173 view->count = 0;
7174 break;
7176 return thread_err ? thread_err : err;
7179 static const struct got_error *
7180 reset_blame_view(struct tog_view *view)
7182 const struct got_error *err;
7183 struct tog_blame_view_state *s = &view->state.blame;
7185 view->count = 0;
7186 s->done = 1;
7187 err = stop_blame(&s->blame);
7188 s->done = 0;
7189 if (err)
7190 return err;
7191 return run_blame(view);
7194 static const struct got_error *
7195 cmd_blame(int argc, char *argv[])
7197 const struct got_error *error;
7198 struct got_repository *repo = NULL;
7199 struct got_worktree *worktree = NULL;
7200 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7201 char *link_target = NULL;
7202 struct got_object_id *commit_id = NULL;
7203 struct got_commit_object *commit = NULL;
7204 char *keyword_idstr = NULL, *commit_id_str = NULL;
7205 int ch;
7206 struct tog_view *view = NULL;
7207 int *pack_fds = NULL;
7209 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7210 switch (ch) {
7211 case 'c':
7212 commit_id_str = optarg;
7213 break;
7214 case 'r':
7215 repo_path = realpath(optarg, NULL);
7216 if (repo_path == NULL)
7217 return got_error_from_errno2("realpath",
7218 optarg);
7219 break;
7220 default:
7221 usage_blame();
7222 /* NOTREACHED */
7226 argc -= optind;
7227 argv += optind;
7229 if (argc != 1)
7230 usage_blame();
7232 error = got_repo_pack_fds_open(&pack_fds);
7233 if (error != NULL)
7234 goto done;
7236 if (repo_path == NULL) {
7237 cwd = getcwd(NULL, 0);
7238 if (cwd == NULL)
7239 return got_error_from_errno("getcwd");
7240 error = got_worktree_open(&worktree, cwd, NULL);
7241 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7242 goto done;
7243 if (worktree)
7244 repo_path =
7245 strdup(got_worktree_get_repo_path(worktree));
7246 else
7247 repo_path = strdup(cwd);
7248 if (repo_path == NULL) {
7249 error = got_error_from_errno("strdup");
7250 goto done;
7254 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7255 if (error != NULL)
7256 goto done;
7258 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7259 worktree);
7260 if (error)
7261 goto done;
7263 init_curses();
7265 error = apply_unveil(got_repo_get_path(repo), NULL);
7266 if (error)
7267 goto done;
7269 error = tog_load_refs(repo, 0);
7270 if (error)
7271 goto done;
7273 if (commit_id_str == NULL) {
7274 struct got_reference *head_ref;
7275 error = got_ref_open(&head_ref, repo, worktree ?
7276 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7277 if (error != NULL)
7278 goto done;
7279 error = got_ref_resolve(&commit_id, repo, head_ref);
7280 got_ref_close(head_ref);
7281 } else {
7282 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
7283 repo, worktree);
7284 if (error != NULL)
7285 goto done;
7286 if (keyword_idstr != NULL)
7287 commit_id_str = keyword_idstr;
7289 error = got_repo_match_object_id(&commit_id, NULL,
7290 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7292 if (error != NULL)
7293 goto done;
7295 error = got_object_open_as_commit(&commit, repo, commit_id);
7296 if (error)
7297 goto done;
7299 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7300 commit, repo);
7301 if (error)
7302 goto done;
7304 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7305 if (view == NULL) {
7306 error = got_error_from_errno("view_open");
7307 goto done;
7309 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7310 commit_id, repo);
7311 if (error != NULL) {
7312 if (view->close == NULL)
7313 close_blame_view(view);
7314 view_close(view);
7315 goto done;
7318 if (worktree) {
7319 error = set_tog_base_commit(repo, worktree);
7320 if (error != NULL)
7321 goto done;
7323 /* Release work tree lock. */
7324 got_worktree_close(worktree);
7325 worktree = NULL;
7328 error = view_loop(view);
7330 done:
7331 free(tog_base_commit.id);
7332 free(repo_path);
7333 free(in_repo_path);
7334 free(link_target);
7335 free(cwd);
7336 free(commit_id);
7337 free(keyword_idstr);
7338 if (commit)
7339 got_object_commit_close(commit);
7340 if (worktree)
7341 got_worktree_close(worktree);
7342 if (repo) {
7343 const struct got_error *close_err = got_repo_close(repo);
7344 if (error == NULL)
7345 error = close_err;
7347 if (pack_fds) {
7348 const struct got_error *pack_err =
7349 got_repo_pack_fds_close(pack_fds);
7350 if (error == NULL)
7351 error = pack_err;
7353 tog_free_refs();
7354 return error;
7357 static const struct got_error *
7358 draw_tree_entries(struct tog_view *view, const char *parent_path)
7360 struct tog_tree_view_state *s = &view->state.tree;
7361 const struct got_error *err = NULL;
7362 struct got_tree_entry *te;
7363 wchar_t *wline;
7364 char *index = NULL;
7365 struct tog_color *tc;
7366 int width, n, nentries, scrollx, i = 1;
7367 int limit = view->nlines;
7369 s->ndisplayed = 0;
7370 if (view_is_hsplit_top(view))
7371 --limit; /* border */
7373 werase(view->window);
7375 if (limit == 0)
7376 return NULL;
7378 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7379 0, 0);
7380 if (err)
7381 return err;
7382 if (view_needs_focus_indication(view))
7383 wstandout(view->window);
7384 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7385 if (tc)
7386 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7387 waddwstr(view->window, wline);
7388 free(wline);
7389 wline = NULL;
7390 while (width++ < view->ncols)
7391 waddch(view->window, ' ');
7392 if (tc)
7393 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7394 if (view_needs_focus_indication(view))
7395 wstandend(view->window);
7396 if (--limit <= 0)
7397 return NULL;
7399 i += s->selected;
7400 if (s->first_displayed_entry) {
7401 i += got_tree_entry_get_index(s->first_displayed_entry);
7402 if (s->tree != s->root)
7403 ++i; /* account for ".." entry */
7405 nentries = got_object_tree_get_nentries(s->tree);
7406 if (asprintf(&index, "[%d/%d] %s",
7407 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7408 return got_error_from_errno("asprintf");
7409 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7410 free(index);
7411 if (err)
7412 return err;
7413 waddwstr(view->window, wline);
7414 free(wline);
7415 wline = NULL;
7416 if (width < view->ncols - 1)
7417 waddch(view->window, '\n');
7418 if (--limit <= 0)
7419 return NULL;
7420 waddch(view->window, '\n');
7421 if (--limit <= 0)
7422 return NULL;
7424 if (s->first_displayed_entry == NULL) {
7425 te = got_object_tree_get_first_entry(s->tree);
7426 if (s->selected == 0) {
7427 if (view->focussed)
7428 wstandout(view->window);
7429 s->selected_entry = NULL;
7431 waddstr(view->window, " ..\n"); /* parent directory */
7432 if (s->selected == 0 && view->focussed)
7433 wstandend(view->window);
7434 s->ndisplayed++;
7435 if (--limit <= 0)
7436 return NULL;
7437 n = 1;
7438 } else {
7439 n = 0;
7440 te = s->first_displayed_entry;
7443 view->maxx = 0;
7444 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7445 char *line = NULL, *id_str = NULL, *link_target = NULL;
7446 const char *modestr = "";
7447 mode_t mode;
7449 te = got_object_tree_get_entry(s->tree, i);
7450 mode = got_tree_entry_get_mode(te);
7452 if (s->show_ids) {
7453 err = got_object_id_str(&id_str,
7454 got_tree_entry_get_id(te));
7455 if (err)
7456 return got_error_from_errno(
7457 "got_object_id_str");
7459 if (got_object_tree_entry_is_submodule(te))
7460 modestr = "$";
7461 else if (S_ISLNK(mode)) {
7462 int i;
7464 err = got_tree_entry_get_symlink_target(&link_target,
7465 te, s->repo);
7466 if (err) {
7467 free(id_str);
7468 return err;
7470 for (i = 0; link_target[i] != '\0'; i++) {
7471 if (!isprint((unsigned char)link_target[i]))
7472 link_target[i] = '?';
7474 modestr = "@";
7476 else if (S_ISDIR(mode))
7477 modestr = "/";
7478 else if (mode & S_IXUSR)
7479 modestr = "*";
7480 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7481 got_tree_entry_get_name(te), modestr,
7482 link_target ? " -> ": "",
7483 link_target ? link_target : "") == -1) {
7484 free(id_str);
7485 free(link_target);
7486 return got_error_from_errno("asprintf");
7488 free(id_str);
7489 free(link_target);
7491 /* use full line width to determine view->maxx */
7492 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7493 if (err) {
7494 free(line);
7495 break;
7497 view->maxx = MAX(view->maxx, width);
7498 free(wline);
7499 wline = NULL;
7501 err = format_line(&wline, &width, &scrollx, line, view->x,
7502 view->ncols, 0, 0);
7503 if (err) {
7504 free(line);
7505 break;
7507 if (n == s->selected) {
7508 if (view->focussed)
7509 wstandout(view->window);
7510 s->selected_entry = te;
7512 tc = match_color(&s->colors, line);
7513 if (tc)
7514 wattr_on(view->window,
7515 COLOR_PAIR(tc->colorpair), NULL);
7516 waddwstr(view->window, &wline[scrollx]);
7517 if (tc)
7518 wattr_off(view->window,
7519 COLOR_PAIR(tc->colorpair), NULL);
7520 if (width < view->ncols)
7521 waddch(view->window, '\n');
7522 if (n == s->selected && view->focussed)
7523 wstandend(view->window);
7524 free(line);
7525 free(wline);
7526 wline = NULL;
7527 n++;
7528 s->ndisplayed++;
7529 s->last_displayed_entry = te;
7530 if (--limit <= 0)
7531 break;
7534 return err;
7537 static void
7538 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7540 struct got_tree_entry *te;
7541 int isroot = s->tree == s->root;
7542 int i = 0;
7544 if (s->first_displayed_entry == NULL)
7545 return;
7547 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7548 while (i++ < maxscroll) {
7549 if (te == NULL) {
7550 if (!isroot)
7551 s->first_displayed_entry = NULL;
7552 break;
7554 s->first_displayed_entry = te;
7555 te = got_tree_entry_get_prev(s->tree, te);
7559 static const struct got_error *
7560 tree_scroll_down(struct tog_view *view, int maxscroll)
7562 struct tog_tree_view_state *s = &view->state.tree;
7563 struct got_tree_entry *next, *last;
7564 int n = 0;
7566 if (s->first_displayed_entry)
7567 next = got_tree_entry_get_next(s->tree,
7568 s->first_displayed_entry);
7569 else
7570 next = got_object_tree_get_first_entry(s->tree);
7572 last = s->last_displayed_entry;
7573 while (next && n++ < maxscroll) {
7574 if (last) {
7575 s->last_displayed_entry = last;
7576 last = got_tree_entry_get_next(s->tree, last);
7578 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7579 s->first_displayed_entry = next;
7580 next = got_tree_entry_get_next(s->tree, next);
7584 return NULL;
7587 static const struct got_error *
7588 tree_entry_path(char **path, struct tog_parent_trees *parents,
7589 struct got_tree_entry *te)
7591 const struct got_error *err = NULL;
7592 struct tog_parent_tree *pt;
7593 size_t len = 2; /* for leading slash and NUL */
7595 TAILQ_FOREACH(pt, parents, entry)
7596 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7597 + 1 /* slash */;
7598 if (te)
7599 len += strlen(got_tree_entry_get_name(te));
7601 *path = calloc(1, len);
7602 if (path == NULL)
7603 return got_error_from_errno("calloc");
7605 (*path)[0] = '/';
7606 pt = TAILQ_LAST(parents, tog_parent_trees);
7607 while (pt) {
7608 const char *name = got_tree_entry_get_name(pt->selected_entry);
7609 if (strlcat(*path, name, len) >= len) {
7610 err = got_error(GOT_ERR_NO_SPACE);
7611 goto done;
7613 if (strlcat(*path, "/", len) >= len) {
7614 err = got_error(GOT_ERR_NO_SPACE);
7615 goto done;
7617 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7619 if (te) {
7620 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7621 err = got_error(GOT_ERR_NO_SPACE);
7622 goto done;
7625 done:
7626 if (err) {
7627 free(*path);
7628 *path = NULL;
7630 return err;
7633 static const struct got_error *
7634 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7635 struct got_tree_entry *te, struct tog_parent_trees *parents,
7636 struct got_object_id *commit_id, struct got_repository *repo)
7638 const struct got_error *err = NULL;
7639 char *path;
7640 struct tog_view *blame_view;
7642 *new_view = NULL;
7644 err = tree_entry_path(&path, parents, te);
7645 if (err)
7646 return err;
7648 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7649 if (blame_view == NULL) {
7650 err = got_error_from_errno("view_open");
7651 goto done;
7654 err = open_blame_view(blame_view, path, commit_id, repo);
7655 if (err) {
7656 if (err->code == GOT_ERR_CANCELLED)
7657 err = NULL;
7658 view_close(blame_view);
7659 } else
7660 *new_view = blame_view;
7661 done:
7662 free(path);
7663 return err;
7666 static const struct got_error *
7667 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7668 struct tog_tree_view_state *s)
7670 struct tog_view *log_view;
7671 const struct got_error *err = NULL;
7672 char *path;
7674 *new_view = NULL;
7676 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7677 if (log_view == NULL)
7678 return got_error_from_errno("view_open");
7680 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7681 if (err)
7682 return err;
7684 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7685 path, 0, NULL);
7686 if (err)
7687 view_close(log_view);
7688 else
7689 *new_view = log_view;
7690 free(path);
7691 return err;
7694 static const struct got_error *
7695 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7696 const char *head_ref_name, struct got_repository *repo)
7698 const struct got_error *err = NULL;
7699 char *commit_id_str = NULL;
7700 struct tog_tree_view_state *s = &view->state.tree;
7701 struct got_commit_object *commit = NULL;
7703 TAILQ_INIT(&s->parents);
7704 STAILQ_INIT(&s->colors);
7706 s->commit_id = got_object_id_dup(commit_id);
7707 if (s->commit_id == NULL) {
7708 err = got_error_from_errno("got_object_id_dup");
7709 goto done;
7712 err = got_object_open_as_commit(&commit, repo, commit_id);
7713 if (err)
7714 goto done;
7717 * The root is opened here and will be closed when the view is closed.
7718 * Any visited subtrees and their path-wise parents are opened and
7719 * closed on demand.
7721 err = got_object_open_as_tree(&s->root, repo,
7722 got_object_commit_get_tree_id(commit));
7723 if (err)
7724 goto done;
7725 s->tree = s->root;
7727 err = got_object_id_str(&commit_id_str, commit_id);
7728 if (err != NULL)
7729 goto done;
7731 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7732 err = got_error_from_errno("asprintf");
7733 goto done;
7736 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7737 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7738 if (head_ref_name) {
7739 s->head_ref_name = strdup(head_ref_name);
7740 if (s->head_ref_name == NULL) {
7741 err = got_error_from_errno("strdup");
7742 goto done;
7745 s->repo = repo;
7747 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7748 err = add_color(&s->colors, "\\$$",
7749 TOG_COLOR_TREE_SUBMODULE,
7750 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7751 if (err)
7752 goto done;
7753 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7754 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7755 if (err)
7756 goto done;
7757 err = add_color(&s->colors, "/$",
7758 TOG_COLOR_TREE_DIRECTORY,
7759 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7760 if (err)
7761 goto done;
7763 err = add_color(&s->colors, "\\*$",
7764 TOG_COLOR_TREE_EXECUTABLE,
7765 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7766 if (err)
7767 goto done;
7769 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7770 get_color_value("TOG_COLOR_COMMIT"));
7771 if (err)
7772 goto done;
7775 view->show = show_tree_view;
7776 view->input = input_tree_view;
7777 view->close = close_tree_view;
7778 view->search_start = search_start_tree_view;
7779 view->search_next = search_next_tree_view;
7780 done:
7781 free(commit_id_str);
7782 if (commit)
7783 got_object_commit_close(commit);
7784 if (err) {
7785 if (view->close == NULL)
7786 close_tree_view(view);
7787 view_close(view);
7789 return err;
7792 static const struct got_error *
7793 close_tree_view(struct tog_view *view)
7795 struct tog_tree_view_state *s = &view->state.tree;
7797 free_colors(&s->colors);
7798 free(s->tree_label);
7799 s->tree_label = NULL;
7800 free(s->commit_id);
7801 s->commit_id = NULL;
7802 free(s->head_ref_name);
7803 s->head_ref_name = NULL;
7804 while (!TAILQ_EMPTY(&s->parents)) {
7805 struct tog_parent_tree *parent;
7806 parent = TAILQ_FIRST(&s->parents);
7807 TAILQ_REMOVE(&s->parents, parent, entry);
7808 if (parent->tree != s->root)
7809 got_object_tree_close(parent->tree);
7810 free(parent);
7813 if (s->tree != NULL && s->tree != s->root)
7814 got_object_tree_close(s->tree);
7815 if (s->root)
7816 got_object_tree_close(s->root);
7817 return NULL;
7820 static const struct got_error *
7821 search_start_tree_view(struct tog_view *view)
7823 struct tog_tree_view_state *s = &view->state.tree;
7825 s->matched_entry = NULL;
7826 return NULL;
7829 static int
7830 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7832 regmatch_t regmatch;
7834 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7835 0) == 0;
7838 static const struct got_error *
7839 search_next_tree_view(struct tog_view *view)
7841 struct tog_tree_view_state *s = &view->state.tree;
7842 struct got_tree_entry *te = NULL;
7844 if (!view->searching) {
7845 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7846 return NULL;
7849 if (s->matched_entry) {
7850 if (view->searching == TOG_SEARCH_FORWARD) {
7851 if (s->selected_entry)
7852 te = got_tree_entry_get_next(s->tree,
7853 s->selected_entry);
7854 else
7855 te = got_object_tree_get_first_entry(s->tree);
7856 } else {
7857 if (s->selected_entry == NULL)
7858 te = got_object_tree_get_last_entry(s->tree);
7859 else
7860 te = got_tree_entry_get_prev(s->tree,
7861 s->selected_entry);
7863 } else {
7864 if (s->selected_entry)
7865 te = s->selected_entry;
7866 else if (view->searching == TOG_SEARCH_FORWARD)
7867 te = got_object_tree_get_first_entry(s->tree);
7868 else
7869 te = got_object_tree_get_last_entry(s->tree);
7872 while (1) {
7873 if (te == NULL) {
7874 if (s->matched_entry == NULL) {
7875 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7876 return NULL;
7878 if (view->searching == TOG_SEARCH_FORWARD)
7879 te = got_object_tree_get_first_entry(s->tree);
7880 else
7881 te = got_object_tree_get_last_entry(s->tree);
7884 if (match_tree_entry(te, &view->regex)) {
7885 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7886 s->matched_entry = te;
7887 break;
7890 if (view->searching == TOG_SEARCH_FORWARD)
7891 te = got_tree_entry_get_next(s->tree, te);
7892 else
7893 te = got_tree_entry_get_prev(s->tree, te);
7896 if (s->matched_entry) {
7897 s->first_displayed_entry = s->matched_entry;
7898 s->selected = 0;
7901 return NULL;
7904 static const struct got_error *
7905 show_tree_view(struct tog_view *view)
7907 const struct got_error *err = NULL;
7908 struct tog_tree_view_state *s = &view->state.tree;
7909 char *parent_path;
7911 err = tree_entry_path(&parent_path, &s->parents, NULL);
7912 if (err)
7913 return err;
7915 err = draw_tree_entries(view, parent_path);
7916 free(parent_path);
7918 view_border(view);
7919 return err;
7922 static const struct got_error *
7923 tree_goto_line(struct tog_view *view, int nlines)
7925 const struct got_error *err = NULL;
7926 struct tog_tree_view_state *s = &view->state.tree;
7927 struct got_tree_entry **fte, **lte, **ste;
7928 int g, last, first = 1, i = 1;
7929 int root = s->tree == s->root;
7930 int off = root ? 1 : 2;
7932 g = view->gline;
7933 view->gline = 0;
7935 if (g == 0)
7936 g = 1;
7937 else if (g > got_object_tree_get_nentries(s->tree))
7938 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7940 fte = &s->first_displayed_entry;
7941 lte = &s->last_displayed_entry;
7942 ste = &s->selected_entry;
7944 if (*fte != NULL) {
7945 first = got_tree_entry_get_index(*fte);
7946 first += off; /* account for ".." */
7948 last = got_tree_entry_get_index(*lte);
7949 last += off;
7951 if (g >= first && g <= last && g - first < nlines) {
7952 s->selected = g - first;
7953 return NULL; /* gline is on the current page */
7956 if (*ste != NULL) {
7957 i = got_tree_entry_get_index(*ste);
7958 i += off;
7961 if (i < g) {
7962 err = tree_scroll_down(view, g - i);
7963 if (err)
7964 return err;
7965 if (got_tree_entry_get_index(*lte) >=
7966 got_object_tree_get_nentries(s->tree) - 1 &&
7967 first + s->selected < g &&
7968 s->selected < s->ndisplayed - 1) {
7969 first = got_tree_entry_get_index(*fte);
7970 first += off;
7971 s->selected = g - first;
7973 } else if (i > g)
7974 tree_scroll_up(s, i - g);
7976 if (g < nlines &&
7977 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7978 s->selected = g - 1;
7980 return NULL;
7983 static const struct got_error *
7984 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7986 const struct got_error *err = NULL;
7987 struct tog_tree_view_state *s = &view->state.tree;
7988 struct got_tree_entry *te;
7989 int n, nscroll = view->nlines - 3;
7991 if (view->gline)
7992 return tree_goto_line(view, nscroll);
7994 switch (ch) {
7995 case '0':
7996 case '$':
7997 case KEY_RIGHT:
7998 case 'l':
7999 case KEY_LEFT:
8000 case 'h':
8001 horizontal_scroll_input(view, ch);
8002 break;
8003 case 'i':
8004 s->show_ids = !s->show_ids;
8005 view->count = 0;
8006 break;
8007 case 'L':
8008 view->count = 0;
8009 if (!s->selected_entry)
8010 break;
8011 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8012 break;
8013 case 'R':
8014 view->count = 0;
8015 err = view_request_new(new_view, view, TOG_VIEW_REF);
8016 break;
8017 case 'g':
8018 case '=':
8019 case KEY_HOME:
8020 s->selected = 0;
8021 view->count = 0;
8022 if (s->tree == s->root)
8023 s->first_displayed_entry =
8024 got_object_tree_get_first_entry(s->tree);
8025 else
8026 s->first_displayed_entry = NULL;
8027 break;
8028 case 'G':
8029 case '*':
8030 case KEY_END: {
8031 int eos = view->nlines - 3;
8033 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8034 --eos; /* border */
8035 s->selected = 0;
8036 view->count = 0;
8037 te = got_object_tree_get_last_entry(s->tree);
8038 for (n = 0; n < eos; n++) {
8039 if (te == NULL) {
8040 if (s->tree != s->root) {
8041 s->first_displayed_entry = NULL;
8042 n++;
8044 break;
8046 s->first_displayed_entry = te;
8047 te = got_tree_entry_get_prev(s->tree, te);
8049 if (n > 0)
8050 s->selected = n - 1;
8051 break;
8053 case 'k':
8054 case KEY_UP:
8055 case CTRL('p'):
8056 if (s->selected > 0) {
8057 s->selected--;
8058 break;
8060 tree_scroll_up(s, 1);
8061 if (s->selected_entry == NULL ||
8062 (s->tree == s->root && s->selected_entry ==
8063 got_object_tree_get_first_entry(s->tree)))
8064 view->count = 0;
8065 break;
8066 case CTRL('u'):
8067 case 'u':
8068 nscroll /= 2;
8069 /* FALL THROUGH */
8070 case KEY_PPAGE:
8071 case CTRL('b'):
8072 case 'b':
8073 if (s->tree == s->root) {
8074 if (got_object_tree_get_first_entry(s->tree) ==
8075 s->first_displayed_entry)
8076 s->selected -= MIN(s->selected, nscroll);
8077 } else {
8078 if (s->first_displayed_entry == NULL)
8079 s->selected -= MIN(s->selected, nscroll);
8081 tree_scroll_up(s, MAX(0, nscroll));
8082 if (s->selected_entry == NULL ||
8083 (s->tree == s->root && s->selected_entry ==
8084 got_object_tree_get_first_entry(s->tree)))
8085 view->count = 0;
8086 break;
8087 case 'j':
8088 case KEY_DOWN:
8089 case CTRL('n'):
8090 if (s->selected < s->ndisplayed - 1) {
8091 s->selected++;
8092 break;
8094 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8095 == NULL) {
8096 /* can't scroll any further */
8097 view->count = 0;
8098 break;
8100 tree_scroll_down(view, 1);
8101 break;
8102 case CTRL('d'):
8103 case 'd':
8104 nscroll /= 2;
8105 /* FALL THROUGH */
8106 case KEY_NPAGE:
8107 case CTRL('f'):
8108 case 'f':
8109 case ' ':
8110 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8111 == NULL) {
8112 /* can't scroll any further; move cursor down */
8113 if (s->selected < s->ndisplayed - 1)
8114 s->selected += MIN(nscroll,
8115 s->ndisplayed - s->selected - 1);
8116 else
8117 view->count = 0;
8118 break;
8120 tree_scroll_down(view, nscroll);
8121 break;
8122 case KEY_ENTER:
8123 case '\r':
8124 case KEY_BACKSPACE:
8125 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
8126 struct tog_parent_tree *parent;
8127 /* user selected '..' */
8128 if (s->tree == s->root) {
8129 view->count = 0;
8130 break;
8132 parent = TAILQ_FIRST(&s->parents);
8133 TAILQ_REMOVE(&s->parents, parent,
8134 entry);
8135 got_object_tree_close(s->tree);
8136 s->tree = parent->tree;
8137 s->first_displayed_entry =
8138 parent->first_displayed_entry;
8139 s->selected_entry =
8140 parent->selected_entry;
8141 s->selected = parent->selected;
8142 if (s->selected > view->nlines - 3) {
8143 err = offset_selection_down(view);
8144 if (err)
8145 break;
8147 free(parent);
8148 } else if (S_ISDIR(got_tree_entry_get_mode(
8149 s->selected_entry))) {
8150 struct got_tree_object *subtree;
8151 view->count = 0;
8152 err = got_object_open_as_tree(&subtree, s->repo,
8153 got_tree_entry_get_id(s->selected_entry));
8154 if (err)
8155 break;
8156 err = tree_view_visit_subtree(s, subtree);
8157 if (err) {
8158 got_object_tree_close(subtree);
8159 break;
8161 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
8162 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
8163 break;
8164 case KEY_RESIZE:
8165 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
8166 s->selected = view->nlines - 4;
8167 view->count = 0;
8168 break;
8169 default:
8170 view->count = 0;
8171 break;
8174 return err;
8177 __dead static void
8178 usage_tree(void)
8180 endwin();
8181 fprintf(stderr,
8182 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
8183 getprogname());
8184 exit(1);
8187 static const struct got_error *
8188 cmd_tree(int argc, char *argv[])
8190 const struct got_error *error;
8191 struct got_repository *repo = NULL;
8192 struct got_worktree *worktree = NULL;
8193 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8194 struct got_object_id *commit_id = NULL;
8195 struct got_commit_object *commit = NULL;
8196 const char *commit_id_arg = NULL;
8197 char *keyword_idstr = NULL, *label = NULL;
8198 struct got_reference *ref = NULL;
8199 const char *head_ref_name = NULL;
8200 int ch;
8201 struct tog_view *view;
8202 int *pack_fds = NULL;
8204 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
8205 switch (ch) {
8206 case 'c':
8207 commit_id_arg = optarg;
8208 break;
8209 case 'r':
8210 repo_path = realpath(optarg, NULL);
8211 if (repo_path == NULL)
8212 return got_error_from_errno2("realpath",
8213 optarg);
8214 break;
8215 default:
8216 usage_tree();
8217 /* NOTREACHED */
8221 argc -= optind;
8222 argv += optind;
8224 if (argc > 1)
8225 usage_tree();
8227 error = got_repo_pack_fds_open(&pack_fds);
8228 if (error != NULL)
8229 goto done;
8231 if (repo_path == NULL) {
8232 cwd = getcwd(NULL, 0);
8233 if (cwd == NULL)
8234 return got_error_from_errno("getcwd");
8235 error = got_worktree_open(&worktree, cwd, NULL);
8236 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8237 goto done;
8238 if (worktree)
8239 repo_path =
8240 strdup(got_worktree_get_repo_path(worktree));
8241 else
8242 repo_path = strdup(cwd);
8243 if (repo_path == NULL) {
8244 error = got_error_from_errno("strdup");
8245 goto done;
8249 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8250 if (error != NULL)
8251 goto done;
8253 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8254 repo, worktree);
8255 if (error)
8256 goto done;
8258 init_curses();
8260 error = apply_unveil(got_repo_get_path(repo), NULL);
8261 if (error)
8262 goto done;
8264 error = tog_load_refs(repo, 0);
8265 if (error)
8266 goto done;
8268 if (commit_id_arg == NULL) {
8269 error = got_repo_match_object_id(&commit_id, &label,
8270 worktree ? got_worktree_get_head_ref_name(worktree) :
8271 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8272 if (error)
8273 goto done;
8274 head_ref_name = label;
8275 } else {
8276 error = got_keyword_to_idstr(&keyword_idstr, commit_id_arg,
8277 repo, worktree);
8278 if (error != NULL)
8279 goto done;
8280 if (keyword_idstr != NULL)
8281 commit_id_arg = keyword_idstr;
8283 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8284 if (error == NULL)
8285 head_ref_name = got_ref_get_name(ref);
8286 else if (error->code != GOT_ERR_NOT_REF)
8287 goto done;
8288 error = got_repo_match_object_id(&commit_id, NULL,
8289 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8290 if (error)
8291 goto done;
8294 error = got_object_open_as_commit(&commit, repo, commit_id);
8295 if (error)
8296 goto done;
8298 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8299 if (view == NULL) {
8300 error = got_error_from_errno("view_open");
8301 goto done;
8303 error = open_tree_view(view, commit_id, head_ref_name, repo);
8304 if (error)
8305 goto done;
8306 if (!got_path_is_root_dir(in_repo_path)) {
8307 error = tree_view_walk_path(&view->state.tree, commit,
8308 in_repo_path);
8309 if (error)
8310 goto done;
8313 if (worktree) {
8314 error = set_tog_base_commit(repo, worktree);
8315 if (error != NULL)
8316 goto done;
8318 /* Release work tree lock. */
8319 got_worktree_close(worktree);
8320 worktree = NULL;
8323 error = view_loop(view);
8325 done:
8326 free(tog_base_commit.id);
8327 free(keyword_idstr);
8328 free(repo_path);
8329 free(cwd);
8330 free(commit_id);
8331 free(label);
8332 if (ref)
8333 got_ref_close(ref);
8334 if (worktree != NULL)
8335 got_worktree_close(worktree);
8336 if (repo) {
8337 const struct got_error *close_err = got_repo_close(repo);
8338 if (error == NULL)
8339 error = close_err;
8341 if (pack_fds) {
8342 const struct got_error *pack_err =
8343 got_repo_pack_fds_close(pack_fds);
8344 if (error == NULL)
8345 error = pack_err;
8347 tog_free_refs();
8348 return error;
8351 static const struct got_error *
8352 ref_view_load_refs(struct tog_ref_view_state *s)
8354 struct got_reflist_entry *sre;
8355 struct tog_reflist_entry *re;
8357 s->nrefs = 0;
8358 TAILQ_FOREACH(sre, &tog_refs, entry) {
8359 if (strncmp(got_ref_get_name(sre->ref),
8360 "refs/got/", 9) == 0 &&
8361 strncmp(got_ref_get_name(sre->ref),
8362 "refs/got/backup/", 16) != 0)
8363 continue;
8365 re = malloc(sizeof(*re));
8366 if (re == NULL)
8367 return got_error_from_errno("malloc");
8369 re->ref = got_ref_dup(sre->ref);
8370 if (re->ref == NULL)
8371 return got_error_from_errno("got_ref_dup");
8372 re->idx = s->nrefs++;
8373 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8376 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8377 return NULL;
8380 static void
8381 ref_view_free_refs(struct tog_ref_view_state *s)
8383 struct tog_reflist_entry *re;
8385 while (!TAILQ_EMPTY(&s->refs)) {
8386 re = TAILQ_FIRST(&s->refs);
8387 TAILQ_REMOVE(&s->refs, re, entry);
8388 got_ref_close(re->ref);
8389 free(re);
8393 static const struct got_error *
8394 open_ref_view(struct tog_view *view, struct got_repository *repo)
8396 const struct got_error *err = NULL;
8397 struct tog_ref_view_state *s = &view->state.ref;
8399 s->selected_entry = 0;
8400 s->repo = repo;
8402 TAILQ_INIT(&s->refs);
8403 STAILQ_INIT(&s->colors);
8405 err = ref_view_load_refs(s);
8406 if (err)
8407 goto done;
8409 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8410 err = add_color(&s->colors, "^refs/heads/",
8411 TOG_COLOR_REFS_HEADS,
8412 get_color_value("TOG_COLOR_REFS_HEADS"));
8413 if (err)
8414 goto done;
8416 err = add_color(&s->colors, "^refs/tags/",
8417 TOG_COLOR_REFS_TAGS,
8418 get_color_value("TOG_COLOR_REFS_TAGS"));
8419 if (err)
8420 goto done;
8422 err = add_color(&s->colors, "^refs/remotes/",
8423 TOG_COLOR_REFS_REMOTES,
8424 get_color_value("TOG_COLOR_REFS_REMOTES"));
8425 if (err)
8426 goto done;
8428 err = add_color(&s->colors, "^refs/got/backup/",
8429 TOG_COLOR_REFS_BACKUP,
8430 get_color_value("TOG_COLOR_REFS_BACKUP"));
8431 if (err)
8432 goto done;
8435 view->show = show_ref_view;
8436 view->input = input_ref_view;
8437 view->close = close_ref_view;
8438 view->search_start = search_start_ref_view;
8439 view->search_next = search_next_ref_view;
8440 done:
8441 if (err) {
8442 if (view->close == NULL)
8443 close_ref_view(view);
8444 view_close(view);
8446 return err;
8449 static const struct got_error *
8450 close_ref_view(struct tog_view *view)
8452 struct tog_ref_view_state *s = &view->state.ref;
8454 ref_view_free_refs(s);
8455 free_colors(&s->colors);
8457 return NULL;
8460 static const struct got_error *
8461 resolve_reflist_entry(struct got_object_id **commit_id,
8462 struct tog_reflist_entry *re, struct got_repository *repo)
8464 const struct got_error *err = NULL;
8465 struct got_object_id *obj_id;
8466 struct got_tag_object *tag = NULL;
8467 int obj_type;
8469 *commit_id = NULL;
8471 err = got_ref_resolve(&obj_id, repo, re->ref);
8472 if (err)
8473 return err;
8475 err = got_object_get_type(&obj_type, repo, obj_id);
8476 if (err)
8477 goto done;
8479 switch (obj_type) {
8480 case GOT_OBJ_TYPE_COMMIT:
8481 *commit_id = obj_id;
8482 break;
8483 case GOT_OBJ_TYPE_TAG:
8484 err = got_object_open_as_tag(&tag, repo, obj_id);
8485 if (err)
8486 goto done;
8487 free(obj_id);
8488 err = got_object_get_type(&obj_type, repo,
8489 got_object_tag_get_object_id(tag));
8490 if (err)
8491 goto done;
8492 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8493 err = got_error(GOT_ERR_OBJ_TYPE);
8494 goto done;
8496 *commit_id = got_object_id_dup(
8497 got_object_tag_get_object_id(tag));
8498 if (*commit_id == NULL) {
8499 err = got_error_from_errno("got_object_id_dup");
8500 goto done;
8502 break;
8503 default:
8504 err = got_error(GOT_ERR_OBJ_TYPE);
8505 break;
8508 done:
8509 if (tag)
8510 got_object_tag_close(tag);
8511 if (err) {
8512 free(*commit_id);
8513 *commit_id = NULL;
8515 return err;
8518 static const struct got_error *
8519 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8520 struct tog_reflist_entry *re, struct got_repository *repo)
8522 struct tog_view *log_view;
8523 const struct got_error *err = NULL;
8524 struct got_object_id *commit_id = NULL;
8526 *new_view = NULL;
8528 err = resolve_reflist_entry(&commit_id, re, repo);
8529 if (err) {
8530 if (err->code != GOT_ERR_OBJ_TYPE)
8531 return err;
8532 else
8533 return NULL;
8536 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8537 if (log_view == NULL) {
8538 err = got_error_from_errno("view_open");
8539 goto done;
8542 err = open_log_view(log_view, commit_id, repo,
8543 got_ref_get_name(re->ref), "", 0, NULL);
8544 done:
8545 if (err)
8546 view_close(log_view);
8547 else
8548 *new_view = log_view;
8549 free(commit_id);
8550 return err;
8553 static void
8554 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8556 struct tog_reflist_entry *re;
8557 int i = 0;
8559 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8560 return;
8562 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8563 while (i++ < maxscroll) {
8564 if (re == NULL)
8565 break;
8566 s->first_displayed_entry = re;
8567 re = TAILQ_PREV(re, tog_reflist_head, entry);
8571 static const struct got_error *
8572 ref_scroll_down(struct tog_view *view, int maxscroll)
8574 struct tog_ref_view_state *s = &view->state.ref;
8575 struct tog_reflist_entry *next, *last;
8576 int n = 0;
8578 if (s->first_displayed_entry)
8579 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8580 else
8581 next = TAILQ_FIRST(&s->refs);
8583 last = s->last_displayed_entry;
8584 while (next && n++ < maxscroll) {
8585 if (last) {
8586 s->last_displayed_entry = last;
8587 last = TAILQ_NEXT(last, entry);
8589 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8590 s->first_displayed_entry = next;
8591 next = TAILQ_NEXT(next, entry);
8595 return NULL;
8598 static const struct got_error *
8599 search_start_ref_view(struct tog_view *view)
8601 struct tog_ref_view_state *s = &view->state.ref;
8603 s->matched_entry = NULL;
8604 return NULL;
8607 static int
8608 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8610 regmatch_t regmatch;
8612 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8613 0) == 0;
8616 static const struct got_error *
8617 search_next_ref_view(struct tog_view *view)
8619 struct tog_ref_view_state *s = &view->state.ref;
8620 struct tog_reflist_entry *re = NULL;
8622 if (!view->searching) {
8623 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8624 return NULL;
8627 if (s->matched_entry) {
8628 if (view->searching == TOG_SEARCH_FORWARD) {
8629 if (s->selected_entry)
8630 re = TAILQ_NEXT(s->selected_entry, entry);
8631 else
8632 re = TAILQ_PREV(s->selected_entry,
8633 tog_reflist_head, entry);
8634 } else {
8635 if (s->selected_entry == NULL)
8636 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8637 else
8638 re = TAILQ_PREV(s->selected_entry,
8639 tog_reflist_head, entry);
8641 } else {
8642 if (s->selected_entry)
8643 re = s->selected_entry;
8644 else if (view->searching == TOG_SEARCH_FORWARD)
8645 re = TAILQ_FIRST(&s->refs);
8646 else
8647 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8650 while (1) {
8651 if (re == NULL) {
8652 if (s->matched_entry == NULL) {
8653 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8654 return NULL;
8656 if (view->searching == TOG_SEARCH_FORWARD)
8657 re = TAILQ_FIRST(&s->refs);
8658 else
8659 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8662 if (match_reflist_entry(re, &view->regex)) {
8663 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8664 s->matched_entry = re;
8665 break;
8668 if (view->searching == TOG_SEARCH_FORWARD)
8669 re = TAILQ_NEXT(re, entry);
8670 else
8671 re = TAILQ_PREV(re, tog_reflist_head, entry);
8674 if (s->matched_entry) {
8675 s->first_displayed_entry = s->matched_entry;
8676 s->selected = 0;
8679 return NULL;
8682 static const struct got_error *
8683 show_ref_view(struct tog_view *view)
8685 const struct got_error *err = NULL;
8686 struct tog_ref_view_state *s = &view->state.ref;
8687 struct tog_reflist_entry *re;
8688 char *line = NULL;
8689 wchar_t *wline;
8690 struct tog_color *tc;
8691 int width, n, scrollx;
8692 int limit = view->nlines;
8694 werase(view->window);
8696 s->ndisplayed = 0;
8697 if (view_is_hsplit_top(view))
8698 --limit; /* border */
8700 if (limit == 0)
8701 return NULL;
8703 re = s->first_displayed_entry;
8705 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8706 s->nrefs) == -1)
8707 return got_error_from_errno("asprintf");
8709 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8710 if (err) {
8711 free(line);
8712 return err;
8714 if (view_needs_focus_indication(view))
8715 wstandout(view->window);
8716 waddwstr(view->window, wline);
8717 while (width++ < view->ncols)
8718 waddch(view->window, ' ');
8719 if (view_needs_focus_indication(view))
8720 wstandend(view->window);
8721 free(wline);
8722 wline = NULL;
8723 free(line);
8724 line = NULL;
8725 if (--limit <= 0)
8726 return NULL;
8728 n = 0;
8729 view->maxx = 0;
8730 while (re && limit > 0) {
8731 char *line = NULL;
8732 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8734 if (s->show_date) {
8735 struct got_commit_object *ci;
8736 struct got_tag_object *tag;
8737 struct got_object_id *id;
8738 struct tm tm;
8739 time_t t;
8741 err = got_ref_resolve(&id, s->repo, re->ref);
8742 if (err)
8743 return err;
8744 err = got_object_open_as_tag(&tag, s->repo, id);
8745 if (err) {
8746 if (err->code != GOT_ERR_OBJ_TYPE) {
8747 free(id);
8748 return err;
8750 err = got_object_open_as_commit(&ci, s->repo,
8751 id);
8752 if (err) {
8753 free(id);
8754 return err;
8756 t = got_object_commit_get_committer_time(ci);
8757 got_object_commit_close(ci);
8758 } else {
8759 t = got_object_tag_get_tagger_time(tag);
8760 got_object_tag_close(tag);
8762 free(id);
8763 if (gmtime_r(&t, &tm) == NULL)
8764 return got_error_from_errno("gmtime_r");
8765 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8766 return got_error(GOT_ERR_NO_SPACE);
8768 if (got_ref_is_symbolic(re->ref)) {
8769 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8770 ymd : "", got_ref_get_name(re->ref),
8771 got_ref_get_symref_target(re->ref)) == -1)
8772 return got_error_from_errno("asprintf");
8773 } else if (s->show_ids) {
8774 struct got_object_id *id;
8775 char *id_str;
8776 err = got_ref_resolve(&id, s->repo, re->ref);
8777 if (err)
8778 return err;
8779 err = got_object_id_str(&id_str, id);
8780 if (err) {
8781 free(id);
8782 return err;
8784 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8785 got_ref_get_name(re->ref), id_str) == -1) {
8786 err = got_error_from_errno("asprintf");
8787 free(id);
8788 free(id_str);
8789 return err;
8791 free(id);
8792 free(id_str);
8793 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8794 got_ref_get_name(re->ref)) == -1)
8795 return got_error_from_errno("asprintf");
8797 /* use full line width to determine view->maxx */
8798 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8799 if (err) {
8800 free(line);
8801 return err;
8803 view->maxx = MAX(view->maxx, width);
8804 free(wline);
8805 wline = NULL;
8807 err = format_line(&wline, &width, &scrollx, line, view->x,
8808 view->ncols, 0, 0);
8809 if (err) {
8810 free(line);
8811 return err;
8813 if (n == s->selected) {
8814 if (view->focussed)
8815 wstandout(view->window);
8816 s->selected_entry = re;
8818 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8819 if (tc)
8820 wattr_on(view->window,
8821 COLOR_PAIR(tc->colorpair), NULL);
8822 waddwstr(view->window, &wline[scrollx]);
8823 if (tc)
8824 wattr_off(view->window,
8825 COLOR_PAIR(tc->colorpair), NULL);
8826 if (width < view->ncols)
8827 waddch(view->window, '\n');
8828 if (n == s->selected && view->focussed)
8829 wstandend(view->window);
8830 free(line);
8831 free(wline);
8832 wline = NULL;
8833 n++;
8834 s->ndisplayed++;
8835 s->last_displayed_entry = re;
8837 limit--;
8838 re = TAILQ_NEXT(re, entry);
8841 view_border(view);
8842 return err;
8845 static const struct got_error *
8846 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8847 struct tog_reflist_entry *re, struct got_repository *repo)
8849 const struct got_error *err = NULL;
8850 struct got_object_id *commit_id = NULL;
8851 struct tog_view *tree_view;
8853 *new_view = NULL;
8855 err = resolve_reflist_entry(&commit_id, re, repo);
8856 if (err) {
8857 if (err->code != GOT_ERR_OBJ_TYPE)
8858 return err;
8859 else
8860 return NULL;
8864 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8865 if (tree_view == NULL) {
8866 err = got_error_from_errno("view_open");
8867 goto done;
8870 err = open_tree_view(tree_view, commit_id,
8871 got_ref_get_name(re->ref), repo);
8872 if (err)
8873 goto done;
8875 *new_view = tree_view;
8876 done:
8877 free(commit_id);
8878 return err;
8881 static const struct got_error *
8882 ref_goto_line(struct tog_view *view, int nlines)
8884 const struct got_error *err = NULL;
8885 struct tog_ref_view_state *s = &view->state.ref;
8886 int g, idx = s->selected_entry->idx;
8888 g = view->gline;
8889 view->gline = 0;
8891 if (g == 0)
8892 g = 1;
8893 else if (g > s->nrefs)
8894 g = s->nrefs;
8896 if (g >= s->first_displayed_entry->idx + 1 &&
8897 g <= s->last_displayed_entry->idx + 1 &&
8898 g - s->first_displayed_entry->idx - 1 < nlines) {
8899 s->selected = g - s->first_displayed_entry->idx - 1;
8900 return NULL;
8903 if (idx + 1 < g) {
8904 err = ref_scroll_down(view, g - idx - 1);
8905 if (err)
8906 return err;
8907 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8908 s->first_displayed_entry->idx + s->selected < g &&
8909 s->selected < s->ndisplayed - 1)
8910 s->selected = g - s->first_displayed_entry->idx - 1;
8911 } else if (idx + 1 > g)
8912 ref_scroll_up(s, idx - g + 1);
8914 if (g < nlines && s->first_displayed_entry->idx == 0)
8915 s->selected = g - 1;
8917 return NULL;
8921 static const struct got_error *
8922 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8924 const struct got_error *err = NULL;
8925 struct tog_ref_view_state *s = &view->state.ref;
8926 struct tog_reflist_entry *re;
8927 int n, nscroll = view->nlines - 1;
8929 if (view->gline)
8930 return ref_goto_line(view, nscroll);
8932 switch (ch) {
8933 case '0':
8934 case '$':
8935 case KEY_RIGHT:
8936 case 'l':
8937 case KEY_LEFT:
8938 case 'h':
8939 horizontal_scroll_input(view, ch);
8940 break;
8941 case 'i':
8942 s->show_ids = !s->show_ids;
8943 view->count = 0;
8944 break;
8945 case 'm':
8946 s->show_date = !s->show_date;
8947 view->count = 0;
8948 break;
8949 case 'o':
8950 s->sort_by_date = !s->sort_by_date;
8951 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8952 view->count = 0;
8953 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8954 got_ref_cmp_by_commit_timestamp_descending :
8955 tog_ref_cmp_by_name, s->repo);
8956 if (err)
8957 break;
8958 got_reflist_object_id_map_free(tog_refs_idmap);
8959 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8960 &tog_refs, s->repo);
8961 if (err)
8962 break;
8963 ref_view_free_refs(s);
8964 err = ref_view_load_refs(s);
8965 break;
8966 case KEY_ENTER:
8967 case '\r':
8968 view->count = 0;
8969 if (!s->selected_entry)
8970 break;
8971 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8972 break;
8973 case 'T':
8974 view->count = 0;
8975 if (!s->selected_entry)
8976 break;
8977 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8978 break;
8979 case 'g':
8980 case '=':
8981 case KEY_HOME:
8982 s->selected = 0;
8983 view->count = 0;
8984 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8985 break;
8986 case 'G':
8987 case '*':
8988 case KEY_END: {
8989 int eos = view->nlines - 1;
8991 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8992 --eos; /* border */
8993 s->selected = 0;
8994 view->count = 0;
8995 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8996 for (n = 0; n < eos; n++) {
8997 if (re == NULL)
8998 break;
8999 s->first_displayed_entry = re;
9000 re = TAILQ_PREV(re, tog_reflist_head, entry);
9002 if (n > 0)
9003 s->selected = n - 1;
9004 break;
9006 case 'k':
9007 case KEY_UP:
9008 case CTRL('p'):
9009 if (s->selected > 0) {
9010 s->selected--;
9011 break;
9013 ref_scroll_up(s, 1);
9014 if (s->selected_entry == TAILQ_FIRST(&s->refs))
9015 view->count = 0;
9016 break;
9017 case CTRL('u'):
9018 case 'u':
9019 nscroll /= 2;
9020 /* FALL THROUGH */
9021 case KEY_PPAGE:
9022 case CTRL('b'):
9023 case 'b':
9024 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
9025 s->selected -= MIN(nscroll, s->selected);
9026 ref_scroll_up(s, MAX(0, nscroll));
9027 if (s->selected_entry == TAILQ_FIRST(&s->refs))
9028 view->count = 0;
9029 break;
9030 case 'j':
9031 case KEY_DOWN:
9032 case CTRL('n'):
9033 if (s->selected < s->ndisplayed - 1) {
9034 s->selected++;
9035 break;
9037 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
9038 /* can't scroll any further */
9039 view->count = 0;
9040 break;
9042 ref_scroll_down(view, 1);
9043 break;
9044 case CTRL('d'):
9045 case 'd':
9046 nscroll /= 2;
9047 /* FALL THROUGH */
9048 case KEY_NPAGE:
9049 case CTRL('f'):
9050 case 'f':
9051 case ' ':
9052 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
9053 /* can't scroll any further; move cursor down */
9054 if (s->selected < s->ndisplayed - 1)
9055 s->selected += MIN(nscroll,
9056 s->ndisplayed - s->selected - 1);
9057 if (view->count > 1 && s->selected < s->ndisplayed - 1)
9058 s->selected += s->ndisplayed - s->selected - 1;
9059 view->count = 0;
9060 break;
9062 ref_scroll_down(view, nscroll);
9063 break;
9064 case CTRL('l'):
9065 view->count = 0;
9066 tog_free_refs();
9067 err = tog_load_refs(s->repo, s->sort_by_date);
9068 if (err)
9069 break;
9070 ref_view_free_refs(s);
9071 err = ref_view_load_refs(s);
9072 break;
9073 case KEY_RESIZE:
9074 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
9075 s->selected = view->nlines - 2;
9076 break;
9077 default:
9078 view->count = 0;
9079 break;
9082 return err;
9085 __dead static void
9086 usage_ref(void)
9088 endwin();
9089 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
9090 getprogname());
9091 exit(1);
9094 static const struct got_error *
9095 cmd_ref(int argc, char *argv[])
9097 const struct got_error *error;
9098 struct got_repository *repo = NULL;
9099 struct got_worktree *worktree = NULL;
9100 char *cwd = NULL, *repo_path = NULL;
9101 int ch;
9102 struct tog_view *view;
9103 int *pack_fds = NULL;
9105 while ((ch = getopt(argc, argv, "r:")) != -1) {
9106 switch (ch) {
9107 case 'r':
9108 repo_path = realpath(optarg, NULL);
9109 if (repo_path == NULL)
9110 return got_error_from_errno2("realpath",
9111 optarg);
9112 break;
9113 default:
9114 usage_ref();
9115 /* NOTREACHED */
9119 argc -= optind;
9120 argv += optind;
9122 if (argc > 1)
9123 usage_ref();
9125 error = got_repo_pack_fds_open(&pack_fds);
9126 if (error != NULL)
9127 goto done;
9129 if (repo_path == NULL) {
9130 cwd = getcwd(NULL, 0);
9131 if (cwd == NULL)
9132 return got_error_from_errno("getcwd");
9133 error = got_worktree_open(&worktree, cwd, NULL);
9134 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9135 goto done;
9136 if (worktree)
9137 repo_path =
9138 strdup(got_worktree_get_repo_path(worktree));
9139 else
9140 repo_path = strdup(cwd);
9141 if (repo_path == NULL) {
9142 error = got_error_from_errno("strdup");
9143 goto done;
9147 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9148 if (error != NULL)
9149 goto done;
9151 init_curses();
9153 error = apply_unveil(got_repo_get_path(repo), NULL);
9154 if (error)
9155 goto done;
9157 error = tog_load_refs(repo, 0);
9158 if (error)
9159 goto done;
9161 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
9162 if (view == NULL) {
9163 error = got_error_from_errno("view_open");
9164 goto done;
9167 error = open_ref_view(view, repo);
9168 if (error)
9169 goto done;
9171 if (worktree) {
9172 error = set_tog_base_commit(repo, worktree);
9173 if (error != NULL)
9174 goto done;
9176 /* Release work tree lock. */
9177 got_worktree_close(worktree);
9178 worktree = NULL;
9181 error = view_loop(view);
9183 done:
9184 free(tog_base_commit.id);
9185 free(repo_path);
9186 free(cwd);
9187 if (worktree != NULL)
9188 got_worktree_close(worktree);
9189 if (repo) {
9190 const struct got_error *close_err = got_repo_close(repo);
9191 if (close_err)
9192 error = close_err;
9194 if (pack_fds) {
9195 const struct got_error *pack_err =
9196 got_repo_pack_fds_close(pack_fds);
9197 if (error == NULL)
9198 error = pack_err;
9200 tog_free_refs();
9201 return error;
9204 static const struct got_error*
9205 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
9206 const char *str)
9208 size_t len;
9210 if (win == NULL)
9211 win = stdscr;
9213 len = strlen(str);
9214 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
9216 if (focus)
9217 wstandout(win);
9218 if (mvwprintw(win, y, x, "%s", str) == ERR)
9219 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
9220 if (focus)
9221 wstandend(win);
9223 return NULL;
9226 static const struct got_error *
9227 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
9229 off_t *p;
9231 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
9232 if (p == NULL) {
9233 free(*line_offsets);
9234 *line_offsets = NULL;
9235 return got_error_from_errno("reallocarray");
9238 *line_offsets = p;
9239 (*line_offsets)[*nlines] = off;
9240 ++(*nlines);
9241 return NULL;
9244 static const struct got_error *
9245 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
9247 *ret = 0;
9249 for (;n > 0; --n, ++km) {
9250 char *t0, *t, *k;
9251 size_t len = 1;
9253 if (km->keys == NULL)
9254 continue;
9256 t = t0 = strdup(km->keys);
9257 if (t0 == NULL)
9258 return got_error_from_errno("strdup");
9260 len += strlen(t);
9261 while ((k = strsep(&t, " ")) != NULL)
9262 len += strlen(k) > 1 ? 2 : 0;
9263 free(t0);
9264 *ret = MAX(*ret, len);
9267 return NULL;
9271 * Write keymap section headers, keys, and key info in km to f.
9272 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9273 * wrap control and symbolic keys in guillemets, else use <>.
9275 static const struct got_error *
9276 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9278 int n, len = width;
9280 if (km->keys) {
9281 static const char *u8_glyph[] = {
9282 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9283 "\xe2\x80\xba" /* U+203A (utf8 >) */
9285 char *t0, *t, *k;
9286 int cs, s, first = 1;
9288 cs = got_locale_is_utf8();
9290 t = t0 = strdup(km->keys);
9291 if (t0 == NULL)
9292 return got_error_from_errno("strdup");
9294 len = strlen(km->keys);
9295 while ((k = strsep(&t, " ")) != NULL) {
9296 s = strlen(k) > 1; /* control or symbolic key */
9297 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9298 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9299 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9300 if (n < 0) {
9301 free(t0);
9302 return got_error_from_errno("fprintf");
9304 first = 0;
9305 len += s ? 2 : 0;
9306 *off += n;
9308 free(t0);
9310 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9311 if (n < 0)
9312 return got_error_from_errno("fprintf");
9313 *off += n;
9315 return NULL;
9318 static const struct got_error *
9319 format_help(struct tog_help_view_state *s)
9321 const struct got_error *err = NULL;
9322 off_t off = 0;
9323 int i, max, n, show = s->all;
9324 static const struct tog_key_map km[] = {
9325 #define KEYMAP_(info, type) { NULL, (info), type }
9326 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9327 GENERATE_HELP
9328 #undef KEYMAP_
9329 #undef KEY_
9332 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9333 if (err)
9334 return err;
9336 n = nitems(km);
9337 err = max_key_str(&max, km, n);
9338 if (err)
9339 return err;
9341 for (i = 0; i < n; ++i) {
9342 if (km[i].keys == NULL) {
9343 show = s->all;
9344 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9345 km[i].type == s->type || s->all)
9346 show = 1;
9348 if (show) {
9349 err = format_help_line(&off, s->f, &km[i], max);
9350 if (err)
9351 return err;
9352 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9353 if (err)
9354 return err;
9357 fputc('\n', s->f);
9358 ++off;
9359 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9360 return err;
9363 static const struct got_error *
9364 create_help(struct tog_help_view_state *s)
9366 FILE *f;
9367 const struct got_error *err;
9369 free(s->line_offsets);
9370 s->line_offsets = NULL;
9371 s->nlines = 0;
9373 f = got_opentemp();
9374 if (f == NULL)
9375 return got_error_from_errno("got_opentemp");
9376 s->f = f;
9378 err = format_help(s);
9379 if (err)
9380 return err;
9382 if (s->f && fflush(s->f) != 0)
9383 return got_error_from_errno("fflush");
9385 return NULL;
9388 static const struct got_error *
9389 search_start_help_view(struct tog_view *view)
9391 view->state.help.matched_line = 0;
9392 return NULL;
9395 static void
9396 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9397 size_t *nlines, int **first, int **last, int **match, int **selected)
9399 struct tog_help_view_state *s = &view->state.help;
9401 *f = s->f;
9402 *nlines = s->nlines;
9403 *line_offsets = s->line_offsets;
9404 *match = &s->matched_line;
9405 *first = &s->first_displayed_line;
9406 *last = &s->last_displayed_line;
9407 *selected = &s->selected_line;
9410 static const struct got_error *
9411 show_help_view(struct tog_view *view)
9413 struct tog_help_view_state *s = &view->state.help;
9414 const struct got_error *err;
9415 regmatch_t *regmatch = &view->regmatch;
9416 wchar_t *wline;
9417 char *line;
9418 ssize_t linelen;
9419 size_t linesz = 0;
9420 int width, nprinted = 0, rc = 0;
9421 int eos = view->nlines;
9423 if (view_is_hsplit_top(view))
9424 --eos; /* account for border */
9426 s->lineno = 0;
9427 rewind(s->f);
9428 werase(view->window);
9430 if (view->gline > s->nlines - 1)
9431 view->gline = s->nlines - 1;
9433 err = win_draw_center(view->window, 0, 0, view->ncols,
9434 view_needs_focus_indication(view),
9435 "tog help (press q to return to tog)");
9436 if (err)
9437 return err;
9438 if (eos <= 1)
9439 return NULL;
9440 waddstr(view->window, "\n\n");
9441 eos -= 2;
9443 s->eof = 0;
9444 view->maxx = 0;
9445 line = NULL;
9446 while (eos > 0 && nprinted < eos) {
9447 attr_t attr = 0;
9449 linelen = getline(&line, &linesz, s->f);
9450 if (linelen == -1) {
9451 if (!feof(s->f)) {
9452 free(line);
9453 return got_ferror(s->f, GOT_ERR_IO);
9455 s->eof = 1;
9456 break;
9458 if (++s->lineno < s->first_displayed_line)
9459 continue;
9460 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9461 continue;
9462 if (s->lineno == view->hiline)
9463 attr = A_STANDOUT;
9465 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9466 view->x ? 1 : 0);
9467 if (err) {
9468 free(line);
9469 return err;
9471 view->maxx = MAX(view->maxx, width);
9472 free(wline);
9473 wline = NULL;
9475 if (attr)
9476 wattron(view->window, attr);
9477 if (s->first_displayed_line + nprinted == s->matched_line &&
9478 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9479 err = add_matched_line(&width, line, view->ncols - 1, 0,
9480 view->window, view->x, regmatch);
9481 if (err) {
9482 free(line);
9483 return err;
9485 } else {
9486 int skip;
9488 err = format_line(&wline, &width, &skip, line,
9489 view->x, view->ncols, 0, view->x ? 1 : 0);
9490 if (err) {
9491 free(line);
9492 return err;
9494 waddwstr(view->window, &wline[skip]);
9495 free(wline);
9496 wline = NULL;
9498 if (s->lineno == view->hiline) {
9499 while (width++ < view->ncols)
9500 waddch(view->window, ' ');
9501 } else {
9502 if (width < view->ncols)
9503 waddch(view->window, '\n');
9505 if (attr)
9506 wattroff(view->window, attr);
9507 if (++nprinted == 1)
9508 s->first_displayed_line = s->lineno;
9510 free(line);
9511 if (nprinted > 0)
9512 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9513 else
9514 s->last_displayed_line = s->first_displayed_line;
9516 view_border(view);
9518 if (s->eof) {
9519 rc = waddnstr(view->window,
9520 "See the tog(1) manual page for full documentation",
9521 view->ncols - 1);
9522 if (rc == ERR)
9523 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9524 } else {
9525 wmove(view->window, view->nlines - 1, 0);
9526 wclrtoeol(view->window);
9527 wstandout(view->window);
9528 rc = waddnstr(view->window, "scroll down for more...",
9529 view->ncols - 1);
9530 if (rc == ERR)
9531 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9532 if (getcurx(view->window) < view->ncols - 6) {
9533 rc = wprintw(view->window, "[%.0f%%]",
9534 100.00 * s->last_displayed_line / s->nlines);
9535 if (rc == ERR)
9536 return got_error_msg(GOT_ERR_IO, "wprintw");
9538 wstandend(view->window);
9541 return NULL;
9544 static const struct got_error *
9545 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9547 struct tog_help_view_state *s = &view->state.help;
9548 const struct got_error *err = NULL;
9549 char *line = NULL;
9550 ssize_t linelen;
9551 size_t linesz = 0;
9552 int eos, nscroll;
9554 eos = nscroll = view->nlines;
9555 if (view_is_hsplit_top(view))
9556 --eos; /* border */
9558 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9560 switch (ch) {
9561 case '0':
9562 case '$':
9563 case KEY_RIGHT:
9564 case 'l':
9565 case KEY_LEFT:
9566 case 'h':
9567 horizontal_scroll_input(view, ch);
9568 break;
9569 case 'g':
9570 case KEY_HOME:
9571 s->first_displayed_line = 1;
9572 view->count = 0;
9573 break;
9574 case 'G':
9575 case KEY_END:
9576 view->count = 0;
9577 if (s->eof)
9578 break;
9579 s->first_displayed_line = (s->nlines - eos) + 3;
9580 s->eof = 1;
9581 break;
9582 case 'k':
9583 case KEY_UP:
9584 if (s->first_displayed_line > 1)
9585 --s->first_displayed_line;
9586 else
9587 view->count = 0;
9588 break;
9589 case CTRL('u'):
9590 case 'u':
9591 nscroll /= 2;
9592 /* FALL THROUGH */
9593 case KEY_PPAGE:
9594 case CTRL('b'):
9595 case 'b':
9596 if (s->first_displayed_line == 1) {
9597 view->count = 0;
9598 break;
9600 while (--nscroll > 0 && s->first_displayed_line > 1)
9601 s->first_displayed_line--;
9602 break;
9603 case 'j':
9604 case KEY_DOWN:
9605 case CTRL('n'):
9606 if (!s->eof)
9607 ++s->first_displayed_line;
9608 else
9609 view->count = 0;
9610 break;
9611 case CTRL('d'):
9612 case 'd':
9613 nscroll /= 2;
9614 /* FALL THROUGH */
9615 case KEY_NPAGE:
9616 case CTRL('f'):
9617 case 'f':
9618 case ' ':
9619 if (s->eof) {
9620 view->count = 0;
9621 break;
9623 while (!s->eof && --nscroll > 0) {
9624 linelen = getline(&line, &linesz, s->f);
9625 s->first_displayed_line++;
9626 if (linelen == -1) {
9627 if (feof(s->f))
9628 s->eof = 1;
9629 else
9630 err = got_ferror(s->f, GOT_ERR_IO);
9631 break;
9634 free(line);
9635 break;
9636 default:
9637 view->count = 0;
9638 break;
9641 return err;
9644 static const struct got_error *
9645 close_help_view(struct tog_view *view)
9647 struct tog_help_view_state *s = &view->state.help;
9649 free(s->line_offsets);
9650 s->line_offsets = NULL;
9651 if (fclose(s->f) == EOF)
9652 return got_error_from_errno("fclose");
9654 return NULL;
9657 static const struct got_error *
9658 reset_help_view(struct tog_view *view)
9660 struct tog_help_view_state *s = &view->state.help;
9663 if (s->f && fclose(s->f) == EOF)
9664 return got_error_from_errno("fclose");
9666 wclear(view->window);
9667 view->count = 0;
9668 view->x = 0;
9669 s->all = !s->all;
9670 s->first_displayed_line = 1;
9671 s->last_displayed_line = view->nlines;
9672 s->matched_line = 0;
9674 return create_help(s);
9677 static const struct got_error *
9678 open_help_view(struct tog_view *view, struct tog_view *parent)
9680 const struct got_error *err = NULL;
9681 struct tog_help_view_state *s = &view->state.help;
9683 s->type = (enum tog_keymap_type)parent->type;
9684 s->first_displayed_line = 1;
9685 s->last_displayed_line = view->nlines;
9686 s->selected_line = 1;
9688 view->show = show_help_view;
9689 view->input = input_help_view;
9690 view->reset = reset_help_view;
9691 view->close = close_help_view;
9692 view->search_start = search_start_help_view;
9693 view->search_setup = search_setup_help_view;
9694 view->search_next = search_next_view_match;
9696 err = create_help(s);
9697 return err;
9700 static const struct got_error *
9701 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9702 enum tog_view_type request, int y, int x)
9704 const struct got_error *err = NULL;
9706 *new_view = NULL;
9708 switch (request) {
9709 case TOG_VIEW_DIFF:
9710 if (view->type == TOG_VIEW_LOG) {
9711 struct tog_log_view_state *s = &view->state.log;
9713 err = open_diff_view_for_commit(new_view, y, x,
9714 s->selected_entry->commit, s->selected_entry->id,
9715 view, s->repo);
9716 } else
9717 return got_error_msg(GOT_ERR_NOT_IMPL,
9718 "parent/child view pair not supported");
9719 break;
9720 case TOG_VIEW_BLAME:
9721 if (view->type == TOG_VIEW_TREE) {
9722 struct tog_tree_view_state *s = &view->state.tree;
9724 err = blame_tree_entry(new_view, y, x,
9725 s->selected_entry, &s->parents, s->commit_id,
9726 s->repo);
9727 } else
9728 return got_error_msg(GOT_ERR_NOT_IMPL,
9729 "parent/child view pair not supported");
9730 break;
9731 case TOG_VIEW_LOG:
9732 if (view->type == TOG_VIEW_BLAME)
9733 err = log_annotated_line(new_view, y, x,
9734 view->state.blame.repo, view->state.blame.id_to_log);
9735 else if (view->type == TOG_VIEW_TREE)
9736 err = log_selected_tree_entry(new_view, y, x,
9737 &view->state.tree);
9738 else if (view->type == TOG_VIEW_REF)
9739 err = log_ref_entry(new_view, y, x,
9740 view->state.ref.selected_entry,
9741 view->state.ref.repo);
9742 else
9743 return got_error_msg(GOT_ERR_NOT_IMPL,
9744 "parent/child view pair not supported");
9745 break;
9746 case TOG_VIEW_TREE:
9747 if (view->type == TOG_VIEW_LOG)
9748 err = browse_commit_tree(new_view, y, x,
9749 view->state.log.selected_entry,
9750 view->state.log.in_repo_path,
9751 view->state.log.head_ref_name,
9752 view->state.log.repo);
9753 else if (view->type == TOG_VIEW_REF)
9754 err = browse_ref_tree(new_view, y, x,
9755 view->state.ref.selected_entry,
9756 view->state.ref.repo);
9757 else
9758 return got_error_msg(GOT_ERR_NOT_IMPL,
9759 "parent/child view pair not supported");
9760 break;
9761 case TOG_VIEW_REF:
9762 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9763 if (*new_view == NULL)
9764 return got_error_from_errno("view_open");
9765 if (view->type == TOG_VIEW_LOG)
9766 err = open_ref_view(*new_view, view->state.log.repo);
9767 else if (view->type == TOG_VIEW_TREE)
9768 err = open_ref_view(*new_view, view->state.tree.repo);
9769 else
9770 err = got_error_msg(GOT_ERR_NOT_IMPL,
9771 "parent/child view pair not supported");
9772 if (err)
9773 view_close(*new_view);
9774 break;
9775 case TOG_VIEW_HELP:
9776 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9777 if (*new_view == NULL)
9778 return got_error_from_errno("view_open");
9779 err = open_help_view(*new_view, view);
9780 if (err)
9781 view_close(*new_view);
9782 break;
9783 default:
9784 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9787 return err;
9791 * If view was scrolled down to move the selected line into view when opening a
9792 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9794 static void
9795 offset_selection_up(struct tog_view *view)
9797 switch (view->type) {
9798 case TOG_VIEW_BLAME: {
9799 struct tog_blame_view_state *s = &view->state.blame;
9800 if (s->first_displayed_line == 1) {
9801 s->selected_line = MAX(s->selected_line - view->offset,
9802 1);
9803 break;
9805 if (s->first_displayed_line > view->offset)
9806 s->first_displayed_line -= view->offset;
9807 else
9808 s->first_displayed_line = 1;
9809 s->selected_line += view->offset;
9810 break;
9812 case TOG_VIEW_LOG:
9813 log_scroll_up(&view->state.log, view->offset);
9814 view->state.log.selected += view->offset;
9815 break;
9816 case TOG_VIEW_REF:
9817 ref_scroll_up(&view->state.ref, view->offset);
9818 view->state.ref.selected += view->offset;
9819 break;
9820 case TOG_VIEW_TREE:
9821 tree_scroll_up(&view->state.tree, view->offset);
9822 view->state.tree.selected += view->offset;
9823 break;
9824 default:
9825 break;
9828 view->offset = 0;
9832 * If the selected line is in the section of screen covered by the bottom split,
9833 * scroll down offset lines to move it into view and index its new position.
9835 static const struct got_error *
9836 offset_selection_down(struct tog_view *view)
9838 const struct got_error *err = NULL;
9839 const struct got_error *(*scrolld)(struct tog_view *, int);
9840 int *selected = NULL;
9841 int header, offset;
9843 switch (view->type) {
9844 case TOG_VIEW_BLAME: {
9845 struct tog_blame_view_state *s = &view->state.blame;
9846 header = 3;
9847 scrolld = NULL;
9848 if (s->selected_line > view->nlines - header) {
9849 offset = abs(view->nlines - s->selected_line - header);
9850 s->first_displayed_line += offset;
9851 s->selected_line -= offset;
9852 view->offset = offset;
9854 break;
9856 case TOG_VIEW_LOG: {
9857 struct tog_log_view_state *s = &view->state.log;
9858 scrolld = &log_scroll_down;
9859 header = view_is_parent_view(view) ? 3 : 2;
9860 selected = &s->selected;
9861 break;
9863 case TOG_VIEW_REF: {
9864 struct tog_ref_view_state *s = &view->state.ref;
9865 scrolld = &ref_scroll_down;
9866 header = 3;
9867 selected = &s->selected;
9868 break;
9870 case TOG_VIEW_TREE: {
9871 struct tog_tree_view_state *s = &view->state.tree;
9872 scrolld = &tree_scroll_down;
9873 header = 5;
9874 selected = &s->selected;
9875 break;
9877 default:
9878 selected = NULL;
9879 scrolld = NULL;
9880 header = 0;
9881 break;
9884 if (selected && *selected > view->nlines - header) {
9885 offset = abs(view->nlines - *selected - header);
9886 view->offset = offset;
9887 if (scrolld && offset) {
9888 err = scrolld(view, offset);
9889 *selected -= offset;
9893 return err;
9896 static void
9897 list_commands(FILE *fp)
9899 size_t i;
9901 fprintf(fp, "commands:");
9902 for (i = 0; i < nitems(tog_commands); i++) {
9903 const struct tog_cmd *cmd = &tog_commands[i];
9904 fprintf(fp, " %s", cmd->name);
9906 fputc('\n', fp);
9909 __dead static void
9910 usage(int hflag, int status)
9912 FILE *fp = (status == 0) ? stdout : stderr;
9914 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9915 getprogname());
9916 if (hflag) {
9917 fprintf(fp, "lazy usage: %s path\n", getprogname());
9918 list_commands(fp);
9920 exit(status);
9923 static char **
9924 make_argv(int argc, ...)
9926 va_list ap;
9927 char **argv;
9928 int i;
9930 va_start(ap, argc);
9932 argv = calloc(argc, sizeof(char *));
9933 if (argv == NULL)
9934 err(1, "calloc");
9935 for (i = 0; i < argc; i++) {
9936 argv[i] = strdup(va_arg(ap, char *));
9937 if (argv[i] == NULL)
9938 err(1, "strdup");
9941 va_end(ap);
9942 return argv;
9946 * Try to convert 'tog path' into a 'tog log path' command.
9947 * The user could simply have mistyped the command rather than knowingly
9948 * provided a path. So check whether argv[0] can in fact be resolved
9949 * to a path in the HEAD commit and print a special error if not.
9950 * This hack is for mpi@ <3
9952 static const struct got_error *
9953 tog_log_with_path(int argc, char *argv[])
9955 const struct got_error *error = NULL, *close_err;
9956 const struct tog_cmd *cmd = NULL;
9957 struct got_repository *repo = NULL;
9958 struct got_worktree *worktree = NULL;
9959 struct got_object_id *commit_id = NULL, *id = NULL;
9960 struct got_commit_object *commit = NULL;
9961 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9962 char *commit_id_str = NULL, **cmd_argv = NULL;
9963 int *pack_fds = NULL;
9965 cwd = getcwd(NULL, 0);
9966 if (cwd == NULL)
9967 return got_error_from_errno("getcwd");
9969 error = got_repo_pack_fds_open(&pack_fds);
9970 if (error != NULL)
9971 goto done;
9973 error = got_worktree_open(&worktree, cwd, NULL);
9974 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9975 goto done;
9977 if (worktree)
9978 repo_path = strdup(got_worktree_get_repo_path(worktree));
9979 else
9980 repo_path = strdup(cwd);
9981 if (repo_path == NULL) {
9982 error = got_error_from_errno("strdup");
9983 goto done;
9986 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9987 if (error != NULL)
9988 goto done;
9990 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9991 repo, worktree);
9992 if (error)
9993 goto done;
9995 error = tog_load_refs(repo, 0);
9996 if (error)
9997 goto done;
9998 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9999 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
10000 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
10001 if (error)
10002 goto done;
10004 if (worktree) {
10005 got_worktree_close(worktree);
10006 worktree = NULL;
10009 error = got_object_open_as_commit(&commit, repo, commit_id);
10010 if (error)
10011 goto done;
10013 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
10014 if (error) {
10015 if (error->code != GOT_ERR_NO_TREE_ENTRY)
10016 goto done;
10017 fprintf(stderr, "%s: '%s' is no known command or path\n",
10018 getprogname(), argv[0]);
10019 usage(1, 1);
10020 /* not reached */
10023 error = got_object_id_str(&commit_id_str, commit_id);
10024 if (error)
10025 goto done;
10027 cmd = &tog_commands[0]; /* log */
10028 argc = 4;
10029 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
10030 error = cmd->cmd_main(argc, cmd_argv);
10031 done:
10032 if (repo) {
10033 close_err = got_repo_close(repo);
10034 if (error == NULL)
10035 error = close_err;
10037 if (commit)
10038 got_object_commit_close(commit);
10039 if (worktree)
10040 got_worktree_close(worktree);
10041 if (pack_fds) {
10042 const struct got_error *pack_err =
10043 got_repo_pack_fds_close(pack_fds);
10044 if (error == NULL)
10045 error = pack_err;
10047 free(id);
10048 free(commit_id_str);
10049 free(commit_id);
10050 free(cwd);
10051 free(repo_path);
10052 free(in_repo_path);
10053 if (cmd_argv) {
10054 int i;
10055 for (i = 0; i < argc; i++)
10056 free(cmd_argv[i]);
10057 free(cmd_argv);
10059 tog_free_refs();
10060 return error;
10063 int
10064 main(int argc, char *argv[])
10066 const struct got_error *io_err, *error = NULL;
10067 const struct tog_cmd *cmd = NULL;
10068 int ch, hflag = 0, Vflag = 0;
10069 char **cmd_argv = NULL;
10070 static const struct option longopts[] = {
10071 { "version", no_argument, NULL, 'V' },
10072 { NULL, 0, NULL, 0}
10074 char *diff_algo_str = NULL;
10075 const char *test_script_path;
10077 setlocale(LC_CTYPE, "");
10080 * Override default signal handlers before starting ncurses.
10081 * This should prevent ncurses from installing its own
10082 * broken cleanup() signal handler.
10084 signal(SIGWINCH, tog_sigwinch);
10085 signal(SIGPIPE, tog_sigpipe);
10086 signal(SIGCONT, tog_sigcont);
10087 signal(SIGINT, tog_sigint);
10088 signal(SIGTERM, tog_sigterm);
10091 * Test mode init must happen before pledge() because "tty" will
10092 * not allow TTY-related ioctls to occur via regular files.
10094 test_script_path = getenv("TOG_TEST_SCRIPT");
10095 if (test_script_path != NULL) {
10096 error = init_mock_term(test_script_path);
10097 if (error) {
10098 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10099 return 1;
10101 } else if (!isatty(STDIN_FILENO))
10102 errx(1, "standard input is not a tty");
10104 #if !defined(PROFILE)
10105 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
10106 NULL) == -1)
10107 err(1, "pledge");
10108 #endif
10110 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
10111 switch (ch) {
10112 case 'h':
10113 hflag = 1;
10114 break;
10115 case 'V':
10116 Vflag = 1;
10117 break;
10118 default:
10119 usage(hflag, 1);
10120 /* NOTREACHED */
10124 argc -= optind;
10125 argv += optind;
10126 optind = 1;
10127 optreset = 1;
10129 if (Vflag) {
10130 got_version_print_str();
10131 return 0;
10134 if (argc == 0) {
10135 if (hflag)
10136 usage(hflag, 0);
10137 /* Build an argument vector which runs a default command. */
10138 cmd = &tog_commands[0];
10139 argc = 1;
10140 cmd_argv = make_argv(argc, cmd->name);
10141 } else {
10142 size_t i;
10144 /* Did the user specify a command? */
10145 for (i = 0; i < nitems(tog_commands); i++) {
10146 if (strncmp(tog_commands[i].name, argv[0],
10147 strlen(argv[0])) == 0) {
10148 cmd = &tog_commands[i];
10149 break;
10154 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
10155 if (diff_algo_str) {
10156 if (strcasecmp(diff_algo_str, "patience") == 0)
10157 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
10158 if (strcasecmp(diff_algo_str, "myers") == 0)
10159 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
10162 tog_base_commit.idx = -1;
10163 tog_base_commit.marker = GOT_WORKTREE_STATE_UNKNOWN;
10165 if (cmd == NULL) {
10166 if (argc != 1)
10167 usage(0, 1);
10168 /* No command specified; try log with a path */
10169 error = tog_log_with_path(argc, argv);
10170 } else {
10171 if (hflag)
10172 cmd->cmd_usage();
10173 else
10174 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
10177 if (using_mock_io) {
10178 io_err = tog_io_close();
10179 if (error == NULL)
10180 error = io_err;
10182 endwin();
10183 if (cmd_argv) {
10184 int i;
10185 for (i = 0; i < argc; i++)
10186 free(cmd_argv[i]);
10187 free(cmd_argv);
10190 if (error && error->code != GOT_ERR_CANCELLED &&
10191 error->code != GOT_ERR_EOF &&
10192 error->code != GOT_ERR_PRIVSEP_EXIT &&
10193 error->code != GOT_ERR_PRIVSEP_PIPE &&
10194 !(error->code == GOT_ERR_ERRNO && errno == EINTR)) {
10195 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10196 return 1;
10198 return 0;